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