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