Rescale images in article buffers for Emacs versions that support this.
[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=off"
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           (if (string-match "^cid:\\(.*\\)" url)
123               ;; URLs with cid: have their content stashed in other
124               ;; parts of the MIME structure, so just insert them
125               ;; immediately.
126               (let ((handle (mm-get-content-id
127                              (setq url (match-string 1 url))))
128                     image)
129                 (when handle
130                   (mm-with-part handle
131                     (setq image (gnus-create-image (buffer-string)
132                                                    nil t))))
133                 (when image
134                   (delete-region start end)
135                   (gnus-put-image image)))
136             ;; Normal, external URL.
137             (when (or (null gnus-blocked-images)
138                       (not (string-match gnus-blocked-images url)))
139               (let ((file (gnus-html-image-id url)))
140                 (if (file-exists-p file)
141                     ;; It's already cached, so just insert it.
142                     (when (gnus-html-put-image file (point))
143                       ;; Delete the ALT text.
144                       (delete-region start end))
145                   ;; We don't have it, so schedule it for fetching
146                   ;; asynchronously.
147                   (push (list url
148                               (set-marker (make-marker) start)
149                               (point-marker))
150                         images)))))))
151        ;; Add a link.
152        ((equal tag "a")
153         (when (string-match "href=\"\\([^\"]+\\)" parameters)
154           (setq url (match-string 1 parameters))
155           (gnus-article-add-button start end
156                                    'browse-url url
157                                    url)
158           (let ((overlay (gnus-make-overlay start end)))
159             (gnus-overlay-put overlay 'evaporate t)
160             (gnus-overlay-put overlay 'gnus-button-url url)
161             (when gnus-article-mouse-face
162               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
163        ;; The upper-case IMG_ALT is apparently just an artifact that
164        ;; should be deleted.
165        ((equal tag "IMG_ALT")
166         (delete-region start end))
167        ;; Whatever.  Just ignore the tag.
168        (t
169         ))
170       (goto-char start))
171     (goto-char (point-min))
172     ;; The output from -halfdump isn't totally regular, so strip
173     ;; off any </pre_int>s that were left over.
174     (while (re-search-forward "</pre_int>" nil t)
175       (replace-match "" t t))
176     (when images
177       (gnus-html-schedule-image-fetching (current-buffer) (nreverse images)))))
178
179 (defun gnus-html-schedule-image-fetching (buffer images)
180   (let* ((url (caar images))
181          (process (start-process
182                    "images" nil "curl"
183                    "-s" "--create-dirs"
184                    "--location"
185                    "--max-time" "60"
186                    "-o" (gnus-html-image-id url)
187                    url)))
188     (process-kill-without-query process)
189     (set-process-sentinel process 'gnus-html-curl-sentinel)
190     (gnus-set-process-plist process (list 'images images
191                                           'buffer buffer))))
192
193 (defun gnus-html-image-id (url)
194   (expand-file-name (sha1 url) gnus-html-cache-directory))
195
196 (defun gnus-html-curl-sentinel (process event)
197   (when (string-match "finished" event)
198     (let* ((images (gnus-process-get process 'images))
199            (buffer (gnus-process-get process 'buffer))
200            (spec (pop images))
201            (file (gnus-html-image-id (car spec))))
202       (when (and (buffer-live-p buffer)
203                  ;; If the position of the marker is 1, then that
204                  ;; means that the text it was in has been deleted;
205                  ;; i.e., that the user has selected a different
206                  ;; article before the image arrived.
207                  (not (= (marker-position (cadr spec)) (point-min))))
208         (with-current-buffer buffer
209           (let ((inhibit-read-only t))
210             (when (gnus-html-put-image file (cadr spec))
211               (delete-region (1+ (cadr spec)) (caddr spec))))))
212       (when images
213         (gnus-html-schedule-image-fetching buffer images)))))
214
215 (defun gnus-html-put-image (file point)
216   (when (display-graphic-p)
217     (let ((image (ignore-errors
218                    (gnus-create-image file))))
219       (save-excursion
220         (goto-char point)
221         (if (and image
222                  ;; Kludge to avoid displaying 30x30 gif images, which
223                  ;; seems to be a signal of a broken image.
224                  (not (and (listp image)
225                            (eq (plist-get (cdr image) :type) 'gif)
226                            (= (car (image-size image t)) 30)
227                            (= (cdr (image-size image t)) 30))))
228             (progn
229               (gnus-put-image (gnus-html-rescale-image image))
230               t)
231           (when (fboundp 'find-image)
232             (gnus-put-image (find-image
233                              '((:type xpm :file "lock-broken.xpm")))))
234           nil)))))
235
236 (defun gnus-html-rescale-image (image)
237   (if (not (fboundp 'imagemagick-types))
238       image
239     (let* ((width (car (image-size image t)))
240            (height (cdr (image-size image t)))
241            (edges (window-pixel-edges))
242            (window-width (truncate (* gnus-max-image-proportion
243                                       (- (nth 2 edges) (nth 0 edges)))))
244            (window-height (truncate (* gnus-max-image-proportion
245                                        (- (nth 3 edges) (nth 1 edges)))))
246            scaled-image)
247       (when (> width window-width)
248         (setq window-height (truncate (* window-height
249                                          (/ (* 1.0 window-width) width)))))
250       (if (> height window-height)
251           (or (create-image file 'imagemagick nil
252                             :height window-height)
253               image)
254         image))))
255
256 (defun gnus-html-prune-cache ()
257   (let ((total-size 0)
258         files)
259     (dolist (file (directory-files gnus-html-cache-directory t nil t))
260       (let ((attributes (file-attributes file)))
261         (unless (nth 0 attributes)
262           (incf total-size (nth 7 attributes))
263           (push (list (time-to-seconds (nth 5 attributes))
264                       (nth 7 attributes) file)
265                 files))))
266     (when (> total-size gnus-html-cache-size)
267       (setq files (sort files (lambda (f1 f2)
268                                 (< (car f1) (car f2)))))
269       (dolist (file files)
270         (when (> total-size gnus-html-cache-size)
271           (decf total-size (cadr file))
272           (delete-file (nth 2 file)))))))
273
274 ;;;###autoload
275 (defun gnus-html-prefetch-images (summary)
276   (let (blocked-images urls)
277     (when (buffer-live-p summary)
278       (with-current-buffer summary
279         (setq blocked-images gnus-blocked-images))
280       (save-match-data
281         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
282           (let ((url (match-string 1)))
283             (when (or (null blocked-images)
284                       (not (string-match blocked-images url)))
285               (unless (file-exists-p (gnus-html-image-id url))
286                 (push url urls)
287                 (push (gnus-html-image-id url) urls)
288                 (push "-o" urls)))))
289         (let ((process
290                (apply 'start-process 
291                       "images" nil "curl"
292                       "-s" "--create-dirs"
293                       "--location"
294                       "--max-time" "60"
295                       urls)))
296           (process-kill-without-query process))))))
297
298 (provide 'gnus-html)
299
300 ;;; gnus-html.el ends here