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