Allow showing the ALT text of images and to browse the images themselves.
[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-wash-tags ()
121   (let (tag parameters string start end images url)
122     (goto-char (point-min))
123     (while (re-search-forward " *<pre_int> *</pre_int> *\n" nil t)
124       (replace-match "" t t))
125     (goto-char (point-min))
126     (while (re-search-forward "<a name[^\n>]+>" nil t)
127       (replace-match "" t t))
128     (goto-char (point-min))
129     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
130       (setq tag (match-string 1)
131             parameters (match-string 2)
132             start (match-beginning 0))
133       (when (plusp (length parameters))
134         (set-text-properties 0 (1- (length parameters)) nil parameters))
135       (delete-region start (point))
136       (when (search-forward (concat "</" tag ">") (line-end-position) t)
137         (delete-region (match-beginning 0) (match-end 0)))
138       (setq end (point))
139       (cond
140        ;; Fetch and insert a picture.
141        ((equal tag "img_alt")
142         (when (string-match "src=\"\\([^\"]+\\)" parameters)
143           (setq url (match-string 1 parameters))
144           (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
145           (if (string-match "^cid:\\(.*\\)" url)
146               ;; URLs with cid: have their content stashed in other
147               ;; parts of the MIME structure, so just insert them
148               ;; immediately.
149               (let ((handle (mm-get-content-id
150                              (setq url (match-string 1 url))))
151                     image)
152                 (when handle
153                   (mm-with-part handle
154                     (setq image (gnus-create-image (buffer-string)
155                                                    nil t))))
156                 (when image
157                   (let ((string (buffer-substring start end)))
158                     (delete-region start end)
159                     (gnus-put-image image (gnus-string-or string "*") 'cid)
160                     (gnus-add-image 'cid image))))
161             ;; Normal, external URL.
162             (if (gnus-html-image-url-blocked-p
163                  url
164                  (if (buffer-live-p gnus-summary-buffer)
165                      (with-current-buffer gnus-summary-buffer
166                        gnus-blocked-images)
167                    gnus-blocked-images))
168                 (progn
169                   (widget-convert-button
170                    'link start end
171                    :action 'gnus-html-insert-image
172                    :help-echo url
173                    :keymap gnus-html-image-map
174                    :button-keymap gnus-html-image-map)
175                   (let ((overlay (gnus-make-overlay start end))
176                         (spec (list url
177                                     (set-marker (make-marker) start)
178                                     (set-marker (make-marker) end))))
179                     (gnus-overlay-put overlay 'local-map gnus-html-image-map)
180                     (gnus-overlay-put overlay 'gnus-image spec)
181                     (gnus-put-text-property
182                      start end
183                      'gnus-image spec)))
184               (let ((file (gnus-html-image-id url))
185                     width height alt-text)
186                 (when (string-match "height=\"?\\([0-9]+\\)" parameters)
187                   (setq height (string-to-number (match-string 1 parameters))))
188                 (when (string-match "width=\"?\\([0-9]+\\)" parameters)
189                   (setq width (string-to-number (match-string 1 parameters))))
190                 (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
191                                     parameters)
192                   (setq alt-text (match-string 2 parameters)))
193                 ;; Don't fetch images that are really small.  They're
194                 ;; probably tracking pictures.
195                 (when (and (or (null height)
196                                (> height 4))
197                            (or (null width)
198                                (> width 4)))
199                   (if (file-exists-p file)
200                       ;; It's already cached, so just insert it.
201                       (let ((string (buffer-substring start end)))
202                         ;; Delete the IMG text.
203                         (delete-region start end)
204                         (gnus-html-put-image file (point) string url alt-text))
205                     ;; We don't have it, so schedule it for fetching
206                     ;; asynchronously.
207                     (push (list url
208                                 (set-marker (make-marker) start)
209                                 (point-marker))
210                           images))))))))
211        ;; Add a link.
212        ((or (equal tag "a")
213             (equal tag "A"))
214         (when (string-match "href=\"\\([^\"]+\\)" parameters)
215           (setq url (match-string 1 parameters))
216           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
217           (gnus-article-add-button start end
218                                    'browse-url url
219                                    url)
220           (let ((overlay (gnus-make-overlay start end)))
221             (gnus-overlay-put overlay 'evaporate t)
222             (gnus-overlay-put overlay 'gnus-button-url url)
223             (gnus-put-text-property start end 'gnus-string url)
224             (when gnus-article-mouse-face
225               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
226        ;; The upper-case IMG_ALT is apparently just an artifact that
227        ;; should be deleted.
228        ((equal tag "IMG_ALT")
229         (delete-region start end))
230        ;; Whatever.  Just ignore the tag.
231        (t
232         ))
233       (goto-char start))
234     (goto-char (point-min))
235     ;; The output from -halfdump isn't totally regular, so strip
236     ;; off any </pre_int>s that were left over.
237     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
238       (replace-match "" t t))
239     (when images
240       (gnus-html-schedule-image-fetching (current-buffer) (nreverse images)))
241     (mm-url-decode-entities)))
242
243 (defun gnus-html-insert-image ()
244   "Fetch and insert the image under point."
245   (interactive)
246   (gnus-html-schedule-image-fetching
247    (current-buffer) (list (get-text-property (point) 'gnus-image))))
248
249 (defun gnus-html-show-alt-text ()
250   "Show the ALT text of the image under point."
251   (interactive)
252   (message "%s" (get-text-property (point) 'gnus-alt-text)))
253
254 (defun gnus-html-browse-image ()
255   "Browse the image under point."
256   (interactive)
257   (browse-url (get-text-property (point) 'gnus-image)))
258
259 (defun gnus-html-schedule-image-fetching (buffer images)
260   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, images %s"
261                 buffer images)
262   (let* ((url (caar images))
263          (process (start-process
264                    "images" nil "curl"
265                    "-s" "--create-dirs"
266                    "--location"
267                    "--max-time" "60"
268                    "-o" (gnus-html-image-id url)
269                    (mm-url-decode-entities-string url))))
270     (process-kill-without-query process)
271     (set-process-sentinel process 'gnus-html-curl-sentinel)
272     (gnus-set-process-plist process (list 'images images
273                                           'buffer buffer))))
274
275 (defun gnus-html-image-id (url)
276   (expand-file-name (sha1 url) gnus-html-cache-directory))
277
278 (defun gnus-html-curl-sentinel (process event)
279   (when (string-match "finished" event)
280     (let* ((images (gnus-process-get process 'images))
281            (buffer (gnus-process-get process 'buffer))
282            (spec (pop images))
283            (file (gnus-html-image-id (car spec))))
284       (when (and (buffer-live-p buffer)
285                  ;; If the position of the marker is 1, then that
286                  ;; means that the text it was in has been deleted;
287                  ;; i.e., that the user has selected a different
288                  ;; article before the image arrived.
289                  (not (= (marker-position (cadr spec)) (point-min))))
290         (with-current-buffer buffer
291           (let ((inhibit-read-only t)
292                 (string (buffer-substring (cadr spec) (caddr spec))))
293             (delete-region (cadr spec) (caddr spec))
294             (gnus-html-put-image file (cadr spec) string))))
295       (when images
296         (gnus-html-schedule-image-fetching buffer images)))))
297
298 (defun gnus-html-put-image (file point string &optional url alt-text)
299   (when (gnus-graphic-display-p)
300     (let* ((image (ignore-errors
301                    (gnus-create-image file)))
302           (size (and image
303                      (if (featurep 'xemacs)
304                          (cons (glyph-width image) (glyph-height image))
305                        (image-size image t)))))
306       (save-excursion
307         (goto-char point)
308         (if (and image
309                  ;; Kludge to avoid displaying 30x30 gif images, which
310                  ;; seems to be a signal of a broken image.
311                  (not (and (if (featurep 'xemacs)
312                                (glyphp image)
313                              (listp image))
314                            (eq (if (featurep 'xemacs)
315                                    (let ((data (cdadar (specifier-spec-list
316                                                         (glyph-image image)))))
317                                      (and (vectorp data)
318                                           (aref data 0)))
319                                  (plist-get (cdr image) :type))
320                                'gif)
321                            (= (car size) 30)
322                            (= (cdr size) 30))))
323             (let ((start (point)))
324               (setq image (gnus-html-rescale-image image file size))
325               (gnus-put-image image
326                               (gnus-string-or string "*")
327                               'external)
328               (let ((overlay (gnus-make-overlay start (point))))
329                 (gnus-overlay-put overlay 'local-map
330                                   gnus-html-displayed-image-map)
331                 (gnus-put-text-property start end 'gnus-alt-text alt-text)
332                 (when url
333                   (gnus-put-text-property start end 'gnus-image url)))
334               (gnus-add-image 'external image)
335               t)
336           (insert string)
337           (when (fboundp 'find-image)
338             (setq image (find-image '((:type xpm :file "lock-broken.xpm"))))
339             (gnus-put-image image
340                             (gnus-string-or string "*")
341                             'internal)
342             (gnus-add-image 'internal image))
343           nil)))))
344
345 (defun gnus-html-rescale-image (image file size)
346   (if (or (not (fboundp 'imagemagick-types))
347           (not (get-buffer-window (current-buffer))))
348       image
349     (let* ((width (car size))
350            (height (cdr size))
351            (edges (window-pixel-edges (get-buffer-window (current-buffer))))
352            (window-width (truncate (* gnus-max-image-proportion
353                                       (- (nth 2 edges) (nth 0 edges)))))
354            (window-height (truncate (* gnus-max-image-proportion
355                                        (- (nth 3 edges) (nth 1 edges)))))
356            scaled-image)
357       (when (> height window-height)
358         (setq image (or (create-image file 'imagemagick nil
359                                       :height window-height)
360                         image))
361         (setq size (image-size image t)))
362       (when (> (car size) window-width)
363         (setq image (or
364                      (create-image file 'imagemagick nil
365                                    :width window-width)
366                      image)))
367       image)))
368
369 (defun gnus-html-prune-cache ()
370   (let ((total-size 0)
371         files)
372     (dolist (file (directory-files gnus-html-cache-directory t nil t))
373       (let ((attributes (file-attributes file)))
374         (unless (nth 0 attributes)
375           (incf total-size (nth 7 attributes))
376           (push (list (time-to-seconds (nth 5 attributes))
377                       (nth 7 attributes) file)
378                 files))))
379     (when (> total-size gnus-html-cache-size)
380       (setq files (sort files (lambda (f1 f2)
381                                 (< (car f1) (car f2)))))
382       (dolist (file files)
383         (when (> total-size gnus-html-cache-size)
384           (decf total-size (cadr file))
385           (delete-file (nth 2 file)))))))
386
387 (defun gnus-html-image-url-blocked-p (url blocked-images)
388   "Find out if URL is blocked by BLOCKED-IMAGES."
389   (let ((ret (and blocked-images
390                   (string-match blocked-images url))))
391     (if ret
392         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
393                       url blocked-images)
394       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
395                     url blocked-images))
396     ret))
397
398 (defun gnus-html-show-images ()
399   "Show any images that are in the HTML-rendered article buffer.
400 This only works if the article in question is HTML."
401   (interactive)
402   (gnus-with-article-buffer
403     (let ((overlays (overlays-in (point-min) (point-max)))
404           overlay images)
405       (while (setq overlay (pop overlays))
406         (when (overlay-get overlay 'gnus-image)
407           (push (overlay-get overlay 'gnus-image) images)))
408       (if (not images)
409           (message "No images to show")
410         (gnus-html-schedule-image-fetching (current-buffer) images)))))
411
412 ;;;###autoload
413 (defun gnus-html-prefetch-images (summary)
414   (let (blocked-images urls)
415     (when (buffer-live-p summary)
416       (with-current-buffer summary
417         (setq blocked-images gnus-blocked-images))
418       (save-match-data
419         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
420           (let ((url (match-string 1)))
421             (unless (gnus-html-image-url-blocked-p url blocked-images)
422               (unless (file-exists-p (gnus-html-image-id url))
423                 (push (mm-url-decode-entities-string url) urls)
424                 (push (gnus-html-image-id url) urls)
425                 (push "-o" urls)))))
426         (let ((process
427                (apply 'start-process
428                       "images" nil "curl"
429                       "-s" "--create-dirs"
430                       "--location"
431                       "--max-time" "60"
432                       urls)))
433           (process-kill-without-query process))))))
434
435 (provide 'gnus-html)
436
437 ;;; gnus-html.el ends here