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