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