Use `url' rather than curl to retrieve images.
[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   (url-retrieve (caar images)
301                 'gnus-html-image-fetched
302                 (list buffer images)))
303
304 (defun gnus-html-image-id (url)
305   (expand-file-name (sha1 url) gnus-html-cache-directory))
306
307 (defun gnus-html-image-fetched (status buffer images)
308   (let ((spec (pop images)))
309     (when (and (buffer-live-p buffer)
310                ;; If the position of the marker is 1, then that
311                ;; means that the text it was in has been deleted;
312                ;; i.e., that the user has selected a different
313                ;; article before the image arrived.
314                (not (= (marker-position (cadr spec)) (point-min))))
315       (let ((file (gnus-html-image-id (car spec))))
316         ;; Search the start of the image data
317         (search-forward "\n\n")
318         ;; Write region (image) silently
319         (write-region (point) (point-max) file nil 1)
320         (kill-buffer)
321         (with-current-buffer buffer
322           (let ((inhibit-read-only t)
323                 (string (buffer-substring (cadr spec) (caddr spec))))
324             (delete-region (cadr spec) (caddr spec))
325             (gnus-html-put-image file (cadr spec) string))))
326       (when images
327         (gnus-html-schedule-image-fetching buffer images)))))
328
329 (defun gnus-html-put-image (file point string &optional url alt-text)
330   (when (gnus-graphic-display-p)
331     (let* ((image (ignore-errors
332                    (gnus-create-image file)))
333           (size (and image
334                      (if (featurep 'xemacs)
335                          (cons (glyph-width image) (glyph-height image))
336                        (image-size image t)))))
337       (save-excursion
338         (goto-char point)
339         (if (and image
340                  ;; Kludge to avoid displaying 30x30 gif images, which
341                  ;; seems to be a signal of a broken image.
342                  (not (and (if (featurep 'xemacs)
343                                (glyphp image)
344                              (listp image))
345                            (eq (if (featurep 'xemacs)
346                                    (let ((data (cdadar (specifier-spec-list
347                                                         (glyph-image image)))))
348                                      (and (vectorp data)
349                                           (aref data 0)))
350                                  (plist-get (cdr image) :type))
351                                'gif)
352                            (= (car size) 30)
353                            (= (cdr size) 30))))
354             (let ((start (point)))
355               (setq image (gnus-html-rescale-image image file size))
356               (gnus-put-image image
357                               (gnus-string-or string "*")
358                               'external)
359               (let ((overlay (gnus-make-overlay start (point))))
360                 (gnus-overlay-put overlay 'local-map
361                                   gnus-html-displayed-image-map)
362                 (gnus-put-text-property start (point) 'gnus-alt-text alt-text)
363                 (when url
364                   (gnus-put-text-property start (point) 'gnus-image url)))
365               (gnus-add-image 'external image)
366               t)
367           (insert string)
368           (when (fboundp 'find-image)
369             (setq image (find-image '((:type xpm :file "lock-broken.xpm"))))
370             (gnus-put-image image
371                             (gnus-string-or string "*")
372                             'internal)
373             (gnus-add-image 'internal image))
374           nil)))))
375
376 (defun gnus-html-rescale-image (image file size)
377   (if (or (not (fboundp 'imagemagick-types))
378           (not (get-buffer-window (current-buffer))))
379       image
380     (let* ((width (car size))
381            (height (cdr size))
382            (edges (window-pixel-edges (get-buffer-window (current-buffer))))
383            (window-width (truncate (* gnus-max-image-proportion
384                                       (- (nth 2 edges) (nth 0 edges)))))
385            (window-height (truncate (* gnus-max-image-proportion
386                                        (- (nth 3 edges) (nth 1 edges)))))
387            scaled-image)
388       (when (> height window-height)
389         (setq image (or (create-image file 'imagemagick nil
390                                       :height window-height)
391                         image))
392         (setq size (image-size image t)))
393       (when (> (car size) window-width)
394         (setq image (or
395                      (create-image file 'imagemagick nil
396                                    :width window-width)
397                      image)))
398       image)))
399
400 (defun gnus-html-prune-cache ()
401   (let ((total-size 0)
402         files)
403     (dolist (file (directory-files gnus-html-cache-directory t nil t))
404       (let ((attributes (file-attributes file)))
405         (unless (nth 0 attributes)
406           (incf total-size (nth 7 attributes))
407           (push (list (time-to-seconds (nth 5 attributes))
408                       (nth 7 attributes) file)
409                 files))))
410     (when (> total-size gnus-html-cache-size)
411       (setq files (sort files (lambda (f1 f2)
412                                 (< (car f1) (car f2)))))
413       (dolist (file files)
414         (when (> total-size gnus-html-cache-size)
415           (decf total-size (cadr file))
416           (delete-file (nth 2 file)))))))
417
418 (defun gnus-html-image-url-blocked-p (url blocked-images)
419   "Find out if URL is blocked by BLOCKED-IMAGES."
420   (let ((ret (and blocked-images
421                   (string-match blocked-images url))))
422     (if ret
423         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
424                       url blocked-images)
425       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
426                     url blocked-images))
427     ret))
428
429 (defun gnus-html-show-images ()
430   "Show any images that are in the HTML-rendered article buffer.
431 This only works if the article in question is HTML."
432   (interactive)
433   (gnus-with-article-buffer
434     (let ((overlays (overlays-in (point-min) (point-max)))
435           overlay images)
436       (while (setq overlay (pop overlays))
437         (when (overlay-get overlay 'gnus-image)
438           (push (overlay-get overlay 'gnus-image) images)))
439       (if (not images)
440           (message "No images to show")
441         (gnus-html-schedule-image-fetching (current-buffer) images)))))
442
443 ;;;###autoload
444 (defun gnus-html-prefetch-images (summary)
445   (let (blocked-images urls)
446     (when (and (buffer-live-p summary)
447                (executable-find "curl"))
448       (with-current-buffer summary
449         (setq blocked-images gnus-blocked-images))
450       (save-match-data
451         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
452           (let ((url (match-string 1)))
453             (unless (gnus-html-image-url-blocked-p url blocked-images)
454               (unless (file-exists-p (gnus-html-image-id url))
455                 (push (mm-url-decode-entities-string url) urls)
456                 (push (gnus-html-image-id url) urls)
457                 (push "-o" urls)))))
458         (let ((process
459                (apply 'start-process
460                       "images" nil "curl"
461                       "-s" "--create-dirs"
462                       "--location"
463                       "--max-time" "60"
464                       urls)))
465           (gnus-set-process-query-on-exit-flag process nil))))))
466
467 (provide 'gnus-html)
468
469 ;;; gnus-html.el ends here