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