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