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