]> code.delx.au - gnu-emacs/blob - lisp/image.el
*** empty log message ***
[gnu-emacs] / lisp / image.el
1 ;;; image.el --- image API
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7 ;; Keywords: multimedia
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 3, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING. If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Commentary:
27
28 ;;; Code:
29
30
31 (defgroup image ()
32 "Image support."
33 :group 'multimedia)
34
35
36 (defconst image-type-header-regexps
37 '(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm)
38 ("\\`P[1-6][[:space:]]+\\(?:#.*[[:space:]]+\\)*[0-9]+[[:space:]]+[0-9]+" . pbm)
39 ("\\`GIF8[79]a" . gif)
40 ("\\`\x89PNG\r\n\x1a\n" . png)
41 ("\\`[\t\n\r ]*#define \\([a-z0-9]+\\)_width [0-9]+\n\
42 #define \\1_height [0-9]+\n\
43 static char \\1_bits" . xbm)
44 ("\\`\\(?:MM\0\\*\\|II\\*\0\\)" . tiff)
45 ("\\`[\t\n\r ]*%!PS" . postscript)
46 ("\\`\xff\xd8" . (image-jpeg-p . jpeg)))
47 "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
48 When the first bytes of an image file match REGEXP, it is assumed to
49 be of image type IMAGE-TYPE if IMAGE-TYPE is a symbol. If not a symbol,
50 IMAGE-TYPE must be a pair (PREDICATE . TYPE). PREDICATE is called
51 with one argument, a string containing the image data. If PREDICATE returns
52 a non-nil value, TYPE is the image's type.")
53
54 (defconst image-type-file-name-regexps
55 '(("\\.png\\'" . png)
56 ("\\.gif\\'" . gif)
57 ("\\.jpe?g\\'" . jpeg)
58 ("\\.bmp\\'" . bmp)
59 ("\\.xpm\\'" . xpm)
60 ("\\.pbm\\'" . pbm)
61 ("\\.xbm\\'" . xbm)
62 ("\\.ps\\'" . postscript)
63 ("\\.tiff?\\'" . tiff))
64 "Alist of (REGEXP . IMAGE-TYPE) pairs used to identify image files.
65 When the name of an image file match REGEXP, it is assumed to
66 be of image type IMAGE-TYPE.")
67
68 ;; We rely on `auto-mode-alist' to detect xbm and xpm files, instead
69 ;; of content autodetection. Their contents are just C code, so it is
70 ;; easy to generate false matches.
71 (defvar image-type-auto-detectable
72 '((pbm . t)
73 (xbm . nil)
74 (bmp . maybe)
75 (gif . maybe)
76 (png . maybe)
77 (xpm . nil)
78 (jpeg . maybe)
79 (tiff . maybe)
80 (postscript . nil))
81 "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
82 \(See `image-type-auto-detected-p').
83
84 AUTODETECT can be
85 - t always auto-detect.
86 - nil never auto-detect.
87 - maybe auto-detect only if the image type is available
88 (see `image-type-available-p').")
89
90 (defvar image-load-path nil
91 "List of locations in which to search for image files.
92 If an element is a string, it defines a directory to search.
93 If an element is a variable symbol whose value is a string, that
94 value defines a directory to search.
95 If an element is a variable symbol whose value is a list, the
96 value is used as a list of directories to search.")
97
98 (eval-at-startup
99 (setq image-load-path
100 (list (file-name-as-directory (expand-file-name "images" data-directory))
101 'data-directory 'load-path)))
102
103
104 (defun image-load-path-for-library (library image &optional path no-error)
105 "Return a suitable search path for images used by LIBRARY.
106
107 It searches for IMAGE in `image-load-path' (excluding
108 \"`data-directory'/images\") and `load-path', followed by a path
109 suitable for LIBRARY, which includes \"../../etc/images\" and
110 \"../etc/images\" relative to the library file itself, and then
111 in \"`data-directory'/images\".
112
113 Then this function returns a list of directories which contains
114 first the directory in which IMAGE was found, followed by the
115 value of `load-path'. If PATH is given, it is used instead of
116 `load-path'.
117
118 If NO-ERROR is non-nil and a suitable path can't be found, don't
119 signal an error. Instead, return a list of directories as before,
120 except that nil appears in place of the image directory.
121
122 Here is an example that uses a common idiom to provide
123 compatibility with versions of Emacs that lack the variable
124 `image-load-path':
125
126 ;; Shush compiler.
127 (defvar image-load-path)
128
129 (let* ((load-path (image-load-path-for-library \"mh-e\" \"mh-logo.xpm\"))
130 (image-load-path (cons (car load-path)
131 (when (boundp 'image-load-path)
132 image-load-path))))
133 (mh-tool-bar-folder-buttons-init))"
134 (unless library (error "No library specified"))
135 (unless image (error "No image specified"))
136 (let (image-directory image-directory-load-path)
137 ;; Check for images in image-load-path or load-path.
138 (let ((img image)
139 (dir (or
140 ;; Images in image-load-path.
141 (image-search-load-path image)
142 ;; Images in load-path.
143 (locate-library image)))
144 parent)
145 ;; Since the image might be in a nested directory (for
146 ;; example, mail/attach.pbm), adjust `image-directory'
147 ;; accordingly.
148 (when dir
149 (setq dir (file-name-directory dir))
150 (while (setq parent (file-name-directory img))
151 (setq img (directory-file-name parent)
152 dir (expand-file-name "../" dir))))
153 (setq image-directory-load-path dir))
154
155 ;; If `image-directory-load-path' isn't Emacs' image directory,
156 ;; it's probably a user preference, so use it. Then use a
157 ;; relative setting if possible; otherwise, use
158 ;; `image-directory-load-path'.
159 (cond
160 ;; User-modified image-load-path?
161 ((and image-directory-load-path
162 (not (equal image-directory-load-path
163 (file-name-as-directory
164 (expand-file-name "images" data-directory)))))
165 (setq image-directory image-directory-load-path))
166 ;; Try relative setting.
167 ((let (library-name d1ei d2ei)
168 ;; First, find library in the load-path.
169 (setq library-name (locate-library library))
170 (if (not library-name)
171 (error "Cannot find library %s in load-path" library))
172 ;; And then set image-directory relative to that.
173 (setq
174 ;; Go down 2 levels.
175 d2ei (file-name-as-directory
176 (expand-file-name
177 (concat (file-name-directory library-name) "../../etc/images")))
178 ;; Go down 1 level.
179 d1ei (file-name-as-directory
180 (expand-file-name
181 (concat (file-name-directory library-name) "../etc/images"))))
182 (setq image-directory
183 ;; Set it to nil if image is not found.
184 (cond ((file-exists-p (expand-file-name image d2ei)) d2ei)
185 ((file-exists-p (expand-file-name image d1ei)) d1ei)))))
186 ;; Use Emacs' image directory.
187 (image-directory-load-path
188 (setq image-directory image-directory-load-path))
189 (no-error
190 (message "Could not find image %s for library %s" image library))
191 (t
192 (error "Could not find image %s for library %s" image library)))
193
194 ;; Return an augmented `path' or `load-path'.
195 (nconc (list image-directory)
196 (delete image-directory (copy-sequence (or path load-path))))))
197
198
199 (defun image-jpeg-p (data)
200 "Value is non-nil if DATA, a string, consists of JFIF image data.
201 We accept the tag Exif because that is the same format."
202 (when (string-match "\\`\xff\xd8" data)
203 (catch 'jfif
204 (let ((len (length data)) (i 2))
205 (while (< i len)
206 (when (/= (aref data i) #xff)
207 (throw 'jfif nil))
208 (setq i (1+ i))
209 (when (>= (+ i 2) len)
210 (throw 'jfif nil))
211 (let ((nbytes (+ (lsh (aref data (+ i 1)) 8)
212 (aref data (+ i 2))))
213 (code (aref data i)))
214 (when (and (>= code #xe0) (<= code #xef))
215 ;; APP0 LEN1 LEN2 "JFIF\0"
216 (throw 'jfif
217 (string-match "JFIF\\|Exif"
218 (substring data i (min (+ i nbytes) len)))))
219 (setq i (+ i 1 nbytes))))))))
220
221
222 ;;;###autoload
223 (defun image-type-from-data (data)
224 "Determine the image type from image data DATA.
225 Value is a symbol specifying the image type or nil if type cannot
226 be determined."
227 (let ((types image-type-header-regexps)
228 type)
229 (while types
230 (let ((regexp (car (car types)))
231 (image-type (cdr (car types))))
232 (if (or (and (symbolp image-type)
233 (string-match regexp data))
234 (and (consp image-type)
235 (funcall (car image-type) data)
236 (setq image-type (cdr image-type))))
237 (setq type image-type
238 types nil)
239 (setq types (cdr types)))))
240 type))
241
242
243 ;;;###autoload
244 (defun image-type-from-buffer ()
245 "Determine the image type from data in the current buffer.
246 Value is a symbol specifying the image type or nil if type cannot
247 be determined."
248 (let ((types image-type-header-regexps)
249 type
250 (opoint (point)))
251 (goto-char (point-min))
252 (while types
253 (let ((regexp (car (car types)))
254 (image-type (cdr (car types)))
255 data)
256 (if (or (and (symbolp image-type)
257 (looking-at regexp))
258 (and (consp image-type)
259 (funcall (car image-type)
260 (or data
261 (setq data
262 (buffer-substring
263 (point-min)
264 (min (point-max)
265 (+ (point-min) 256))))))
266 (setq image-type (cdr image-type))))
267 (setq type image-type
268 types nil)
269 (setq types (cdr types)))))
270 (goto-char opoint)
271 type))
272
273
274 ;;;###autoload
275 (defun image-type-from-file-header (file)
276 "Determine the type of image file FILE from its first few bytes.
277 Value is a symbol specifying the image type, or nil if type cannot
278 be determined."
279 (unless (or (file-readable-p file)
280 (file-name-absolute-p file))
281 (setq file (image-search-load-path file)))
282 (and file
283 (file-readable-p file)
284 (with-temp-buffer
285 (set-buffer-multibyte nil)
286 (insert-file-contents-literally file nil 0 256)
287 (image-type-from-buffer))))
288
289
290 ;;;###autoload
291 (defun image-type-from-file-name (file)
292 "Determine the type of image file FILE from its name.
293 Value is a symbol specifying the image type, or nil if type cannot
294 be determined."
295 (let ((types image-type-file-name-regexps)
296 type)
297 (while types
298 (if (string-match (car (car types)) file)
299 (setq type (cdr (car types))
300 types nil)
301 (setq types (cdr types))))
302 type))
303
304
305 ;;;###autoload
306 (defun image-type (file-or-data &optional type data-p)
307 "Determine and return image type.
308 FILE-OR-DATA is an image file name or image data.
309 Optional TYPE is a symbol describing the image type. If TYPE is omitted
310 or nil, try to determine the image type from its first few bytes
311 of image data. If that doesn't work, and FILE-OR-DATA is a file name,
312 use its file extension as image type.
313 Optional DATA-P non-nil means FILE-OR-DATA is a string containing image data."
314 (when (and (not data-p) (not (stringp file-or-data)))
315 (error "Invalid image file name `%s'" file-or-data))
316 (unless type
317 (setq type (if data-p
318 (image-type-from-data file-or-data)
319 (or (image-type-from-file-header file-or-data)
320 (image-type-from-file-name file-or-data))))
321 (or type(error "Cannot determine image type")))
322 (or (memq type (and (boundp 'image-types) image-types))
323 (error "Invalid image type `%s'" type))
324 type)
325
326
327 ;;;###autoload
328 (defun image-type-available-p (type)
329 "Return non-nil if image type TYPE is available.
330 Image types are symbols like `xbm' or `jpeg'."
331 (and (fboundp 'init-image-library)
332 (init-image-library type image-library-alist)))
333
334
335 ;;;###autoload
336 (defun image-type-auto-detected-p ()
337 "Return t if the current buffer contains an auto-detectable image.
338 This function is intended to be used from `magic-fallback-mode-alist'.
339
340 The buffer is considered to contain an auto-detectable image if
341 its beginning matches an image type in `image-type-header-regexps',
342 and that image type is present in `image-type-auto-detectable'."
343 (let* ((type (image-type-from-buffer))
344 (auto (and type (cdr (assq type image-type-auto-detectable)))))
345 (and auto
346 (or (eq auto t) (image-type-available-p type)))))
347
348
349 ;;;###autoload
350 (defun create-image (file-or-data &optional type data-p &rest props)
351 "Create an image.
352 FILE-OR-DATA is an image file name or image data.
353 Optional TYPE is a symbol describing the image type. If TYPE is omitted
354 or nil, try to determine the image type from its first few bytes
355 of image data. If that doesn't work, and FILE-OR-DATA is a file name,
356 use its file extension as image type.
357 Optional DATA-P non-nil means FILE-OR-DATA is a string containing image data.
358 Optional PROPS are additional image attributes to assign to the image,
359 like, e.g. `:mask MASK'.
360 Value is the image created, or nil if images of type TYPE are not supported.
361
362 Images should not be larger than specified by `max-image-size'."
363 (setq type (image-type file-or-data type data-p))
364 (when (image-type-available-p type)
365 (append (list 'image :type type (if data-p :data :file) file-or-data)
366 props)))
367
368
369 ;;;###autoload
370 (defun put-image (image pos &optional string area)
371 "Put image IMAGE in front of POS in the current buffer.
372 IMAGE must be an image created with `create-image' or `defimage'.
373 IMAGE is displayed by putting an overlay into the current buffer with a
374 `before-string' STRING that has a `display' property whose value is the
375 image. STRING is defaulted if you omit it.
376 POS may be an integer or marker.
377 AREA is where to display the image. AREA nil or omitted means
378 display it in the text area, a value of `left-margin' means
379 display it in the left marginal area, a value of `right-margin'
380 means display it in the right marginal area."
381 (unless string (setq string "x"))
382 (let ((buffer (current-buffer)))
383 (unless (eq (car-safe image) 'image)
384 (error "Not an image: %s" image))
385 (unless (or (null area) (memq area '(left-margin right-margin)))
386 (error "Invalid area %s" area))
387 (setq string (copy-sequence string))
388 (let ((overlay (make-overlay pos pos buffer))
389 (prop (if (null area) image (list (list 'margin area) image))))
390 (put-text-property 0 (length string) 'display prop string)
391 (overlay-put overlay 'put-image t)
392 (overlay-put overlay 'before-string string))))
393
394
395 ;;;###autoload
396 (defun insert-image (image &optional string area slice)
397 "Insert IMAGE into current buffer at point.
398 IMAGE is displayed by inserting STRING into the current buffer
399 with a `display' property whose value is the image. STRING is
400 defaulted if you omit it.
401 AREA is where to display the image. AREA nil or omitted means
402 display it in the text area, a value of `left-margin' means
403 display it in the left marginal area, a value of `right-margin'
404 means display it in the right marginal area.
405 SLICE specifies slice of IMAGE to insert. SLICE nil or omitted
406 means insert whole image. SLICE is a list (X Y WIDTH HEIGHT)
407 specifying the X and Y positions and WIDTH and HEIGHT of image area
408 to insert. A float value 0.0 - 1.0 means relative to the width or
409 height of the image; integer values are taken as pixel values."
410 ;; Use a space as least likely to cause trouble when it's a hidden
411 ;; character in the buffer.
412 (unless string (setq string " "))
413 (unless (eq (car-safe image) 'image)
414 (error "Not an image: %s" image))
415 (unless (or (null area) (memq area '(left-margin right-margin)))
416 (error "Invalid area %s" area))
417 (if area
418 (setq image (list (list 'margin area) image))
419 ;; Cons up a new spec equal but not eq to `image' so that
420 ;; inserting it twice in a row (adjacently) displays two copies of
421 ;; the image. Don't try to avoid this by looking at the display
422 ;; properties on either side so that we DTRT more often with
423 ;; cut-and-paste. (Yanking killed image text next to another copy
424 ;; of it loses anyway.)
425 (setq image (cons 'image (cdr image))))
426 (let ((start (point)))
427 (insert string)
428 (add-text-properties start (point)
429 `(display ,(if slice
430 (list (cons 'slice slice) image)
431 image) rear-nonsticky (display)))))
432
433
434 ;;;###autoload
435 (defun insert-sliced-image (image &optional string area rows cols)
436 "Insert IMAGE into current buffer at point.
437 IMAGE is displayed by inserting STRING into the current buffer
438 with a `display' property whose value is the image. STRING is
439 defaulted if you omit it.
440 AREA is where to display the image. AREA nil or omitted means
441 display it in the text area, a value of `left-margin' means
442 display it in the left marginal area, a value of `right-margin'
443 means display it in the right marginal area.
444 The image is automatically split into ROW x COLS slices."
445 (unless string (setq string " "))
446 (unless (eq (car-safe image) 'image)
447 (error "Not an image: %s" image))
448 (unless (or (null area) (memq area '(left-margin right-margin)))
449 (error "Invalid area %s" area))
450 (if area
451 (setq image (list (list 'margin area) image))
452 ;; Cons up a new spec equal but not eq to `image' so that
453 ;; inserting it twice in a row (adjacently) displays two copies of
454 ;; the image. Don't try to avoid this by looking at the display
455 ;; properties on either side so that we DTRT more often with
456 ;; cut-and-paste. (Yanking killed image text next to another copy
457 ;; of it loses anyway.)
458 (setq image (cons 'image (cdr image))))
459 (let ((x 0.0) (dx (/ 1.0001 (or cols 1)))
460 (y 0.0) (dy (/ 1.0001 (or rows 1))))
461 (while (< y 1.0)
462 (while (< x 1.0)
463 (let ((start (point)))
464 (insert string)
465 (add-text-properties start (point)
466 `(display ,(list (list 'slice x y dx dy) image)
467 rear-nonsticky (display)))
468 (setq x (+ x dx))))
469 (setq x 0.0
470 y (+ y dy))
471 (insert (propertize "\n" 'line-height t)))))
472
473
474
475 ;;;###autoload
476 (defun remove-images (start end &optional buffer)
477 "Remove images between START and END in BUFFER.
478 Remove only images that were put in BUFFER with calls to `put-image'.
479 BUFFER nil or omitted means use the current buffer."
480 (unless buffer
481 (setq buffer (current-buffer)))
482 (let ((overlays (overlays-in start end)))
483 (while overlays
484 (let ((overlay (car overlays)))
485 (when (overlay-get overlay 'put-image)
486 (delete-overlay overlay)))
487 (setq overlays (cdr overlays)))))
488
489 (defun image-search-load-path (file &optional path)
490 (unless path
491 (setq path image-load-path))
492 (let (element found filename)
493 (while (and (not found) (consp path))
494 (setq element (car path))
495 (cond
496 ((stringp element)
497 (setq found
498 (file-readable-p
499 (setq filename (expand-file-name file element)))))
500 ((and (symbolp element) (boundp element))
501 (setq element (symbol-value element))
502 (cond
503 ((stringp element)
504 (setq found
505 (file-readable-p
506 (setq filename (expand-file-name file element)))))
507 ((consp element)
508 (if (setq filename (image-search-load-path file element))
509 (setq found t))))))
510 (setq path (cdr path)))
511 (if found filename)))
512
513 ;;;###autoload
514 (defun find-image (specs)
515 "Find an image, choosing one of a list of image specifications.
516
517 SPECS is a list of image specifications.
518
519 Each image specification in SPECS is a property list. The contents of
520 a specification are image type dependent. All specifications must at
521 least contain the properties `:type TYPE' and either `:file FILE' or
522 `:data DATA', where TYPE is a symbol specifying the image type,
523 e.g. `xbm', FILE is the file to load the image from, and DATA is a
524 string containing the actual image data. The specification whose TYPE
525 is supported, and FILE exists, is used to construct the image
526 specification to be returned. Return nil if no specification is
527 satisfied.
528
529 The image is looked for in `image-load-path'.
530
531 Image files should not be larger than specified by `max-image-size'."
532 (let (image)
533 (while (and specs (null image))
534 (let* ((spec (car specs))
535 (type (plist-get spec :type))
536 (data (plist-get spec :data))
537 (file (plist-get spec :file))
538 found)
539 (when (image-type-available-p type)
540 (cond ((stringp file)
541 (if (setq found (image-search-load-path file))
542 (setq image
543 (cons 'image (plist-put (copy-sequence spec)
544 :file found)))))
545 ((not (null data))
546 (setq image (cons 'image spec)))))
547 (setq specs (cdr specs))))
548 image))
549
550
551 ;;;###autoload
552 (defmacro defimage (symbol specs &optional doc)
553 "Define SYMBOL as an image.
554
555 SPECS is a list of image specifications. DOC is an optional
556 documentation string.
557
558 Each image specification in SPECS is a property list. The contents of
559 a specification are image type dependent. All specifications must at
560 least contain the properties `:type TYPE' and either `:file FILE' or
561 `:data DATA', where TYPE is a symbol specifying the image type,
562 e.g. `xbm', FILE is the file to load the image from, and DATA is a
563 string containing the actual image data. The first image
564 specification whose TYPE is supported, and FILE exists, is used to
565 define SYMBOL.
566
567 Example:
568
569 (defimage test-image ((:type xpm :file \"~/test1.xpm\")
570 (:type xbm :file \"~/test1.xbm\")))"
571 (declare (doc-string 3))
572 `(defvar ,symbol (find-image ',specs) ,doc))
573
574
575 (provide 'image)
576
577 ;; arch-tag: 8e76a07b-eb48-4f3e-a7a0-1a7ba9f096b3
578 ;;; image.el ends here