Embiggen pictures slightly.
[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
34 (require 'gnus-art)
35 (require 'mm-url)
36 (require 'url)
37 (require 'url-cache)
38 (require 'xml)
39 (require 'browse-url)
40
41 (defcustom gnus-html-image-cache-ttl (days-to-time 7)
42   "Time used to determine if we should use images from the cache."
43   :version "24.1"
44   :group 'gnus-art
45   :type 'integer)
46
47 (defcustom gnus-html-image-automatic-caching t
48   "Whether automatically cache retrieve images."
49   :version "24.1"
50   :group 'gnus-art
51   :type 'boolean)
52
53 (defcustom gnus-html-frame-width 70
54   "What width to use when rendering HTML."
55   :version "24.1"
56   :group 'gnus-art
57   :type 'integer)
58
59 (defcustom gnus-blocked-images "."
60   "Images that have URLs matching this regexp will be blocked."
61   :version "24.1"
62   :group 'gnus-art
63   :type 'regexp)
64
65 (defcustom gnus-max-image-proportion 0.9
66   "How big pictures displayed are in relation to the window they're in.
67 A value of 0.7 means that they are allowed to take up 70% of the
68 width and height of the window.  If they are larger than this,
69 and Emacs supports it, then the images will be rescaled down to
70 fit these criteria."
71   :version "24.1"
72   :group 'gnus-art
73   :type 'float)
74
75 (defvar gnus-html-image-map
76   (let ((map (make-sparse-keymap)))
77     (define-key map "u" 'gnus-article-copy-string)
78     (define-key map "i" 'gnus-html-insert-image)
79     (define-key map "v" 'gnus-html-browse-url)
80     map))
81
82 (defvar gnus-html-displayed-image-map
83   (let ((map (make-sparse-keymap)))
84     (define-key map "a" 'gnus-html-show-alt-text)
85     (define-key map "i" 'gnus-html-browse-image)
86     (define-key map "\r" 'gnus-html-browse-url)
87     (define-key map "u" 'gnus-article-copy-string)
88     (define-key map [tab] 'widget-forward)
89     map))
90
91 (defun gnus-html-encode-url (url)
92   "Encode URL."
93   (browse-url-url-encode-chars url "[)$ ]"))
94
95 (defun gnus-html-cache-expired (url ttl)
96   "Check if URL is cached for more than TTL."
97   (cond (url-standalone-mode
98          (not (file-exists-p (url-cache-create-filename url))))
99         (t (let ((cache-time (url-is-cached url)))
100              (if cache-time
101                  (time-less-p
102                   (time-add
103                    cache-time
104                    ttl)
105                   (current-time))
106                t)))))
107
108 ;;;###autoload
109 (defun gnus-article-html (&optional handle)
110   (let ((article-buffer (current-buffer)))
111     (unless handle
112       (setq handle (mm-dissect-buffer t)))
113     (save-restriction
114       (narrow-to-region (point) (point))
115       (save-excursion
116         (mm-with-part handle
117           (let* ((coding-system-for-read 'utf-8)
118                  (coding-system-for-write 'utf-8)
119                  (default-process-coding-system
120                    (cons coding-system-for-read coding-system-for-write))
121                  (charset (mail-content-type-get (mm-handle-type handle)
122                                                  'charset)))
123             (when (and charset
124                        (setq charset (mm-charset-to-coding-system charset))
125                        (not (eq charset 'ascii)))
126               (insert (prog1
127                           (mm-decode-coding-string (buffer-string) charset)
128                         (erase-buffer)
129                         (mm-enable-multibyte))))
130             (call-process-region (point-min) (point-max)
131                                  "w3m"
132                                  nil article-buffer nil
133                                  "-halfdump"
134                                  "-no-cookie"
135                                  "-I" "UTF-8"
136                                  "-O" "UTF-8"
137                                  "-o" "ext_halfdump=1"
138                                  "-o" "display_ins_del=2"
139                                  "-o" "pre_conv=1"
140                                  "-t" (format "%s" tab-width)
141                                  "-cols" (format "%s" gnus-html-frame-width)
142                                  "-o" "display_image=on"
143                                  "-T" "text/html"))))
144       (gnus-html-wash-tags))))
145
146 (defvar gnus-article-mouse-face)
147
148 (defun gnus-html-pre-wash ()
149   (goto-char (point-min))
150   (while (re-search-forward " *<pre_int> *</pre_int> *\n" nil t)
151     (replace-match "" t t))
152   (goto-char (point-min))
153   (while (re-search-forward "<a name[^\n>]+>" nil t)
154     (replace-match "" t t)))
155
156 (defun gnus-html-wash-images ()
157   "Run through current buffer and replace img tags by images."
158   (let (tag parameters string start end images url)
159     (goto-char (point-min))
160     ;; Search for all the images first.
161     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
162       (setq parameters (match-string 1)
163             start (match-beginning 0))
164       (delete-region start (point))
165       (when (search-forward "</img_alt>" (line-end-position) t)
166         (delete-region (match-beginning 0) (match-end 0)))
167       (setq end (point))
168       (when (string-match "src=\"\\([^\"]+\\)" parameters)
169         (setq url (gnus-html-encode-url (match-string 1 parameters)))
170         (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
171         (if (string-match "^cid:\\(.*\\)" url)
172             ;; URLs with cid: have their content stashed in other
173             ;; parts of the MIME structure, so just insert them
174             ;; immediately.
175             (let ((handle (mm-get-content-id
176                            (setq url (match-string 1 url))))
177                   image)
178               (when handle
179                 (mm-with-part handle
180                   (setq image (gnus-create-image (buffer-string)
181                                                  nil t))))
182               (when image
183                 (let ((string (buffer-substring start end)))
184                   (delete-region start end)
185                   (gnus-put-image image (gnus-string-or string "*") 'cid)
186                   (gnus-add-image 'cid image))))
187           ;; Normal, external URL.
188           (let ((alt-text (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
189                                               parameters)
190                             (xml-substitute-special (match-string 2 parameters)))))
191             (gnus-put-text-property start end 'gnus-image-url url)
192             (if (gnus-html-image-url-blocked-p
193                  url
194                  (if (buffer-live-p gnus-summary-buffer)
195                      (with-current-buffer gnus-summary-buffer
196                        gnus-blocked-images)
197                    gnus-blocked-images))
198                 (progn
199                   (widget-convert-button
200                    'link start end
201                    :action 'gnus-html-insert-image
202                    :help-echo url
203                    :keymap gnus-html-image-map
204                    :button-keymap gnus-html-image-map)
205                   (let ((overlay (gnus-make-overlay start end))
206                         (spec (list url alt-text)))
207                     (gnus-overlay-put overlay 'local-map gnus-html-image-map)
208                     (gnus-overlay-put overlay 'gnus-image spec)
209                     (gnus-put-text-property
210                      start end
211                      'gnus-image spec)))
212               ;; Non-blocked url
213               (let ((width
214                      (when (string-match "width=\"?\\([0-9]+\\)" parameters)
215                        (string-to-number (match-string 1 parameters))))
216                     (height
217                      (when (string-match "height=\"?\\([0-9]+\\)" parameters)
218                        (string-to-number (match-string 1 parameters)))))
219                 ;; Don't fetch images that are really small.  They're
220                 ;; probably tracking pictures.
221                 (when (and (or (null height)
222                                (> height 4))
223                            (or (null width)
224                                (> width 4)))
225                   (gnus-html-display-image url start end alt-text))))))))))
226
227 (defun gnus-html-display-image (url start end alt-text)
228   "Display image at URL on text from START to END.
229 Use ALT-TEXT for the image string."
230   (if (gnus-html-cache-expired url gnus-html-image-cache-ttl)
231       ;; We don't have it, so schedule it for fetching
232       ;; asynchronously.
233       (gnus-html-schedule-image-fetching
234        (current-buffer)
235        (list url alt-text))
236     ;; It's already cached, so just insert it.
237     (gnus-html-put-image (gnus-html-get-image-data url) url alt-text)))
238
239 (defun gnus-html-wash-tags ()
240   (let (tag parameters string start end images url)
241     (gnus-html-pre-wash)
242     (gnus-html-wash-images)
243
244     (goto-char (point-min))
245     ;; Then do the other tags.
246     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
247       (setq tag (match-string 1)
248             parameters (match-string 2)
249             start (match-beginning 0))
250       (when (plusp (length parameters))
251         (set-text-properties 0 (1- (length parameters)) nil parameters))
252       (delete-region start (point))
253       (when (search-forward (concat "</" tag ">") nil t)
254         (delete-region (match-beginning 0) (match-end 0)))
255       (setq end (point))
256       (cond
257        ;; Fetch and insert a picture.
258        ((equal tag "img_alt"))
259        ;; Add a link.
260        ((or (equal tag "a")
261             (equal tag "A"))
262         (when (string-match "href=\"\\([^\"]+\\)" parameters)
263           (setq url (match-string 1 parameters))
264           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
265           (gnus-article-add-button start end
266                                    'browse-url url
267                                    url)
268           (let ((overlay (gnus-make-overlay start end)))
269             (gnus-overlay-put overlay 'evaporate t)
270             (gnus-overlay-put overlay 'gnus-button-url url)
271             (gnus-put-text-property start end 'gnus-string url)
272             (when gnus-article-mouse-face
273               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
274        ;; The upper-case IMG_ALT is apparently just an artifact that
275        ;; should be deleted.
276        ((equal tag "IMG_ALT")
277         (delete-region start end))
278        ;; w3m does not normalize the case
279        ((or (equal tag "b")
280             (equal tag "B"))
281         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-bold))
282        ((or (equal tag "u")
283             (equal tag "U"))
284         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
285        ((or (equal tag "i")
286             (equal tag "I"))
287         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-italic))
288        ((or (equal tag "s")
289             (equal tag "S"))
290         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-strikethru))
291        ((or (equal tag "ins")
292             (equal tag "INS"))
293         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
294        ;; Handle different UL types
295        ((equal tag "_SYMBOL")
296         (when (string-match "TYPE=\\(.+\\)" parameters)
297           (let ((type (string-to-number (match-string 1 parameters))))
298             (delete-region start end)
299             (cond ((= type 33) (insert " "))
300                   ((= type 34) (insert " "))
301                   ((= type 35) (insert " "))
302                   ((= type 36) (insert " "))
303                   ((= type 37) (insert " "))
304                   ((= type 38) (insert " "))
305                   ((= type 39) (insert " "))
306                   ((= type 40) (insert " "))
307                   ((= type 42) (insert " "))
308                   ((= type 43) (insert " "))
309                   (t (insert " "))))))
310        ;; Whatever.  Just ignore the tag.
311        (t
312         ))
313       (goto-char start))
314     (goto-char (point-min))
315     ;; The output from -halfdump isn't totally regular, so strip
316     ;; off any </pre_int>s that were left over.
317     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
318       (replace-match "" t t))
319     (mm-url-decode-entities)))
320
321 (defun gnus-html-insert-image ()
322   "Fetch and insert the image under point."
323   (interactive)
324   (apply 'gnus-html-display-image (get-text-property (point) 'gnus-image)))
325
326 (defun gnus-html-show-alt-text ()
327   "Show the ALT text of the image under point."
328   (interactive)
329   (message "%s" (get-text-property (point) 'gnus-alt-text)))
330
331 (defun gnus-html-browse-image ()
332   "Browse the image under point."
333   (interactive)
334   (browse-url (get-text-property (point) 'gnus-image-url)))
335
336 (defun gnus-html-browse-url ()
337   "Browse the image under point."
338   (interactive)
339   (let ((url (get-text-property (point) 'gnus-string)))
340     (if (not url)
341         (message "No URL at point")
342       (browse-url url))))
343
344 (defun gnus-html-schedule-image-fetching (buffer image)
345   "Retrieve IMAGE, and place it into BUFFER on arrival."
346   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, image %s"
347                 buffer image)
348   (ignore-errors
349     (url-retrieve (car image)
350                   'gnus-html-image-fetched
351                   (list buffer image))))
352
353 (defun gnus-html-image-fetched (status buffer image)
354   "Callback function called when image has been fetched."
355   (unless (plist-get status :error)
356     (when gnus-html-image-automatic-caching
357       (url-store-in-cache (current-buffer)))
358     (when (and (or (search-forward "\n\n" nil t)
359                    (search-forward "\r\n\r\n" nil t))
360                (buffer-live-p buffer))
361       (let ((data (buffer-substring (point) (point-max))))
362         (with-current-buffer buffer
363           (let ((inhibit-read-only t))
364             (gnus-html-put-image data (car image) (cadr image)))))))
365   (kill-buffer (current-buffer)))
366
367 (defun gnus-html-get-image-data (url)
368   "Get image data for URL.
369 Return a string with image data."
370   (with-temp-buffer
371     (mm-disable-multibyte)
372     (url-cache-extract (url-cache-create-filename url))
373     (when (or (search-forward "\n\n" nil t)
374               (search-forward "\r\n\r\n" nil t))
375       (buffer-substring (point) (point-max)))))
376
377 (defun gnus-html-put-image (data url &optional alt-text)
378   (when (gnus-graphic-display-p)
379     (let* ((start (text-property-any (point-min) (point-max) 'gnus-image-url url))
380            (end (when start
381                   (next-single-property-change start 'gnus-image-url))))
382       ;; Image found?
383       (when start
384         (let* ((image
385                 (ignore-errors
386                   (gnus-create-image data nil t)))
387                (size (and image
388                           (if (featurep 'xemacs)
389                               (cons (glyph-width image) (glyph-height image))
390                             (image-size image t)))))
391           (save-excursion
392             (goto-char start)
393             (let ((alt-text (or alt-text (buffer-substring-no-properties start end))))
394               (if (and image
395                        ;; Kludge to avoid displaying 30x30 gif images, which
396                        ;; seems to be a signal of a broken image.
397                        (not (and (if (featurep 'xemacs)
398                                      (glyphp image)
399                                    (listp image))
400                                  (eq (if (featurep 'xemacs)
401                                          (let ((d (cdadar (specifier-spec-list
402                                                            (glyph-image image)))))
403                                            (and (vectorp d)
404                                                 (aref d 0)))
405                                        (plist-get (cdr image) :type))
406                                      'gif)
407                                  (= (car size) 30)
408                                  (= (cdr size) 30))))
409                   ;; Good image, add it!
410                   (let ((image (gnus-html-rescale-image image data size)))
411                     (delete-region start end)
412                     (gnus-put-image image alt-text 'external)
413                     (gnus-put-text-property start (point) 'help-echo alt-text)
414                     (gnus-overlay-put (gnus-make-overlay start (point)) 'local-map
415                                       gnus-html-displayed-image-map)
416                     (gnus-put-text-property start (point) 'gnus-alt-text alt-text)
417                     (when url
418                       (gnus-put-text-property start (point) 'gnus-image-url url))
419                     (gnus-add-image 'external image)
420                     t)
421                 ;; Bad image, try to show something else
422                 (when (fboundp 'find-image)
423                   (delete-region start end)
424                   (setq image (find-image '((:type xpm :file "lock-broken.xpm"))))
425                   (gnus-put-image image alt-text 'internal)
426                   (gnus-add-image 'internal image))
427                 nil))))))))
428
429 (defun gnus-html-rescale-image (image data size)
430   (if (or (not (fboundp 'imagemagick-types))
431           (not (get-buffer-window (current-buffer))))
432       image
433     (let* ((width (car size))
434            (height (cdr size))
435            (edges (window-inside-pixel-edges (get-buffer-window (current-buffer))))
436            (window-width (truncate (* gnus-max-image-proportion
437                                       (- (nth 2 edges) (nth 0 edges)))))
438            (window-height (truncate (* gnus-max-image-proportion
439                                        (- (nth 3 edges) (nth 1 edges)))))
440            scaled-image)
441       (when (> height window-height)
442         (setq image (or (create-image data 'imagemagick t
443                                       :height window-height)
444                         image))
445         (setq size (image-size image t)))
446       (when (> (car size) window-width)
447         (setq image (or
448                      (create-image data 'imagemagick t
449                                    :width window-width)
450                      image)))
451       image)))
452
453 (defun gnus-html-image-url-blocked-p (url blocked-images)
454   "Find out if URL is blocked by BLOCKED-IMAGES."
455   (let ((ret (and blocked-images
456                   (string-match blocked-images url))))
457     (if ret
458         (gnus-message 8 "gnus-html-image-url-blocked-p: %s blocked by regex %s"
459                       url blocked-images)
460       (gnus-message 9 "gnus-html-image-url-blocked-p: %s passes regex %s"
461                     url blocked-images))
462     ret))
463
464 (defun gnus-html-show-images ()
465   "Show any images that are in the HTML-rendered article buffer.
466 This only works if the article in question is HTML."
467   (interactive)
468   (gnus-with-article-buffer
469     (dolist (overlay (overlays-in (point-min) (point-max)))
470       (let ((o (overlay-get overlay 'gnus-image)))
471         (when o
472           (apply 'gnus-html-display-image o))))))
473
474 ;;;###autoload
475 (defun gnus-html-prefetch-images (summary)
476   (when (buffer-live-p summary)
477     (let ((blocked-images (with-current-buffer summary
478                             gnus-blocked-images)))
479       (save-match-data
480         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
481           (let ((url (gnus-html-encode-url (match-string 1))))
482             (unless (gnus-html-image-url-blocked-p url blocked-images)
483               (when (gnus-html-cache-expired url gnus-html-image-cache-ttl)
484                 (gnus-html-schedule-image-fetching nil
485                                                    (list url))))))))))
486
487 (provide 'gnus-html)
488
489 ;;; gnus-html.el ends here