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