Fix up the w3m/curl dependencies.
[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   (when (executable-find "curl")
292     (let* ((url (caar images))
293            (process (start-process
294                      "images" nil "curl"
295                      "-s" "--create-dirs"
296                      "--location"
297                      "--max-time" "60"
298                      "-o" (gnus-html-image-id url)
299                      (mm-url-decode-entities-string url))))
300       (process-kill-without-query process)
301       (set-process-sentinel process 'gnus-html-curl-sentinel)
302       (gnus-set-process-plist process (list 'images images
303                                             'buffer buffer)))))
304
305 (defun gnus-html-image-id (url)
306   (expand-file-name (sha1 url) gnus-html-cache-directory))
307
308 (defun gnus-html-curl-sentinel (process event)
309   (when (string-match "finished" event)
310     (let* ((images (gnus-process-get process 'images))
311            (buffer (gnus-process-get process 'buffer))
312            (spec (pop images))
313            (file (gnus-html-image-id (car spec))))
314       (when (and (buffer-live-p buffer)
315                  ;; If the position of the marker is 1, then that
316                  ;; means that the text it was in has been deleted;
317                  ;; i.e., that the user has selected a different
318                  ;; article before the image arrived.
319                  (not (= (marker-position (cadr spec)) (point-min))))
320         (with-current-buffer buffer
321           (let ((inhibit-read-only t)
322                 (string (buffer-substring (cadr spec) (caddr spec))))
323             (delete-region (cadr spec) (caddr spec))
324             (gnus-html-put-image file (cadr spec) string))))
325       (when images
326         (gnus-html-schedule-image-fetching buffer images)))))
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           (process-kill-without-query process))))))
465
466 (provide 'gnus-html)
467
468 ;;; gnus-html.el ends here