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