Misc fixes by Stefan Monnier <monnier@iro.umontreal.ca>.
[gnus] / lisp / gnus-html.el
1 ;;; gnus-html.el --- Quoted-Printable functions
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   :group 'gnus-art
38   :type 'directory)
39
40 (defcustom gnus-html-cache-size 500000000
41   "The size of the Gnus image cache."
42   :group 'gnus-art
43   :type 'integer)
44
45 (defcustom gnus-html-frame-width 70
46   "What width to use when rendering HTML."
47   :group 'gnus-art
48   :type 'integer)
49
50 (defcustom gnus-blocked-images "."
51   "Images that have URLs matching this regexp will be blocked."
52   :group 'gnus-art
53   :type 'regexp)
54
55 ;;;###autoload
56 (defun gnus-article-html (handle)
57   (let ((article-buffer (current-buffer)))
58     (save-restriction
59       (narrow-to-region (point) (point))
60       (save-excursion
61         (mm-with-part handle
62           (let* ((coding-system-for-read 'utf-8)
63                  (coding-system-for-write 'utf-8)
64                  (default-process-coding-system
65                    (cons coding-system-for-read coding-system-for-write)))
66             (call-process-region (point-min) (point-max)
67                                  "w3m" 
68                                  nil article-buffer nil
69                                  "-halfdump"
70                                  "-no-cookie"
71                                  "-I" "UTF-8"
72                                  "-O" "UTF-8"
73                                  "-o" "ext_halfdump=1"
74                                  "-o" "pre_conv=1"
75                                  "-t" (format "%s" tab-width)
76                                  "-cols" (format "%s" gnus-html-frame-width)
77                                  "-o" "display_image=off"
78                                  "-T" "text/html"))))
79       (gnus-html-wash-tags))))
80
81 (defvar gnus-article-mouse-face)
82
83 (defun gnus-html-wash-tags ()
84   (let (tag parameters string start end images url)
85     (mm-url-decode-entities)
86     (goto-char (point-min))
87     (while (re-search-forward "<\\([^ />]+\\)\\([^>]*\\)>" nil t)
88       (setq tag (match-string 1)
89             parameters (match-string 2)
90             start (match-beginning 0))
91       (when (plusp (length parameters))
92         (set-text-properties 0 (1- (length parameters)) nil parameters))
93       (delete-region start (point))
94       (when (search-forward (concat "</" tag ">") nil t)
95         (delete-region (match-beginning 0) (match-end 0)))
96       (setq end (point))
97       (cond
98        ;; Fetch and insert a picture.
99        ((equal tag "img_alt")
100         (when (string-match "src=\"\\([^\"]+\\)" parameters)
101           (setq url (match-string 1 parameters))
102           (if (string-match "^cid:\\(.*\\)" url)
103               ;; URLs with cid: have their content stashed in other
104               ;; parts of the MIME structure, so just insert them
105               ;; immediately.
106               (let ((handle (mm-get-content-id
107                              (setq url (match-string 1 url))))
108                     image)
109                 (when handle
110                   (mm-with-part handle
111                     (setq image (gnus-create-image (buffer-string)
112                                                    nil t))))
113                 (when image
114                   (delete-region start end)
115                   (gnus-put-image image)))
116             ;; Normal, external URL.
117             (when (or (null gnus-blocked-images)
118                       (not (string-match gnus-blocked-images url)))
119               (let ((file (gnus-html-image-id url)))
120                 (if (file-exists-p file)
121                     ;; It's already cached, so just insert it.
122                     (when (gnus-html-put-image file (point))
123                       ;; Delete the ALT text.
124                       (delete-region start end))
125                   ;; We don't have it, so schedule it for fetching
126                   ;; asynchronously.
127                   (push (list url
128                               (set-marker (make-marker) start)
129                               (point-marker))
130                         images)))))))
131        ;; Add a link.
132        ((equal tag "a")
133         (when (string-match "href=\"\\([^\"]+\\)" parameters)
134           (setq url (match-string 1 parameters))
135           (gnus-article-add-button start end
136                                    'browse-url url
137                                    url)
138           (let ((overlay (gnus-make-overlay start end)))
139             (gnus-overlay-put overlay 'evaporate t)
140             (gnus-overlay-put overlay 'gnus-button-url url)
141             (when gnus-article-mouse-face
142               (gnus-overlay-put overlay 'mouse-face gnus-article-mouse-face)))))
143        ;; Whatever.  Just ignore the tag.
144        (t
145         ))
146       (goto-char start))
147     (goto-char (point-min))
148     ;; The output from -halfdump isn't totally regular, so strip
149     ;; off any </pre_int>s that were left over.
150     (while (re-search-forward "</pre_int>" nil t)
151       (replace-match "" t t))
152     (when images
153       (gnus-html-schedule-image-fetching (current-buffer) (nreverse images)))))
154
155 (defun gnus-html-schedule-image-fetching (buffer images)
156   (let* ((url (caar images))
157          (process (start-process
158                    "images" nil "curl"
159                    "-s" "--create-dirs"
160                    "--location"
161                    "--max-time" "60"
162                    "-o" (gnus-html-image-id url)
163                    url)))
164     (process-kill-without-query process)
165     (set-process-sentinel process 'gnus-html-curl-sentinel)
166     (gnus-set-process-plist process (list 'images images
167                                           'buffer buffer))))
168
169 (defun gnus-html-image-id (url)
170   (expand-file-name (sha1 url) gnus-html-cache-directory))
171
172 (defun gnus-html-curl-sentinel (process event)
173   (when (string-match "finished" event)
174     (let* ((images (process-get process 'images))
175            (buffer (process-get process 'buffer))
176            (spec (pop images))
177            (file (gnus-html-image-id (car spec))))
178       (when (and (buffer-live-p buffer)
179                  ;; If the position of the marker is 1, then that
180                  ;; means that the text it was in has been deleted;
181                  ;; i.e., that the user has selected a different
182                  ;; article before the image arrived.
183                  (not (= (marker-position (cadr spec)) (point-min))))
184         (with-current-buffer buffer
185           (let ((inhibit-read-only t))
186             (when (gnus-html-put-image file (cadr spec))
187               (delete-region (1+ (cadr spec)) (caddr spec))))))
188       (when images
189         (gnus-html-schedule-image-fetching buffer images)))))
190
191 (defun gnus-html-put-image (file point)
192   (when (display-graphic-p)
193     (let ((image (ignore-errors
194                    (gnus-create-image file))))
195       (save-excursion
196         (goto-char point)
197         (if (and image
198                  ;; Kludge to avoid displaying 30x30 gif images, which
199                  ;; seems to be a signal of a broken image.
200                  (not (and (listp image)
201                            (eq (plist-get (cdr image) :type) 'gif)
202                            (= (car (image-size image t)) 30)
203                            (= (cdr (image-size image t)) 30))))
204             (progn
205               (gnus-put-image image)
206               t)
207           (when (fboundp 'find-image)
208             (gnus-put-image (find-image
209                              '((:type xpm :file "lock-broken.xpm")))))
210           nil)))))
211
212 (defun gnus-html-prune-cache ()
213   (let ((total-size 0)
214         files)
215     (dolist (file (directory-files gnus-html-cache-directory t nil t))
216       (let ((attributes (file-attributes file)))
217         (unless (nth 0 attributes)
218           (incf total-size (nth 7 attributes))
219           (push (list (time-to-seconds (nth 5 attributes))
220                       (nth 7 attributes) file)
221                 files))))
222     (when (> total-size gnus-html-cache-size)
223       (setq files (sort files (lambda (f1 f2)
224                                 (< (car f1) (car f2)))))
225       (dolist (file files)
226         (when (> total-size gnus-html-cache-size)
227           (decf total-size (cadr file))
228           (delete-file (nth 2 file)))))))
229
230 ;;;###autoload
231 (defun gnus-html-prefetch-images (summary)
232   (let (blocked-images urls)
233     (when (buffer-live-p summary)
234       (with-current-buffer summary
235         (setq blocked-images gnus-blocked-images))
236       (save-match-data
237         (while (re-search-forward "<img.*src=[\"']\\([^\"']+\\)" nil t)
238           (let ((url (match-string 1)))
239             (when (or (null blocked-images)
240                       (not (string-match blocked-images url)))
241               (unless (file-exists-p (gnus-html-image-id url))
242                 (push url urls)
243                 (push (gnus-html-image-id url) urls)
244                 (push "-o" urls)))))
245         (let ((process
246                (apply 'start-process 
247                       "images" nil "curl"
248                       "-s" "--create-dirs"
249                       "--location"
250                       "--max-time" "60"
251                       urls)))
252           (process-kill-without-query process))))))
253
254 (provide 'gnus-html)
255
256 ;;; gnus-html.el ends here