Refactor out the image bit, and don't restrict end-tag searches to the end of the...
[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-images ()
132   (let (tag parameters string start end images url)
133     (goto-char (point-min))
134     ;; Search for all the images first.
135     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
136       (setq parameters (match-string 1)
137             start (match-beginning 0))
138       (delete-region start (point))
139       (when (search-forward "</img_alt>" (line-end-position) t)
140         (delete-region (match-beginning 0) (match-end 0)))
141       (setq end (point))
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     (when images
212       (gnus-html-schedule-image-fetching (current-buffer) (nreverse images)))))
213
214 (defun gnus-html-wash-tags ()
215   (let (tag parameters string start end images url)
216     (gnus-html-pre-wash)
217     (gnus-html-wash-images)
218
219     (goto-char (point-min))
220     ;; Then do the other tags.
221     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
222       (setq tag (match-string 1)
223             parameters (match-string 2)
224             start (match-beginning 0))
225       (when (plusp (length parameters))
226         (set-text-properties 0 (1- (length parameters)) nil parameters))
227       (delete-region start (point))
228       (when (search-forward (concat "</" tag ">") nil t)
229         (delete-region (match-beginning 0) (match-end 0)))
230       (setq end (point))
231       (cond
232        ;; Fetch and insert a picture.
233        ((equal tag "img_alt"))
234        ;; Add a link.
235        ((or (equal tag "a")
236             (equal tag "A"))
237         (when (string-match "href=\"\\([^\"]+\\)" parameters)
238           (setq url (match-string 1 parameters))
239           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
240           (gnus-article-add-button start end
241                                    'browse-url url
242                                    url)
243           (let ((overlay (gnus-make-overlay start end)))
244             (gnus-overlay-put overlay 'evaporate t)
245             (gnus-overlay-put overlay 'gnus-button-url url)
246             (gnus-put-text-property start end 'gnus-string url)
247             (when gnus-article-mouse-face
248               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
249        ;; The upper-case IMG_ALT is apparently just an artifact that
250        ;; should be deleted.
251        ((equal tag "IMG_ALT")
252         (delete-region start end))
253        ;; Whatever.  Just ignore the tag.
254        (t
255         ))
256       (goto-char start))
257     (goto-char (point-min))
258     ;; The output from -halfdump isn't totally regular, so strip
259     ;; off any </pre_int>s that were left over.
260     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
261       (replace-match "" t t))
262     (mm-url-decode-entities)))
263
264 (defun gnus-html-insert-image ()
265   "Fetch and insert the image under point."
266   (interactive)
267   (gnus-html-schedule-image-fetching
268    (current-buffer) (list (get-text-property (point) 'gnus-image))))
269
270 (defun gnus-html-show-alt-text ()
271   "Show the ALT text of the image under point."
272   (interactive)
273   (message "%s" (get-text-property (point) 'gnus-alt-text)))
274
275 (defun gnus-html-browse-image ()
276   "Browse the image under point."
277   (interactive)
278   (browse-url (get-text-property (point) 'gnus-image)))
279
280 (defun gnus-html-browse-url ()
281   "Browse the image under point."
282   (interactive)
283   (let ((url (get-text-property (point) 'gnus-string)))
284     (if (not url)
285         (message "No URL at point")
286       (browse-url url))))
287
288 (defun gnus-html-schedule-image-fetching (buffer images)
289   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, images %s"
290                 buffer images)
291   (let* ((url (caar images))
292          (process (start-process
293                    "images" nil "curl"
294                    "-s" "--create-dirs"
295                    "--location"
296                    "--max-time" "60"
297                    "-o" (gnus-html-image-id url)
298                    (mm-url-decode-entities-string url))))
299     (process-kill-without-query process)
300     (set-process-sentinel process 'gnus-html-curl-sentinel)
301     (gnus-set-process-plist process (list 'images images
302                                           'buffer buffer))))
303
304 (defun gnus-html-image-id (url)
305   (expand-file-name (sha1 url) gnus-html-cache-directory))
306
307 (defun gnus-html-curl-sentinel (process event)
308   (when (string-match "finished" event)
309     (let* ((images (gnus-process-get process 'images))
310            (buffer (gnus-process-get process 'buffer))
311            (spec (pop images))
312            (file (gnus-html-image-id (car spec))))
313       (when (and (buffer-live-p buffer)
314                  ;; If the position of the marker is 1, then that
315                  ;; means that the text it was in has been deleted;
316                  ;; i.e., that the user has selected a different
317                  ;; article before the image arrived.
318                  (not (= (marker-position (cadr spec)) (point-min))))
319         (with-current-buffer buffer
320           (let ((inhibit-read-only t)
321                 (string (buffer-substring (cadr spec) (caddr spec))))
322             (delete-region (cadr spec) (caddr spec))
323             (gnus-html-put-image file (cadr spec) string))))
324       (when images
325         (gnus-html-schedule-image-fetching buffer images)))))
326
327 (defun gnus-html-put-image (file point string &optional url alt-text)
328   (when (gnus-graphic-display-p)
329     (let* ((image (ignore-errors
330                    (gnus-create-image file)))
331           (size (and image
332                      (if (featurep 'xemacs)
333                          (cons (glyph-width image) (glyph-height image))
334                        (image-size image t)))))
335       (save-excursion
336         (goto-char point)
337         (if (and image
338                  ;; Kludge to avoid displaying 30x30 gif images, which
339                  ;; seems to be a signal of a broken image.
340                  (not (and (if (featurep 'xemacs)
341                                (glyphp image)
342                              (listp image))
343                            (eq (if (featurep 'xemacs)
344                                    (let ((data (cdadar (specifier-spec-list
345                                                         (glyph-image image)))))
346                                      (and (vectorp data)
347                                           (aref data 0)))
348                                  (plist-get (cdr image) :type))
349                                'gif)
350                            (= (car size) 30)
351                            (= (cdr size) 30))))
352             (let ((start (point)))
353               (setq image (gnus-html-rescale-image image file size))
354               (gnus-put-image image
355                               (gnus-string-or string "*")
356                               'external)
357               (let ((overlay (gnus-make-overlay start (point))))
358                 (gnus-overlay-put overlay 'local-map
359                                   gnus-html-displayed-image-map)
360                 (gnus-put-text-property start (point) 'gnus-alt-text alt-text)
361                 (when url
362                   (gnus-put-text-property start (point) 'gnus-image url)))
363               (gnus-add-image 'external image)
364               t)
365           (insert string)
366           (when (fboundp 'find-image)
367             (setq image (find-image '((:type xpm :file "lock-broken.xpm"))))
368             (gnus-put-image image
369                             (gnus-string-or string "*")
370                             'internal)
371             (gnus-add-image 'internal image))
372           nil)))))
373
374 (defun gnus-html-rescale-image (image file size)
375   (if (or (not (fboundp 'imagemagick-types))
376           (not (get-buffer-window (current-buffer))))
377       image
378     (let* ((width (car size))
379            (height (cdr size))
380            (edges (window-pixel-edges (get-buffer-window (current-buffer))))
381            (window-width (truncate (* gnus-max-image-proportion
382                                       (- (nth 2 edges) (nth 0 edges)))))
383            (window-height (truncate (* gnus-max-image-proportion
384                                        (- (nth 3 edges) (nth 1 edges)))))
385            scaled-image)
386       (when (> height window-height)
387         (setq image (or (create-image file 'imagemagick nil
388                                       :height window-height)
389                         image))
390         (setq size (image-size image t)))
391       (when (> (car size) window-width)
392         (setq image (or
393                      (create-image file 'imagemagick nil
394                                    :width window-width)
395                      image)))
396       image)))
397
398 (defun gnus-html-prune-cache ()
399   (let ((total-size 0)
400         files)
401     (dolist (file (directory-files gnus-html-cache-directory t nil t))
402       (let ((attributes (file-attributes file)))
403         (unless (nth 0 attributes)
404           (incf total-size (nth 7 attributes))
405           (push (list (time-to-seconds (nth 5 attributes))
406                       (nth 7 attributes) file)
407                 files))))
408     (when (> total-size gnus-html-cache-size)
409       (setq files (sort files (lambda (f1 f2)
410                                 (< (car f1) (car f2)))))
411       (dolist (file files)
412         (when (> total-size gnus-html-cache-size)
413           (decf total-size (cadr file))
414           (delete-file (nth 2 file)))))))
415
416 (defun gnus-html-image-url-blocked-p (url blocked-images)
417   "Find out if URL is blocked by BLOCKED-IMAGES."
418   (let ((ret (and blocked-images
419                   (string-match blocked-images url))))
420     (if ret
421         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
422                       url blocked-images)
423       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
424                     url blocked-images))
425     ret))
426
427 (defun gnus-html-show-images ()
428   "Show any images that are in the HTML-rendered article buffer.
429 This only works if the article in question is HTML."
430   (interactive)
431   (gnus-with-article-buffer
432     (let ((overlays (overlays-in (point-min) (point-max)))
433           overlay images)
434       (while (setq overlay (pop overlays))
435         (when (overlay-get overlay 'gnus-image)
436           (push (overlay-get overlay 'gnus-image) images)))
437       (if (not images)
438           (message "No images to show")
439         (gnus-html-schedule-image-fetching (current-buffer) images)))))
440
441 ;;;###autoload
442 (defun gnus-html-prefetch-images (summary)
443   (let (blocked-images urls)
444     (when (buffer-live-p summary)
445       (with-current-buffer summary
446         (setq blocked-images gnus-blocked-images))
447       (save-match-data
448         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
449           (let ((url (match-string 1)))
450             (unless (gnus-html-image-url-blocked-p url blocked-images)
451               (unless (file-exists-p (gnus-html-image-id url))
452                 (push (mm-url-decode-entities-string url) urls)
453                 (push (gnus-html-image-id url) urls)
454                 (push "-o" urls)))))
455         (let ((process
456                (apply 'start-process
457                       "images" nil "curl"
458                       "-s" "--create-dirs"
459                       "--location"
460                       "--max-time" "60"
461                       urls)))
462           (process-kill-without-query process))))))
463
464 (provide 'gnus-html)
465
466 ;;; gnus-html.el ends here