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