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