gnus-html-rescale-image: Use window-inside-pixel-edges rather than window-pixel-edges
[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 in seconds used to cache the image on disk."
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     (define-key map "v" 'gnus-html-browse-url)
74     map))
75
76 (defvar gnus-html-displayed-image-map
77   (let ((map (make-sparse-keymap)))
78     (define-key map "a" 'gnus-html-show-alt-text)
79     (define-key map "i" 'gnus-html-browse-image)
80     (define-key map "\r" 'gnus-html-browse-url)
81     (define-key map "u" 'gnus-article-copy-string)
82     (define-key map [tab] 'widget-forward)
83     map))
84
85 (defun gnus-html-encode-url (url)
86   "Encode URL."
87   (browse-url-url-encode-chars url "[)$ ]"))
88
89 (defun gnus-html-cache-expired (url ttl)
90   "Check if URL is cached for more than TTL."
91   (cond (url-standalone-mode
92          (not (file-exists-p (url-cache-create-filename url))))
93         (t (let ((cache-time (url-is-cached url)))
94              (if cache-time
95                  (time-less-p
96                   (time-add
97                    cache-time
98                    ttl)
99                   (current-time))
100                t)))))
101
102 ;;;###autoload
103 (defun gnus-article-html (&optional handle)
104   (let ((article-buffer (current-buffer)))
105     (unless handle
106       (setq handle (mm-dissect-buffer t)))
107     (save-restriction
108       (narrow-to-region (point) (point))
109       (save-excursion
110         (mm-with-part handle
111           (let* ((coding-system-for-read 'utf-8)
112                  (coding-system-for-write 'utf-8)
113                  (default-process-coding-system
114                    (cons coding-system-for-read coding-system-for-write))
115                  (charset (mail-content-type-get (mm-handle-type handle)
116                                                  'charset)))
117             (when (and charset
118                        (setq charset (mm-charset-to-coding-system charset))
119                        (not (eq charset 'ascii)))
120               (insert (prog1
121                           (mm-decode-coding-string (buffer-string) charset)
122                         (erase-buffer)
123                         (mm-enable-multibyte))))
124             (call-process-region (point-min) (point-max)
125                                  "w3m"
126                                  nil article-buffer nil
127                                  "-halfdump"
128                                  "-no-cookie"
129                                  "-I" "UTF-8"
130                                  "-O" "UTF-8"
131                                  "-o" "ext_halfdump=1"
132                                  "-o" "display_ins_del=2"
133                                  "-o" "pre_conv=1"
134                                  "-t" (format "%s" tab-width)
135                                  "-cols" (format "%s" gnus-html-frame-width)
136                                  "-o" "display_image=on"
137                                  "-T" "text/html"))))
138       (gnus-html-wash-tags))))
139
140 (defvar gnus-article-mouse-face)
141
142 (defun gnus-html-pre-wash ()
143   (goto-char (point-min))
144   (while (re-search-forward " *<pre_int> *</pre_int> *\n" nil t)
145     (replace-match "" t t))
146   (goto-char (point-min))
147   (while (re-search-forward "<a name[^\n>]+>" nil t)
148     (replace-match "" t t)))
149
150 (defun gnus-html-wash-images ()
151   "Run through current buffer and replace img tags by images."
152   (let (tag parameters string start end images url)
153     (goto-char (point-min))
154     ;; Search for all the images first.
155     (while (re-search-forward "<img_alt \\([^>]*\\)>" nil t)
156       (setq parameters (match-string 1)
157             start (match-beginning 0))
158       (delete-region start (point))
159       (when (search-forward "</img_alt>" (line-end-position) t)
160         (delete-region (match-beginning 0) (match-end 0)))
161       (setq end (point))
162       (when (string-match "src=\"\\([^\"]+\\)" parameters)
163         (setq url (gnus-html-encode-url (match-string 1 parameters)))
164         (gnus-message 8 "gnus-html-wash-tags: fetching image URL %s" url)
165         (if (string-match "^cid:\\(.*\\)" url)
166             ;; URLs with cid: have their content stashed in other
167             ;; parts of the MIME structure, so just insert them
168             ;; immediately.
169             (let ((handle (mm-get-content-id
170                            (setq url (match-string 1 url))))
171                   image)
172               (when handle
173                 (mm-with-part handle
174                   (setq image (gnus-create-image (buffer-string)
175                                                  nil t))))
176               (when image
177                 (let ((string (buffer-substring start end)))
178                   (delete-region start end)
179                   (gnus-put-image image (gnus-string-or string "*") 'cid)
180                   (gnus-add-image 'cid image))))
181           ;; Normal, external URL.
182           (let ((alt-text (when (string-match "\\(alt\\|title\\)=\"\\([^\"]+\\)"
183                                               parameters)
184                             (xml-substitute-special (match-string 2 parameters)))))
185             (if (gnus-html-image-url-blocked-p
186                  url
187                  (if (buffer-live-p gnus-summary-buffer)
188                      (with-current-buffer gnus-summary-buffer
189                        gnus-blocked-images)
190                    gnus-blocked-images))
191                 (progn
192                   (widget-convert-button
193                    'link start end
194                    :action 'gnus-html-insert-image
195                    :help-echo url
196                    :keymap gnus-html-image-map
197                    :button-keymap gnus-html-image-map)
198                   (let ((overlay (gnus-make-overlay start end))
199                         (spec (list url
200                                     (set-marker (make-marker) start)
201                                     (set-marker (make-marker) end)
202                                     alt-text)))
203                     (gnus-overlay-put overlay 'local-map gnus-html-image-map)
204                     (gnus-overlay-put overlay 'gnus-image spec)
205                     (gnus-put-text-property start end 'gnus-image-url url)
206                     (gnus-put-text-property
207                      start end
208                      'gnus-image spec)))
209               ;; Non-blocked url
210               (let ((width
211                      (when (string-match "width=\"?\\([0-9]+\\)" parameters)
212                        (string-to-number (match-string 1 parameters))))
213                     (height
214                      (when (string-match "height=\"?\\([0-9]+\\)" parameters)
215                        (string-to-number (match-string 1 parameters)))))
216                 ;; Don't fetch images that are really small.  They're
217                 ;; probably tracking pictures.
218                 (when (and (or (null height)
219                                (> height 4))
220                            (or (null width)
221                                (> width 4)))
222                   (gnus-html-display-image url start end alt-text))))))))))
223
224 (defun gnus-html-display-image (url start end alt-text)
225   "Display image at URL on text from START to END.
226 Use ALT-TEXT for the image string."
227   (if (gnus-html-cache-expired url gnus-html-image-cache-ttl)
228       ;; We don't have it, so schedule it for fetching
229       ;; asynchronously.
230       (gnus-html-schedule-image-fetching
231        (current-buffer)
232        (list url
233              (set-marker (make-marker) start)
234              (set-marker (make-marker) end)
235              alt-text))
236     ;; It's already cached, so just insert it.
237     (gnus-html-put-image (gnus-html-get-image-data url)
238                          start end url alt-text)))
239
240 (defun gnus-html-wash-tags ()
241   (let (tag parameters string start end images url)
242     (gnus-html-pre-wash)
243     (gnus-html-wash-images)
244
245     (goto-char (point-min))
246     ;; Then do the other tags.
247     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
248       (setq tag (match-string 1)
249             parameters (match-string 2)
250             start (match-beginning 0))
251       (when (plusp (length parameters))
252         (set-text-properties 0 (1- (length parameters)) nil parameters))
253       (delete-region start (point))
254       (when (search-forward (concat "</" tag ">") nil t)
255         (delete-region (match-beginning 0) (match-end 0)))
256       (setq end (point))
257       (cond
258        ;; Fetch and insert a picture.
259        ((equal tag "img_alt"))
260        ;; Add a link.
261        ((or (equal tag "a")
262             (equal tag "A"))
263         (when (string-match "href=\"\\([^\"]+\\)" parameters)
264           (setq url (match-string 1 parameters))
265           (gnus-message 8 "gnus-html-wash-tags: fetching link URL %s" url)
266           (gnus-article-add-button start end
267                                    'browse-url url
268                                    url)
269           (let ((overlay (gnus-make-overlay start end)))
270             (gnus-overlay-put overlay 'evaporate t)
271             (gnus-overlay-put overlay 'gnus-button-url url)
272             (gnus-put-text-property start end 'gnus-string url)
273             (when gnus-article-mouse-face
274               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
275        ;; The upper-case IMG_ALT is apparently just an artifact that
276        ;; should be deleted.
277        ((equal tag "IMG_ALT")
278         (delete-region start end))
279        ;; w3m does not normalize the case
280        ((or (equal tag "b")
281             (equal tag "B"))
282         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-bold))
283        ((or (equal tag "u")
284             (equal tag "U"))
285         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
286        ((or (equal tag "i")
287             (equal tag "I"))
288         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-italic))
289        ((or (equal tag "s")
290             (equal tag "S"))
291         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-strikethru))
292        ((or (equal tag "ins")
293             (equal tag "INS"))
294         (gnus-overlay-put (gnus-make-overlay start end) 'face 'gnus-emphasis-underline))
295        ;; Handle different UL types
296        ((equal tag "_SYMBOL")
297         (when (string-match "TYPE=\\(.+\\)" parameters)
298           (let ((type (string-to-number (match-string 1 parameters))))
299             (delete-region start end)
300             (cond ((= type 33) (insert " "))
301                   ((= type 34) (insert " "))
302                   ((= type 35) (insert " "))
303                   ((= type 36) (insert " "))
304                   ((= type 37) (insert " "))
305                   ((= type 38) (insert " "))
306                   ((= type 39) (insert " "))
307                   ((= type 40) (insert " "))
308                   ((= type 42) (insert " "))
309                   ((= type 43) (insert " "))
310                   (t (insert " "))))))
311        ;; Whatever.  Just ignore the tag.
312        (t
313         ))
314       (goto-char start))
315     (goto-char (point-min))
316     ;; The output from -halfdump isn't totally regular, so strip
317     ;; off any </pre_int>s that were left over.
318     (while (re-search-forward "</pre_int>\\|</internal>" nil t)
319       (replace-match "" t t))
320     (mm-url-decode-entities)))
321
322 (defun gnus-html-insert-image ()
323   "Fetch and insert the image under point."
324   (interactive)
325   (apply 'gnus-html-display-image (get-text-property (point) 'gnus-image)))
326
327 (defun gnus-html-show-alt-text ()
328   "Show the ALT text of the image under point."
329   (interactive)
330   (message "%s" (get-text-property (point) 'gnus-alt-text)))
331
332 (defun gnus-html-browse-image ()
333   "Browse the image under point."
334   (interactive)
335   (browse-url (get-text-property (point) 'gnus-image-url)))
336
337 (defun gnus-html-browse-url ()
338   "Browse the image under point."
339   (interactive)
340   (let ((url (get-text-property (point) 'gnus-string)))
341     (if (not url)
342         (message "No URL at point")
343       (browse-url url))))
344
345 (defun gnus-html-schedule-image-fetching (buffer image)
346   "Retrieve IMAGE, and place it into BUFFER on arrival."
347   (gnus-message 8 "gnus-html-schedule-image-fetching: buffer %s, image %s"
348                 buffer image)
349   (ignore-errors
350     (url-retrieve (car image)
351                   'gnus-html-image-fetched
352                   (list buffer image))))
353
354 (defun gnus-html-image-fetched (status buffer image)
355   (url-store-in-cache (current-buffer))
356   (when (and (search-forward "\n\n" nil t)
357              (buffer-live-p buffer)
358              ;; If the `image' has no marker, do not replace anything
359              (cadr image)
360              ;; If the position of the marker is 1, then that
361              ;; means that the text it was in has been deleted;
362              ;; i.e., that the user has selected a different
363              ;; article before the image arrived.
364              (not (= (marker-position (cadr image))
365                      (with-current-buffer buffer
366                        (point-min)))))
367     (let ((data (buffer-substring (point) (point-max))))
368       (with-current-buffer buffer
369         (let ((inhibit-read-only t))
370           (gnus-html-put-image data (cadr image) (caddr image) (car image) (cadddr image))))))
371   (kill-buffer (current-buffer)))
372
373 (defun gnus-html-get-image-data (url)
374   "Get image data for URL.
375 Return a string with image data."
376   (with-temp-buffer
377     (mm-disable-multibyte)
378     (url-cache-extract (url-cache-create-filename url))
379     (when (or (search-forward "\n\n" nil t)
380               (search-forward "\r\n\r\n" nil t))
381       (buffer-substring (point) (point-max)))))
382
383 (defun gnus-html-put-image (data start end &optional url alt-text)
384   (when (gnus-graphic-display-p)
385     (let* ((image (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             (delete-region start end)
423             (when (fboundp 'find-image)
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