Rework how Gnus is supposed to be able to display all the images in HTML.
[gnus] / lisp / gnus-html.el
1 ;;; gnus-html.el --- Render HTML in a buffer.
2
3 ;; Copyright (C) 2010  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)
173     (goto-char (point-min))
174     ;; Search for all the images first.
175     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
176       (setq parameters (match-string 1)
177             start (match-beginning 0))
178       (delete-region start (point))
179       (when (search-forward "</img_alt>" (line-end-position) t)
180         (delete-region (match-beginning 0) (match-end 0)))
181       (setq end (point))
182       (when (string-match "src=\"\\([^\"]+\\)" parameters)
183         (setq url (gnus-html-encode-url (match-string 1 parameters)))
184         (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
185         (if (string-match "^cid:\\(.*\\)" url)
186             ;; URLs with cid: have their content stashed in other
187             ;; parts of the MIME structure, so just insert them
188             ;; immediately.
189             (let* ((handle (mm-get-content-id
190                             (setq url (match-string 1 url))))
191                    (image (when handle
192                             (gnus-create-image (mm-with-part handle (buffer-string))
193                                                nil t))))
194               (when image
195                 (let ((string (buffer-substring start end)))
196                   (delete-region start end)
197                   (gnus-put-image (gnus-rescale-image image (gnus-html-maximum-image-size))
198                                   (gnus-string-or string "*") 'cid)
199                   (gnus-add-image 'cid image))))
200           ;; Normal, external URL.
201           (let ((alt-text (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
202                                               parameters)
203                             (xml-substitute-special (match-string 2 parameters)))))
204             (gnus-put-text-property start end 'image-url url)
205             (if (gnus-html-image-url-blocked-p
206                  url
207                  (if (buffer-live-p gnus-summary-buffer)
208                      (with-current-buffer gnus-summary-buffer
209                        (gnus-blocked-images))
210                    (gnus-blocked-images)))
211                 (progn
212                   (widget-convert-button
213                    'link start end
214                    :action 'gnus-html-insert-image
215                    :help-echo url
216                    :keymap gnus-html-image-map
217                    :button-keymap gnus-html-image-map)
218                   (let ((overlay (gnus-make-overlay start end))
219                         (spec (list url start end alt-text)))
220                     (gnus-overlay-put overlay 'local-map gnus-html-image-map)
221                     (gnus-overlay-put overlay 'gnus-image spec)
222                     (gnus-put-text-property
223                      start end
224                      'gnus-image spec)))
225               ;; Non-blocked url
226               (let ((width
227                      (when (string-match "width=\"?\\([0-9]+\\)" parameters)
228                        (string-to-number (match-string 1 parameters))))
229                     (height
230                      (when (string-match "height=\"?\\([0-9]+\\)" parameters)
231                        (string-to-number (match-string 1 parameters)))))
232                 ;; Don't fetch images that are really small.  They're
233                 ;; probably tracking pictures.
234                 (when (and (or (null height)
235                                (> height 4))
236                            (or (null width)
237                                (> width 4)))
238                   (gnus-html-display-image url start end alt-text))))))))))
239
240 (defun gnus-html-display-image (url start end &optional alt-text)
241   "Display image at URL on text from START to END.
242 Use ALT-TEXT for the image string."
243   (if (gnus-html-cache-expired url gnus-html-image-cache-ttl)
244       ;; We don't have it, so schedule it for fetching
245       ;; asynchronously.
246       (gnus-html-schedule-image-fetching
247        (current-buffer)
248        (list url alt-text))
249     ;; It's already cached, so just insert it.
250     (gnus-html-put-image (gnus-html-get-image-data url) url (or alt-text "*"))))
251
252 (defun gnus-html-wash-tags ()
253   (let (tag parameters string start end images url)
254     (gnus-html-pre-wash)
255     (gnus-html-wash-images)
256
257     (goto-char (point-min))
258     ;; Then do the other tags.
259     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
260       (setq tag (match-string 1)
261             parameters (match-string 2)
262             start (match-beginning 0))
263       (when (> (length parameters) 0)
264         (set-text-properties 0 (1- (length parameters)) nil parameters))
265       (delete-region start (point))
266       (when (search-forward (concat "</" tag ">") nil t)
267         (delete-region (match-beginning 0) (match-end 0)))
268       (setq end (point))
269       (cond
270        ;; Fetch and insert a picture.
271        ((equal tag "img_alt"))
272        ;; Add a link.
273        ((or (equal tag "a")
274             (equal tag "A"))
275         (when (string-match "href=\"\\([^\"]+\\)" parameters)
276           (setq url (match-string 1 parameters))
277           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
278           (gnus-article-add-button start end
279                                    'browse-url (mm-url-decode-entities-string url)
280                                    url)
281           (let ((overlay (gnus-make-overlay start end)))
282             (gnus-overlay-put overlay 'evaporate t)
283             (gnus-overlay-put overlay 'gnus-button-url url)
284             (gnus-put-text-property start end 'gnus-string url)
285             (when gnus-article-mouse-face
286               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
287        ;; The upper-case IMG_ALT is apparently just an artifact that
288        ;; should be deleted.
289        ((equal tag "IMG_ALT")
290         (delete-region start end))
291        ;; w3m does not normalize the case
292        ((or (equal tag "b")
293             (equal tag "B"))
294         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-bold))
295        ((or (equal tag "u")
296             (equal tag "U"))
297         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
298        ((or (equal tag "i")
299             (equal tag "I"))
300         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-italic))
301        ((or (equal tag "s")
302             (equal tag "S"))
303         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-strikethru))
304        ((or (equal tag "ins")
305             (equal tag "INS"))
306         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
307        ;; Handle different UL types
308        ((equal tag "_SYMBOL")
309         (when (string-match "TYPE=\\(.+\\)" parameters)
310           (let ((type (string-to-number (match-string 1 parameters))))
311             (delete-region start end)
312             (cond ((= type 33) (insert " "))
313                   ((= type 34) (insert " "))
314                   ((= type 35) (insert " "))
315                   ((= type 36) (insert " "))
316                   ((= type 37) (insert " "))
317                   ((= type 38) (insert " "))
318                   ((= type 39) (insert " "))
319                   ((= type 40) (insert " "))
320                   ((= type 42) (insert " "))
321                   ((= type 43) (insert " "))
322                   (t (insert " "))))))
323        ;; Whatever.  Just ignore the tag.
324        (t
325         ))
326       (goto-char start))
327     (goto-char (point-min))
328     ;; The output from -halfdump isn't totally regular, so strip
329     ;; off any </pre_int>s that were left over.
330     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
331       (replace-match "" t t))
332     (mm-url-decode-entities)))
333
334 (defun gnus-html-insert-image ()
335   "Fetch and insert the image under point."
336   (interactive)
337   (apply 'gnus-html-display-image (get-text-property (point) 'gnus-image)))
338
339 (defun gnus-html-show-alt-text ()
340   "Show the ALT text of the image under point."
341   (interactive)
342   (message "%s" (get-text-property (point) 'gnus-alt-text)))
343
344 (defun gnus-html-browse-image ()
345   "Browse the image under point."
346   (interactive)
347   (browse-url (get-text-property (point) 'image-url)))
348
349 (defun gnus-html-browse-url ()
350   "Browse the image under point."
351   (interactive)
352   (let ((url (get-text-property (point) 'gnus-string)))
353     (cond
354      ((not url)
355       (message "No link under point"))
356      ((string-match "^mailto:" url)
357       (gnus-url-mailto url))
358      (t
359       (browse-url url)))))
360
361 (defun gnus-html-schedule-image-fetching (buffer image)
362   "Retrieve IMAGE, and place it into BUFFER on arrival."
363   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, image %s"
364                 buffer image)
365   (let ((args (list (car image)
366                     'gnus-html-image-fetched
367                     (list buffer image))))
368     (when (> (length (if (featurep 'xemacs)
369                          (cdr (split-string (function-arglist 'url-retrieve)))
370                        (help-function-arglist 'url-retrieve)))
371              4)
372       (setq args (nconc args (list t))))
373     (ignore-errors
374       (apply #'url-retrieve args))))
375
376 (defun gnus-html-image-fetched (status buffer image)
377   "Callback function called when image has been fetched."
378   (unless (plist-get status :error)
379     (when gnus-html-image-automatic-caching
380       (url-store-in-cache (current-buffer)))
381     (when (and (or (search-forward "\n\n" nil t)
382                    (search-forward "\r\n\r\n" nil t))
383                (buffer-live-p buffer))
384       (let ((data (buffer-substring (point) (point-max))))
385         (with-current-buffer buffer
386           (let ((inhibit-read-only t))
387             (gnus-html-put-image data (car image) (cadr image)))))))
388   (kill-buffer (current-buffer)))
389
390 (defun gnus-html-get-image-data (url)
391   "Get image data for URL.
392 Return a string with image data."
393   (with-temp-buffer
394     (mm-disable-multibyte)
395     (url-cache-extract (url-cache-create-filename url))
396     (when (or (search-forward "\n\n" nil t)
397               (search-forward "\r\n\r\n" nil t))
398       (buffer-substring (point) (point-max)))))
399
400 (defun gnus-html-maximum-image-size ()
401   "Return the maximum size of an image according to `gnus-max-image-proportion'."
402   (let ((edges (gnus-window-inside-pixel-edges
403                 (get-buffer-window (current-buffer)))))
404     ;; (width . height)
405     (cons
406      ;; Aimed width
407      (truncate
408       (* gnus-max-image-proportion
409          (- (nth 2 edges) (nth 0 edges))))
410      ;; Aimed height
411      (truncate (* gnus-max-image-proportion
412                   (- (nth 3 edges) (nth 1 edges)))))))
413
414 (defun gnus-html-put-image (data url &optional alt-text)
415   "Put an image with DATA from URL and optional ALT-TEXT."
416   (when (gnus-graphic-display-p)
417     (let* ((start (text-property-any (point-min) (point-max)
418                                      'image-url url))
419            (end (when start
420                   (next-single-property-change start 'image-url))))
421       ;; Image found?
422       (when start
423         (let* ((image
424                 (ignore-errors
425                   (gnus-create-image data nil t)))
426                (size (and image
427                           (if (featurep 'xemacs)
428                               (cons (glyph-width image) (glyph-height image))
429                             (image-size image t)))))
430           (save-excursion
431             (goto-char start)
432             (let ((alt-text (or alt-text
433                                 (buffer-substring-no-properties start end))))
434               (if (and image
435                        ;; Kludge to avoid displaying 30x30 gif images, which
436                        ;; seems to be a signal of a broken image.
437                        (not (and (if (featurep 'xemacs)
438                                      (glyphp image)
439                                    (listp image))
440                                  (eq (if (featurep 'xemacs)
441                                          (let ((d (cdadar
442                                                    (specifier-spec-list
443                                                     (glyph-image image)))))
444                                            (and (vectorp d)
445                                                 (aref d 0)))
446                                        (plist-get (cdr image) :type))
447                                      'gif)
448                                  (= (car size) 30)
449                                  (= (cdr size) 30))))
450                   ;; Good image, add it!
451                   (let ((image (gnus-rescale-image image (gnus-html-maximum-image-size))))
452                     (delete-region start end)
453                     (gnus-put-image image alt-text 'external)
454                     (gnus-put-text-property start (point) 'help-echo alt-text)
455                     (gnus-overlay-put
456                      (gnus-make-overlay start (point)) 'local-map
457                      gnus-html-displayed-image-map)
458                     (gnus-put-text-property start (point)
459                                             'gnus-alt-text alt-text)
460                     (when url
461                       (gnus-put-text-property start (point)
462                                               'image-url url))
463                     (gnus-add-image 'external image)
464                     t)
465                 ;; Bad image, try to show something else
466                 (when (fboundp 'find-image)
467                   (delete-region start end)
468                   (setq image (find-image
469                                '((:type xpm :file "lock-broken.xpm"))))
470                   (gnus-put-image image alt-text 'internal)
471                   (gnus-add-image 'internal image))
472                 nil))))))))
473
474 (defun gnus-html-image-url-blocked-p (url blocked-images)
475   "Find out if URL is blocked by BLOCKED-IMAGES."
476   (let ((ret (and blocked-images
477                   (string-match blocked-images url))))
478     (if ret
479         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
480                       url blocked-images)
481       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
482                     url blocked-images))
483     ret))
484
485 ;;;###autoload
486 (defun gnus-html-prefetch-images (summary)
487   (when (buffer-live-p summary)
488     (let ((blocked-images (with-current-buffer summary
489                             (gnus-blocked-images))))
490       (save-match-data
491         (while (re-search-forward "<img[^>]+src=[\"']\\(http[^\"']+\\)" nil t)
492           (let ((url (gnus-html-encode-url
493                       (mm-url-decode-entities-string (match-string 1)))))
494             (unless (gnus-html-image-url-blocked-p url blocked-images)
495               (when (gnus-html-cache-expired url gnus-html-image-cache-ttl)
496                 (gnus-html-schedule-image-fetching nil
497                                                    (list url))))))))))
498
499 (provide 'gnus-html)
500
501 ;;; gnus-html.el ends here