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