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