a42cd9309b55cb44f03d1b3cbf64eb52314ed9a7
[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                   (let ((overlay (gnus-make-overlay start end))
165                         (spec (list url
166                                     (set-marker (make-marker) start)
167                                     (set-marker (make-marker) end))))
168                     (gnus-overlay-put overlay 'local-map gnus-html-image-map)
169                     (gnus-overlay-put overlay 'gnus-image spec)
170                     (gnus-put-text-property
171                      start end
172                      'gnus-image spec)))
173               (let ((file (gnus-html-image-id url))
174                     width height)
175                 (when (string-match "height=\"?\\([0-9]+\\)" parameters)
176                   (setq height (string-to-number (match-string 1 parameters))))
177                 (when (string-match "width=\"?\\([0-9]+\\)" parameters)
178                   (setq width (string-to-number (match-string 1 parameters))))
179                 ;; Don't fetch images that are really small.  They're
180                 ;; probably tracking pictures.
181                 (when (and (or (null height)
182                                (> height 4))
183                            (or (null width)
184                                (> width 4)))
185                   (if (file-exists-p file)
186                       ;; It's already cached, so just insert it.
187                       (let ((string (buffer-substring start end)))
188                         ;; Delete the ALT text.
189                         (delete-region start end)
190                         (gnus-html-put-image file (point) string))
191                     ;; We don't have it, so schedule it for fetching
192                     ;; asynchronously.
193                     (push (list url
194                                 (set-marker (make-marker) start)
195                                 (point-marker))
196                           images))))))))
197        ;; Add a link.
198        ((or (equal tag "a")
199             (equal tag "A"))
200         (when (string-match "href=\"\\([^\"]+\\)" parameters)
201           (setq url (match-string 1 parameters))
202           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
203           (gnus-article-add-button start end
204                                    'browse-url url
205                                    url)
206           (let ((overlay (gnus-make-overlay start end)))
207             (gnus-overlay-put overlay 'evaporate t)
208             (gnus-overlay-put overlay 'gnus-button-url url)
209             (gnus-put-text-property start end 'gnus-string url)
210             (when gnus-article-mouse-face
211               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
212        ;; The upper-case IMG_ALT is apparently just an artifact that
213        ;; should be deleted.
214        ((equal tag "IMG_ALT")
215         (delete-region start end))
216        ;; Whatever.  Just ignore the tag.
217        (t
218         ))
219       (goto-char start))
220     (goto-char (point-min))
221     ;; The output from -halfdump isn't totally regular, so strip
222     ;; off any </pre_int>s that were left over.
223     (while (re-search-forward "</pre_int>" nil t)
224       (replace-match "" t t))
225     (when images
226       (gnus-html-schedule-image-fetching (current-buffer) (nreverse images)))))
227
228 (defun gnus-html-insert-image ()
229   "Fetch and insert the image under point."
230   (interactive)
231   (gnus-html-schedule-image-fetching
232    (current-buffer) (list (get-text-property (point) 'gnus-image))))
233
234 (defun gnus-html-schedule-image-fetching (buffer images)
235   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, images %s"
236                 buffer images)
237   (let* ((url (caar images))
238          (process (start-process
239                    "images" nil "curl"
240                    "-s" "--create-dirs"
241                    "--location"
242                    "--max-time" "60"
243                    "-o" (gnus-html-image-id url)
244                    url)))
245     (process-kill-without-query process)
246     (set-process-sentinel process 'gnus-html-curl-sentinel)
247     (gnus-set-process-plist process (list 'images images
248                                           'buffer buffer))))
249
250 (defun gnus-html-image-id (url)
251   (expand-file-name (sha1 url) gnus-html-cache-directory))
252
253 (defun gnus-html-curl-sentinel (process event)
254   (when (string-match "finished" event)
255     (let* ((images (gnus-process-get process 'images))
256            (buffer (gnus-process-get process 'buffer))
257            (spec (pop images))
258            (file (gnus-html-image-id (car spec))))
259       (when (and (buffer-live-p buffer)
260                  ;; If the position of the marker is 1, then that
261                  ;; means that the text it was in has been deleted;
262                  ;; i.e., that the user has selected a different
263                  ;; article before the image arrived.
264                  (not (= (marker-position (cadr spec)) (point-min))))
265         (with-current-buffer buffer
266           (let ((inhibit-read-only t)
267                 (string (buffer-substring (cadr spec) (caddr spec))))
268             (delete-region (cadr spec) (caddr spec))
269             (gnus-html-put-image file (cadr spec) string))))
270       (when images
271         (gnus-html-schedule-image-fetching buffer images)))))
272
273 (defun gnus-html-put-image (file point string)
274   (when (gnus-graphic-display-p)
275     (let* ((image (ignore-errors
276                    (gnus-create-image file)))
277           (size (and image
278                      (if (featurep 'xemacs)
279                          (cons (glyph-width image) (glyph-height image))
280                        (image-size image t)))))
281       (save-excursion
282         (goto-char point)
283         (if (and image
284                  ;; Kludge to avoid displaying 30x30 gif images, which
285                  ;; seems to be a signal of a broken image.
286                  (not (and (if (featurep 'xemacs)
287                                (glyphp image)
288                              (listp image))
289                            (eq (if (featurep 'xemacs)
290                                    (let ((data (cdadar (specifier-spec-list
291                                                         (glyph-image image)))))
292                                      (and (vectorp data)
293                                           (aref data 0)))
294                                  (plist-get (cdr image) :type))
295                                'gif)
296                            (= (car size) 30)
297                            (= (cdr size) 30))))
298             (progn
299               (setq image (gnus-html-rescale-image image file size))
300               (gnus-put-image image
301                               (gnus-string-or string "*")
302                               'external)
303               (gnus-add-image 'external image)
304               t)
305           (insert string)
306           (when (fboundp 'find-image)
307             (gnus-put-image (find-image
308                              '((:type xpm :file "lock-broken.xpm")))
309                             (gnus-string-or string "*")))
310           nil)))))
311
312 (defun gnus-html-rescale-image (image file size)
313   (if (or (not (fboundp 'imagemagick-types))
314           (not (get-buffer-window (current-buffer))))
315       image
316     (let* ((width (car size))
317            (height (cdr size))
318            (edges (window-pixel-edges (get-buffer-window (current-buffer))))
319            (window-width (truncate (* gnus-max-image-proportion
320                                       (- (nth 2 edges) (nth 0 edges)))))
321            (window-height (truncate (* gnus-max-image-proportion
322                                        (- (nth 3 edges) (nth 1 edges)))))
323            scaled-image)
324       (when (> height window-height)
325         (setq image (or (create-image file 'imagemagick nil
326                                       :height window-height)
327                         image))
328         (setq size (image-size image t)))
329       (when (> (car size) window-width)
330         (setq image (or
331                      (create-image file 'imagemagick nil
332                                    :width window-width)
333                      image)))
334       image)))
335
336 (defun gnus-html-prune-cache ()
337   (let ((total-size 0)
338         files)
339     (dolist (file (directory-files gnus-html-cache-directory t nil t))
340       (let ((attributes (file-attributes file)))
341         (unless (nth 0 attributes)
342           (incf total-size (nth 7 attributes))
343           (push (list (time-to-seconds (nth 5 attributes))
344                       (nth 7 attributes) file)
345                 files))))
346     (when (> total-size gnus-html-cache-size)
347       (setq files (sort files (lambda (f1 f2)
348                                 (< (car f1) (car f2)))))
349       (dolist (file files)
350         (when (> total-size gnus-html-cache-size)
351           (decf total-size (cadr file))
352           (delete-file (nth 2 file)))))))
353
354 (defun gnus-html-image-url-blocked-p (url blocked-images)
355 "Find out if URL is blocked by BLOCKED-IMAGES."
356   (let ((ret (and blocked-images
357                   (string-match blocked-images url))))
358     (if ret
359         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
360                       url blocked-images)
361       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
362                     url blocked-images))
363     ret))
364
365 ;;;###autoload
366 (defun gnus-html-prefetch-images (summary)
367   (let (blocked-images urls)
368     (when (buffer-live-p summary)
369       (with-current-buffer summary
370         (setq blocked-images gnus-blocked-images))
371       (save-match-data
372         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
373           (let ((url (match-string 1)))
374             (unless (gnus-html-image-url-blocked-p url blocked-images)
375               (unless (file-exists-p (gnus-html-image-id url))
376                 (push url urls)
377                 (push (gnus-html-image-id url) urls)
378                 (push "-o" urls)))))
379         (let ((process
380                (apply 'start-process
381                       "images" nil "curl"
382                       "-s" "--create-dirs"
383                       "--location"
384                       "--max-time" "60"
385                       urls)))
386           (process-kill-without-query process))))))
387
388 (provide 'gnus-html)
389
390 ;;; gnus-html.el ends here