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