gnus-html.el (gnus-html-put-image): Register a displayer.
[gnus] / lisp / gnus-html.el
1 ;;; gnus-html.el --- Render HTML in a buffer.
2
3 ;; Copyright (C) 2010-2011  Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: html, web
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; The idea is to provide a simple, fast and pretty minimal way to
26 ;; render HTML (including links and images) in a buffer, based on an
27 ;; external HTML renderer (i.e., w3m).
28
29 ;;; Code:
30
31 (eval-when-compile (require 'cl))
32
33 (require 'gnus-art)
34 (eval-when-compile (require 'mm-decode))
35
36 (require 'mm-url)
37 (require 'url)
38 (require 'url-cache)
39 (require 'xml)
40 (require 'browse-url)
41 (eval-and-compile (unless (featurep 'xemacs) (require 'help-fns)))
42
43 (defcustom gnus-html-image-cache-ttl (days-to-time 7)
44   "Time used to determine if we should use images from the cache."
45   :version "24.1"
46   :group 'gnus-art
47   :type 'integer)
48
49 (defcustom gnus-html-image-automatic-caching t
50   "Whether automatically cache retrieve images."
51   :version "24.1"
52   :group 'gnus-art
53   :type 'boolean)
54
55 (defcustom gnus-html-frame-width 70
56   "What width to use when rendering HTML."
57   :version "24.1"
58   :group 'gnus-art
59   :type 'integer)
60
61 (defcustom gnus-max-image-proportion 0.9
62   "How big pictures displayed are in relation to the window they're in.
63 A value of 0.7 means that they are allowed to take up 70% of the
64 width and height of the window.  If they are larger than this,
65 and Emacs supports it, then the images will be rescaled down to
66 fit these criteria."
67   :version "24.1"
68   :group 'gnus-art
69   :type 'float)
70
71 (defvar gnus-html-image-map
72   (let ((map (make-sparse-keymap)))
73     (define-key map "u" 'gnus-article-copy-string)
74     (define-key map "i" 'gnus-html-insert-image)
75     (define-key map "v" 'gnus-html-browse-url)
76     map))
77
78 (defvar gnus-html-displayed-image-map
79   (let ((map (make-sparse-keymap)))
80     (define-key map "a" 'gnus-html-show-alt-text)
81     (define-key map "i" 'gnus-html-browse-image)
82     (define-key map "\r" 'gnus-html-browse-url)
83     (define-key map "u" 'gnus-article-copy-string)
84     (define-key map [tab] 'widget-forward)
85     map))
86
87 (eval-and-compile
88   (defalias 'gnus-html-encode-url-chars
89     (if (fboundp 'browse-url-url-encode-chars)
90         'browse-url-url-encode-chars
91       (lambda (text chars)
92         "URL-encode the chars in TEXT that match CHARS.
93 CHARS is a regexp-like character alternative (e.g., \"[)$]\")."
94         (let ((encoded-text (copy-sequence text))
95               (s 0))
96           (while (setq s (string-match chars encoded-text s))
97             (setq encoded-text
98                   (replace-match (format "%%%x"
99                                          (string-to-char
100                                           (match-string 0 encoded-text)))
101                                  t t encoded-text)
102                   s (1+ s)))
103           encoded-text)))))
104
105 (defun gnus-html-encode-url (url)
106   "Encode URL."
107   (gnus-html-encode-url-chars url "[)$ ]"))
108
109 (defun gnus-html-cache-expired (url ttl)
110   "Check if URL is cached for more than TTL."
111   (cond (url-standalone-mode
112          (not (file-exists-p (url-cache-create-filename url))))
113         (t (let ((cache-time (url-is-cached url)))
114              (if cache-time
115                  (time-less-p
116                   (time-add
117                    cache-time
118                    ttl)
119                   (current-time))
120                t)))))
121
122 ;;;###autoload
123 (defun gnus-article-html (&optional handle)
124   (let ((article-buffer (current-buffer)))
125     (unless handle
126       (setq handle (mm-dissect-buffer t)))
127     (save-restriction
128       (narrow-to-region (point) (point))
129       (save-excursion
130         (mm-with-part handle
131           (let* ((coding-system-for-read 'utf-8)
132                  (coding-system-for-write 'utf-8)
133                  (default-process-coding-system
134                    (cons coding-system-for-read coding-system-for-write))
135                  (charset (mail-content-type-get (mm-handle-type handle)
136                                                  'charset)))
137             (when (and charset
138                        (setq charset (mm-charset-to-coding-system charset))
139                        (not (eq charset 'ascii)))
140               (insert (prog1
141                           (mm-decode-coding-string (buffer-string) charset)
142                         (erase-buffer)
143                         (mm-enable-multibyte))))
144             (call-process-region (point-min) (point-max)
145                                  "w3m"
146                                  nil article-buffer nil
147                                  "-halfdump"
148                                  "-no-cookie"
149                                  "-I" "UTF-8"
150                                  "-O" "UTF-8"
151                                  "-o" "ext_halfdump=1"
152                                  "-o" "display_ins_del=2"
153                                  "-o" "pre_conv=1"
154                                  "-t" (format "%s" tab-width)
155                                  "-cols" (format "%s" gnus-html-frame-width)
156                                  "-o" "display_image=on"
157                                  "-T" "text/html"))))
158       (gnus-html-wash-tags))))
159
160 (defvar gnus-article-mouse-face)
161
162 (defun gnus-html-pre-wash ()
163   (goto-char (point-min))
164   (while (re-search-forward " *<pre_int> *</pre_int> *\n" nil t)
165     (replace-match "" t t))
166   (goto-char (point-min))
167   (while (re-search-forward "<a name[^\n>]+>" nil t)
168     (replace-match "" t t)))
169
170 (defun gnus-html-wash-images ()
171   "Run through current buffer and replace img tags by images."
172   (let (tag parameters string start end images url alt-text
173             inhibit-images blocked-images)
174     (if (buffer-live-p gnus-summary-buffer)
175         (with-current-buffer gnus-summary-buffer
176           (setq inhibit-images gnus-inhibit-images
177                 blocked-images (gnus-blocked-images)))
178       (setq inhibit-images gnus-inhibit-images
179             blocked-images (gnus-blocked-images)))
180     (goto-char (point-min))
181     ;; Search for all the images first.
182     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
183       (setq parameters (match-string 1)
184             start (match-beginning 0))
185       (delete-region start (point))
186       (when (search-forward "</img_alt>" (line-end-position) t)
187         (delete-region (match-beginning 0) (match-end 0)))
188       (setq end (point))
189       (when (string-match "src=\"\\([^\"]+\\)" parameters)
190         (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
191         (setq url (gnus-html-encode-url (match-string 1 parameters))
192               alt-text (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
193                                            parameters)
194                          (xml-substitute-special (match-string 2 parameters))))
195         (gnus-add-text-properties
196          start end
197          (list 'image-url url
198                'image-displayer `(lambda (url start end)
199                                    (gnus-html-display-image url start end
200                                                             ,alt-text))
201                'gnus-image (list url start end alt-text)))
202         (widget-convert-button
203          'url-link start (point)
204          :help-echo alt-text
205          :keymap gnus-html-image-map
206          url)
207         (if (string-match "\\`cid:" url)
208             ;; URLs with cid: have their content stashed in other
209             ;; parts of the MIME structure, so just insert them
210             ;; immediately.
211             (let* ((handle (mm-get-content-id (substring url (match-end 0))))
212                    (image (when (and handle
213                                      (not inhibit-images))
214                             (gnus-create-image
215                              (mm-with-part handle (buffer-string))
216                              nil t))))
217               (if image
218                   (gnus-add-image
219                    'cid
220                    (gnus-put-image
221                     (gnus-rescale-image
222                      image (gnus-html-maximum-image-size))
223                     (gnus-string-or (prog1
224                                         (buffer-substring start end)
225                                       (delete-region start end))
226                                     "*")
227                     'cid))
228                 (widget-convert-button
229                  'link start end
230                  :action 'gnus-html-insert-image
231                  :help-echo url
232                  :keymap gnus-html-image-map
233                  :button-keymap gnus-html-image-map)))
234           ;; Normal, external URL.
235           (if (or inhibit-images
236                   (gnus-html-image-url-blocked-p url blocked-images))
237               (widget-convert-button
238                'link start end
239                :action 'gnus-html-insert-image
240                :help-echo url
241                :keymap gnus-html-image-map
242                :button-keymap gnus-html-image-map)
243             ;; Non-blocked url
244             (let ((width
245                    (when (string-match "width=\"?\\([0-9]+\\)" parameters)
246                      (string-to-number (match-string 1 parameters))))
247                   (height
248                    (when (string-match "height=\"?\\([0-9]+\\)" parameters)
249                      (string-to-number (match-string 1 parameters)))))
250               ;; Don't fetch images that are really small.  They're
251               ;; probably tracking pictures.
252               (when (and (or (null height)
253                              (> height 4))
254                          (or (null width)
255                              (> width 4)))
256                 (gnus-html-display-image url start end alt-text)))))))))
257
258 (defun gnus-html-display-image (url start end &optional alt-text)
259   "Display image at URL on text from START to END.
260 Use ALT-TEXT for the image string."
261   (or alt-text (setq alt-text "*"))
262   (if (string-match "\\`cid:" url)
263       (let ((handle (mm-get-content-id (substring url (match-end 0)))))
264         (when handle
265           (gnus-html-put-image (mm-with-part handle (buffer-string))
266                                url alt-text)))
267     (if (gnus-html-cache-expired url gnus-html-image-cache-ttl)
268         ;; We don't have it, so schedule it for fetching
269         ;; asynchronously.
270         (gnus-html-schedule-image-fetching
271          (current-buffer)
272          (list url alt-text))
273       ;; It's already cached, so just insert it.
274       (gnus-html-put-image (gnus-html-get-image-data url) url alt-text))))
275
276 (defun gnus-html-wash-tags ()
277   (let (tag parameters string start end images url)
278     (gnus-html-pre-wash)
279     (gnus-html-wash-images)
280
281     (goto-char (point-min))
282     ;; Then do the other tags.
283     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
284       (setq tag (match-string 1)
285             parameters (match-string 2)
286             start (match-beginning 0))
287       (when (> (length parameters) 0)
288         (set-text-properties 0 (1- (length parameters)) nil parameters))
289       (delete-region start (point))
290       (when (search-forward (concat "</" tag ">") nil t)
291         (delete-region (match-beginning 0) (match-end 0)))
292       (setq end (point))
293       (cond
294        ;; Fetch and insert a picture.
295        ((equal tag "img_alt"))
296        ;; Add a link.
297        ((or (equal tag "a")
298             (equal tag "A"))
299         (when (string-match "href=\"\\([^\"]+\\)" parameters)
300           (setq url (match-string 1 parameters))
301           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
302           (gnus-article-add-button start end
303                                    'browse-url (mm-url-decode-entities-string url)
304                                    url)
305           (let ((overlay (gnus-make-overlay start end)))
306             (gnus-overlay-put overlay 'evaporate t)
307             (gnus-overlay-put overlay 'gnus-button-url url)
308             (gnus-put-text-property start end 'gnus-string url)
309             (when gnus-article-mouse-face
310               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
311        ;; The upper-case IMG_ALT is apparently just an artifact that
312        ;; should be deleted.
313        ((equal tag "IMG_ALT")
314         (delete-region start end))
315        ;; w3m does not normalize the case
316        ((or (equal tag "b")
317             (equal tag "B"))
318         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-bold))
319        ((or (equal tag "u")
320             (equal tag "U"))
321         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
322        ((or (equal tag "i")
323             (equal tag "I"))
324         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-italic))
325        ((or (equal tag "s")
326             (equal tag "S"))
327         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-strikethru))
328        ((or (equal tag "ins")
329             (equal tag "INS"))
330         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
331        ;; Handle different UL types
332        ((equal tag "_SYMBOL")
333         (when (string-match "TYPE=\\(.+\\)" parameters)
334           (let ((type (string-to-number (match-string 1 parameters))))
335             (delete-region start end)
336             (cond ((= type 33) (insert " "))
337                   ((= type 34) (insert " "))
338                   ((= type 35) (insert " "))
339                   ((= type 36) (insert " "))
340                   ((= type 37) (insert " "))
341                   ((= type 38) (insert " "))
342                   ((= type 39) (insert " "))
343                   ((= type 40) (insert " "))
344                   ((= type 42) (insert " "))
345                   ((= type 43) (insert " "))
346                   (t (insert " "))))))
347        ;; Whatever.  Just ignore the tag.
348        (t
349         ))
350       (goto-char start))
351     (goto-char (point-min))
352     ;; The output from -halfdump isn't totally regular, so strip
353     ;; off any </pre_int>s that were left over.
354     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
355       (replace-match "" t t))
356     (mm-url-decode-entities)))
357
358 (defun gnus-html-insert-image (&rest args)
359   "Fetch and insert the image under point."
360   (interactive)
361   (apply 'gnus-html-display-image (get-text-property (point) 'gnus-image)))
362
363 (defun gnus-html-show-alt-text ()
364   "Show the ALT text of the image under point."
365   (interactive)
366   (message "%s" (get-text-property (point) 'gnus-alt-text)))
367
368 (defun gnus-html-browse-image ()
369   "Browse the image under point."
370   (interactive)
371   (browse-url (get-text-property (point) 'image-url)))
372
373 (defun gnus-html-browse-url ()
374   "Browse the image under point."
375   (interactive)
376   (let ((url (get-text-property (point) 'gnus-string)))
377     (cond
378      ((not url)
379       (message "No link under point"))
380      ((string-match "^mailto:" url)
381       (gnus-url-mailto url))
382      (t
383       (browse-url url)))))
384
385 (defun gnus-html-schedule-image-fetching (buffer image)
386   "Retrieve IMAGE, and place it into BUFFER on arrival."
387   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, image %s"
388                 buffer image)
389   (if (fboundp 'url-queue-retrieve)
390       (url-queue-retrieve (car image)
391                           'gnus-html-image-fetched
392                           (list buffer image) t)
393     (ignore-errors
394       (url-retrieve (car image)
395                     'gnus-html-image-fetched
396                     (list buffer image)))))
397
398 (defun gnus-html-image-fetched (status buffer image)
399   "Callback function called when image has been fetched."
400   (unless (plist-get status :error)
401     (when gnus-html-image-automatic-caching
402       (url-store-in-cache (current-buffer)))
403     (when (and (or (search-forward "\n\n" nil t)
404                    (search-forward "\r\n\r\n" nil t))
405                (buffer-live-p buffer))
406       (let ((data (buffer-substring (point) (point-max))))
407         (with-current-buffer buffer
408           (let ((inhibit-read-only t))
409             (gnus-html-put-image data (car image) (cadr image)))))))
410   (kill-buffer (current-buffer)))
411
412 (defun gnus-html-get-image-data (url)
413   "Get image data for URL.
414 Return a string with image data."
415   (with-temp-buffer
416     (mm-disable-multibyte)
417     (url-cache-extract (url-cache-create-filename url))
418     (when (or (search-forward "\n\n" nil t)
419               (search-forward "\r\n\r\n" nil t))
420       (buffer-substring (point) (point-max)))))
421
422 (defun gnus-html-maximum-image-size ()
423   "Return the maximum size of an image according to `gnus-max-image-proportion'."
424   (let ((edges (gnus-window-inside-pixel-edges
425                 (get-buffer-window (current-buffer)))))
426     ;; (width . height)
427     (cons
428      ;; Aimed width
429      (truncate
430       (* gnus-max-image-proportion
431          (- (nth 2 edges) (nth 0 edges))))
432      ;; Aimed height
433      (truncate (* gnus-max-image-proportion
434                   (- (nth 3 edges) (nth 1 edges)))))))
435
436 (defun gnus-html-put-image (data url &optional alt-text)
437   "Put an image with DATA from URL and optional ALT-TEXT."
438   (when (gnus-graphic-display-p)
439     (let* ((start (text-property-any (point-min) (point-max)
440                                      'image-url url))
441            (end (when start
442                   (next-single-property-change start 'image-url))))
443       ;; Image found?
444       (when start
445         (let* ((image
446                 (ignore-errors
447                   (gnus-create-image data nil t)))
448                (size (and image
449                           (if (featurep 'xemacs)
450                               (cons (glyph-width image) (glyph-height image))
451                             (image-size image t)))))
452           (save-excursion
453             (goto-char start)
454             (let ((alt-text (or alt-text
455                                 (buffer-substring-no-properties start end)))
456                   (inhibit-read-only t))
457               (if (and image
458                        ;; Kludge to avoid displaying 30x30 gif images, which
459                        ;; seems to be a signal of a broken image.
460                        (not (and (if (featurep 'xemacs)
461                                      (glyphp image)
462                                    (listp image))
463                                  (eq (if (featurep 'xemacs)
464                                          (let ((d (cdadar
465                                                    (specifier-spec-list
466                                                     (glyph-image image)))))
467                                            (and (vectorp d)
468                                                 (aref d 0)))
469                                        (plist-get (cdr image) :type))
470                                      'gif)
471                                  (= (car size) 30)
472                                  (= (cdr size) 30))))
473                   ;; Good image, add it!
474                   (let ((image (gnus-rescale-image image (gnus-html-maximum-image-size))))
475                     (delete-region start end)
476                     (gnus-put-image image alt-text 'external)
477                     (widget-convert-button
478                      'url-link start (point)
479                      :help-echo alt-text
480                      :keymap gnus-html-displayed-image-map
481                      url)
482                     (gnus-put-text-property start (point)
483                                             'gnus-alt-text alt-text)
484                     (when url
485                       (gnus-add-text-properties
486                        start (point)
487                        `(image-url
488                          ,url
489                          image-displayer
490                          (lambda (url start end)
491                            (gnus-html-display-image ,url ,start ,(point)
492                                                     ,alt-text)))))
493                     (gnus-add-image 'external image)
494                     t)
495                 ;; Bad image, try to show something else
496                 (when (fboundp 'find-image)
497                   (delete-region start end)
498                   (setq image (find-image
499                                '((:type xpm :file "lock-broken.xpm"))))
500                   (gnus-put-image image alt-text 'internal)
501                   (gnus-add-image 'internal image))
502                 nil))))))))
503
504 (defun gnus-html-image-url-blocked-p (url blocked-images)
505   "Find out if URL is blocked by BLOCKED-IMAGES."
506   (let ((ret (and blocked-images
507                   (string-match blocked-images url))))
508     (if ret
509         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
510                       url blocked-images)
511       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
512                     url blocked-images))
513     ret))
514
515 ;;;###autoload
516 (defun gnus-html-prefetch-images (summary)
517   (when (buffer-live-p summary)
518     (let (inhibit-images blocked-images)
519       (with-current-buffer summary
520         (setq inhibit-images gnus-inhibit-images
521               blocked-images (gnus-blocked-images)))
522       (save-match-data
523         (while (re-search-forward "<img[^>]+src=[\"']\\(http[^\"']+\\)" nil t)
524           (let ((url (gnus-html-encode-url
525                       (mm-url-decode-entities-string (match-string 1)))))
526             (unless (or inhibit-images
527                         (gnus-html-image-url-blocked-p url blocked-images))
528               (when (gnus-html-cache-expired url gnus-html-image-cache-ttl)
529                 (gnus-html-schedule-image-fetching nil
530                                                    (list url))))))))))
531
532 (provide 'gnus-html)
533
534 ;;; gnus-html.el ends here