image.el 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. ;;; image.el --- image API -*- lexical-binding:t -*-
  2. ;; Copyright (C) 1998-2017 Free Software Foundation, Inc.
  3. ;; Maintainer: emacs-devel@gnu.org
  4. ;; Keywords: multimedia
  5. ;; Package: emacs
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;;; Code:
  19. (defgroup image ()
  20. "Image support."
  21. :group 'multimedia)
  22. (defalias 'image-refresh 'image-flush)
  23. (defconst image-type-header-regexps
  24. `(("\\`/[\t\n\r ]*\\*.*XPM.\\*/" . xpm)
  25. ("\\`P[1-6]\\(?:\
  26. \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[[:space:]]\\)+\
  27. \\(?:\\(?:#[^\r\n]*[\r\n]\\)?[0-9]\\)+\
  28. \\)\\{2\\}" . pbm)
  29. ("\\`GIF8[79]a" . gif)
  30. ("\\`\x89PNG\r\n\x1a\n" . png)
  31. ("\\`[\t\n\r ]*#define \\([a-z0-9_]+\\)_width [0-9]+\n\
  32. #define \\1_height [0-9]+\n\\(\
  33. #define \\1_x_hot [0-9]+\n\
  34. #define \\1_y_hot [0-9]+\n\\)?\
  35. static \\(unsigned \\)?char \\1_bits" . xbm)
  36. ("\\`\\(?:MM\0\\*\\|II\\*\0\\)" . tiff)
  37. ("\\`[\t\n\r ]*%!PS" . postscript)
  38. ("\\`\xff\xd8" . jpeg) ; used to be (image-jpeg-p . jpeg)
  39. (,(let* ((incomment-re "\\(?:[^-]\\|-[^-]\\)")
  40. (comment-re (concat "\\(?:!--" incomment-re "*-->[ \t\r\n]*<\\)")))
  41. (concat "\\(?:<\\?xml[ \t\r\n]+[^>]*>\\)?[ \t\r\n]*<"
  42. comment-re "*"
  43. "\\(?:!DOCTYPE[ \t\r\n]+[^>]*>[ \t\r\n]*<[ \t\r\n]*" comment-re "*\\)?"
  44. "[Ss][Vv][Gg]"))
  45. . svg)
  46. )
  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. (defvar image-type-file-name-regexps
  54. '(("\\.png\\'" . png)
  55. ("\\.gif\\'" . gif)
  56. ("\\.jpe?g\\'" . jpeg)
  57. ("\\.bmp\\'" . bmp)
  58. ("\\.xpm\\'" . xpm)
  59. ("\\.pbm\\'" . pbm)
  60. ("\\.xbm\\'" . xbm)
  61. ("\\.ps\\'" . postscript)
  62. ("\\.tiff?\\'" . tiff)
  63. ("\\.svgz?\\'" . svg)
  64. )
  65. "Alist of (REGEXP . IMAGE-TYPE) pairs used to identify image files.
  66. When the name of an image file match REGEXP, it is assumed to
  67. be of image type IMAGE-TYPE.")
  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. (svg . maybe)
  81. (postscript . nil))
  82. "Alist of (IMAGE-TYPE . AUTODETECT) pairs used to auto-detect image files.
  83. \(See `image-type-auto-detected-p').
  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. (defvar image-format-suffixes
  90. '((image/x-rgb "rgb") (image/x-icon "ico"))
  91. "An alist associating image types with file name suffixes.
  92. This is used as a hint by the ImageMagick library when detecting
  93. the type of image data (that does not have an associated file name).
  94. Each element has the form (MIME-CONTENT-TYPE EXTENSION).
  95. If `create-image' is called with a :format attribute whose value
  96. equals a content-type found in this list, the ImageMagick library is
  97. told that the data would have the associated suffix if saved to a file.")
  98. (defcustom image-load-path
  99. (list (file-name-as-directory (expand-file-name "images" data-directory))
  100. 'data-directory 'load-path)
  101. "List of locations in which to search for image files.
  102. If an element is a string, it defines a directory to search.
  103. If an element is a variable symbol whose value is a string, that
  104. value defines a directory to search.
  105. If an element is a variable symbol whose value is a list, the
  106. value is used as a list of directories to search.
  107. Subdirectories are not automatically included in the search."
  108. :type '(repeat (choice directory variable))
  109. :initialize #'custom-initialize-delay)
  110. (defcustom image-scaling-factor 'auto
  111. "When displaying images, apply this scaling factor before displaying.
  112. This is not supported for all image types, and is mostly useful
  113. when you have a high-resolution monitor.
  114. The value is either a floating point number (where numbers higher
  115. than 1 means to increase the size and lower means to shrink the
  116. size), or the symbol `auto', which will compute a scaling factor
  117. based on the font pixel size."
  118. :type '(choice number
  119. (const :tag "Automatically compute" auto))
  120. :version "26.1")
  121. ;; Map put into text properties on images.
  122. (defvar image-map
  123. (let ((map (make-sparse-keymap)))
  124. (define-key map "-" 'image-decrease-size)
  125. (define-key map "+" 'image-increase-size)
  126. (define-key map "r" 'image-rotate)
  127. (define-key map "o" 'image-save)
  128. map))
  129. (defun image-load-path-for-library (library image &optional path no-error)
  130. "Return a suitable search path for images used by LIBRARY.
  131. It searches for IMAGE in `image-load-path' (excluding
  132. \"`data-directory'/images\") and `load-path', followed by a path
  133. suitable for LIBRARY, which includes \"../../etc/images\" and
  134. \"../etc/images\" relative to the library file itself, and then
  135. in \"`data-directory'/images\".
  136. Then this function returns a list of directories which contains
  137. first the directory in which IMAGE was found, followed by the
  138. value of `load-path'. If PATH is given, it is used instead of
  139. `load-path'.
  140. If NO-ERROR is non-nil and a suitable path can't be found, don't
  141. signal an error. Instead, return a list of directories as before,
  142. except that nil appears in place of the image directory.
  143. Here is an example that uses a common idiom to provide
  144. compatibility with versions of Emacs that lack the variable
  145. `image-load-path':
  146. ;; Shush compiler.
  147. (defvar image-load-path)
  148. (let* ((load-path (image-load-path-for-library \"mh-e\" \"mh-logo.xpm\"))
  149. (image-load-path (cons (car load-path)
  150. (when (boundp \\='image-load-path)
  151. image-load-path))))
  152. (mh-tool-bar-folder-buttons-init))"
  153. (unless library (error "No library specified"))
  154. (unless image (error "No image specified"))
  155. (let (image-directory image-directory-load-path)
  156. ;; Check for images in image-load-path or load-path.
  157. (let ((img image)
  158. (dir (or
  159. ;; Images in image-load-path.
  160. (image-search-load-path image)
  161. ;; Images in load-path.
  162. (locate-library image)))
  163. parent)
  164. ;; Since the image might be in a nested directory (for
  165. ;; example, mail/attach.pbm), adjust `image-directory'
  166. ;; accordingly.
  167. (when dir
  168. (setq dir (file-name-directory dir))
  169. (while (setq parent (file-name-directory img))
  170. (setq img (directory-file-name parent)
  171. dir (expand-file-name "../" dir))))
  172. (setq image-directory-load-path dir))
  173. ;; If `image-directory-load-path' isn't Emacs's image directory,
  174. ;; it's probably a user preference, so use it. Then use a
  175. ;; relative setting if possible; otherwise, use
  176. ;; `image-directory-load-path'.
  177. (cond
  178. ;; User-modified image-load-path?
  179. ((and image-directory-load-path
  180. (not (equal image-directory-load-path
  181. (file-name-as-directory
  182. (expand-file-name "images" data-directory)))))
  183. (setq image-directory image-directory-load-path))
  184. ;; Try relative setting.
  185. ((let (library-name d1ei d2ei)
  186. ;; First, find library in the load-path.
  187. (setq library-name (locate-library library))
  188. (if (not library-name)
  189. (error "Cannot find library %s in load-path" library))
  190. ;; And then set image-directory relative to that.
  191. (setq
  192. ;; Go down 2 levels.
  193. d2ei (file-name-as-directory
  194. (expand-file-name
  195. (concat (file-name-directory library-name) "../../etc/images")))
  196. ;; Go down 1 level.
  197. d1ei (file-name-as-directory
  198. (expand-file-name
  199. (concat (file-name-directory library-name) "../etc/images"))))
  200. (setq image-directory
  201. ;; Set it to nil if image is not found.
  202. (cond ((file-exists-p (expand-file-name image d2ei)) d2ei)
  203. ((file-exists-p (expand-file-name image d1ei)) d1ei)))))
  204. ;; Use Emacs's image directory.
  205. (image-directory-load-path
  206. (setq image-directory image-directory-load-path))
  207. (no-error
  208. (message "Could not find image %s for library %s" image library))
  209. (t
  210. (error "Could not find image %s for library %s" image library)))
  211. ;; Return an augmented `path' or `load-path'.
  212. (nconc (list image-directory)
  213. (delete image-directory (copy-sequence (or path load-path))))))
  214. ;; Used to be in image-type-header-regexps, but now not used anywhere
  215. ;; (since 2009-08-28).
  216. (defun image-jpeg-p (data)
  217. "Value is non-nil if DATA, a string, consists of JFIF image data.
  218. We accept the tag Exif because that is the same format."
  219. (setq data (ignore-errors (string-to-unibyte data)))
  220. (when (and data (string-match-p "\\`\xff\xd8" data))
  221. (catch 'jfif
  222. (let ((len (length data)) (i 2))
  223. (while (< i len)
  224. (when (/= (aref data i) #xff)
  225. (throw 'jfif nil))
  226. (setq i (1+ i))
  227. (when (>= (+ i 2) len)
  228. (throw 'jfif nil))
  229. (let ((nbytes (+ (lsh (aref data (+ i 1)) 8)
  230. (aref data (+ i 2))))
  231. (code (aref data i)))
  232. (when (and (>= code #xe0) (<= code #xef))
  233. ;; APP0 LEN1 LEN2 "JFIF\0"
  234. (throw 'jfif
  235. (string-match-p "JFIF\\|Exif"
  236. (substring data i (min (+ i nbytes) len)))))
  237. (setq i (+ i 1 nbytes))))))))
  238. ;;;###autoload
  239. (defun image-type-from-data (data)
  240. "Determine the image type from image data DATA.
  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. (while types
  246. (let ((regexp (car (car types)))
  247. (image-type (cdr (car types))))
  248. (if (or (and (symbolp image-type)
  249. (string-match-p regexp data))
  250. (and (consp image-type)
  251. (funcall (car image-type) data)
  252. (setq image-type (cdr image-type))))
  253. (setq type image-type
  254. types nil)
  255. (setq types (cdr types)))))
  256. type))
  257. ;;;###autoload
  258. (defun image-type-from-buffer ()
  259. "Determine the image type from data in the current buffer.
  260. Value is a symbol specifying the image type or nil if type cannot
  261. be determined."
  262. (let ((types image-type-header-regexps)
  263. type
  264. (opoint (point)))
  265. (goto-char (point-min))
  266. (while types
  267. (let ((regexp (car (car types)))
  268. (image-type (cdr (car types)))
  269. data)
  270. (if (or (and (symbolp image-type)
  271. (looking-at-p regexp))
  272. (and (consp image-type)
  273. (funcall (car image-type)
  274. (or data
  275. (setq data
  276. (buffer-substring
  277. (point-min)
  278. (min (point-max)
  279. (+ (point-min) 256))))))
  280. (setq image-type (cdr image-type))))
  281. (setq type image-type
  282. types nil)
  283. (setq types (cdr types)))))
  284. (goto-char opoint)
  285. (and type
  286. (boundp 'image-types)
  287. (memq type image-types)
  288. type)))
  289. ;;;###autoload
  290. (defun image-type-from-file-header (file)
  291. "Determine the type of image file FILE from its first few bytes.
  292. Value is a symbol specifying the image type, or nil if type cannot
  293. be determined."
  294. (unless (or (file-readable-p file)
  295. (file-name-absolute-p file))
  296. (setq file (image-search-load-path file)))
  297. (and file
  298. (file-readable-p file)
  299. (with-temp-buffer
  300. (set-buffer-multibyte nil)
  301. (insert-file-contents-literally file nil 0 256)
  302. (image-type-from-buffer))))
  303. ;;;###autoload
  304. (defun image-type-from-file-name (file)
  305. "Determine the type of image file FILE from its name.
  306. Value is a symbol specifying the image type, or nil if type cannot
  307. be determined."
  308. (let (type first (case-fold-search t))
  309. (catch 'found
  310. (dolist (elem image-type-file-name-regexps first)
  311. (when (string-match-p (car elem) file)
  312. (if (image-type-available-p (setq type (cdr elem)))
  313. (throw 'found type)
  314. ;; If nothing seems to be supported, return first type that matched.
  315. (or first (setq first type))))))))
  316. ;;;###autoload
  317. (defun image-type (source &optional type data-p)
  318. "Determine and return image type.
  319. SOURCE is an image file name or image data.
  320. Optional TYPE is a symbol describing the image type. If TYPE is omitted
  321. or nil, try to determine the image type from its first few bytes
  322. of image data. If that doesn't work, and SOURCE is a file name,
  323. use its file extension as image type.
  324. Optional DATA-P non-nil means SOURCE is a string containing image data."
  325. (when (and (not data-p) (not (stringp source)))
  326. (error "Invalid image file name `%s'" source))
  327. (unless type
  328. (setq type (if data-p
  329. (image-type-from-data source)
  330. (or (image-type-from-file-header source)
  331. (image-type-from-file-name source))))
  332. (or type (error "Cannot determine image type")))
  333. (or (memq type (and (boundp 'image-types) image-types))
  334. (error "Invalid image type `%s'" type))
  335. type)
  336. (if (fboundp 'image-metadata) ; eg not --without-x
  337. (define-obsolete-function-alias 'image-extension-data
  338. 'image-metadata "24.1"))
  339. (define-obsolete-variable-alias
  340. 'image-library-alist
  341. 'dynamic-library-alist "24.1")
  342. ;;;###autoload
  343. (defun image-type-available-p (type)
  344. "Return non-nil if image type TYPE is available.
  345. Image types are symbols like `xbm' or `jpeg'."
  346. (and (fboundp 'init-image-library)
  347. (init-image-library type)))
  348. ;;;###autoload
  349. (defun image-type-auto-detected-p ()
  350. "Return t if the current buffer contains an auto-detectable image.
  351. This function is intended to be used from `magic-fallback-mode-alist'.
  352. The buffer is considered to contain an auto-detectable image if
  353. its beginning matches an image type in `image-type-header-regexps',
  354. and that image type is present in `image-type-auto-detectable' with a
  355. non-nil value. If that value is non-nil, but not t, then the image type
  356. must be available."
  357. (let* ((type (image-type-from-buffer))
  358. (auto (and type (cdr (assq type image-type-auto-detectable)))))
  359. (and auto
  360. (or (eq auto t) (image-type-available-p type)))))
  361. ;;;###autoload
  362. (defun create-image (file-or-data &optional type data-p &rest props)
  363. "Create an image.
  364. FILE-OR-DATA is an image file name or image data.
  365. Optional TYPE is a symbol describing the image type. If TYPE is omitted
  366. or nil, try to determine the image type from its first few bytes
  367. of image data. If that doesn't work, and FILE-OR-DATA is a file name,
  368. use its file extension as image type.
  369. Optional DATA-P non-nil means FILE-OR-DATA is a string containing image data.
  370. Optional PROPS are additional image attributes to assign to the image,
  371. like, e.g. `:mask MASK'.
  372. Value is the image created, or nil if images of type TYPE are not supported.
  373. Images should not be larger than specified by `max-image-size'.
  374. Image file names that are not absolute are searched for in the
  375. \"images\" sub-directory of `data-directory' and
  376. `x-bitmap-file-path' (in that order)."
  377. ;; It is x_find_image_file in image.c that sets the search path.
  378. (setq type (image-type file-or-data type data-p))
  379. (when (image-type-available-p type)
  380. (append (list 'image :type type (if data-p :data :file) file-or-data)
  381. (and (not (plist-get props :scale))
  382. (list :scale
  383. (image-compute-scaling-factor image-scaling-factor)))
  384. props)))
  385. (defun image--set-property (image property value)
  386. "Set PROPERTY in IMAGE to VALUE.
  387. Internal use only."
  388. (if (null value)
  389. (while (cdr image)
  390. ;; IMAGE starts with the symbol `image', and the rest is a
  391. ;; plist. Decouple plist entries where the key matches
  392. ;; the property.
  393. (if (eq (cadr image) property)
  394. (setcdr image (cddr image))
  395. (setq image (cddr image))))
  396. ;; Just enter the new value.
  397. (plist-put (cdr image) property value))
  398. value)
  399. (defun image-property (image property)
  400. "Return the value of PROPERTY in IMAGE.
  401. Properties can be set with
  402. (setf (image-property IMAGE PROPERTY) VALUE)
  403. If VALUE is nil, PROPERTY is removed from IMAGE."
  404. (declare (gv-setter image--set-property))
  405. (plist-get (cdr image) property))
  406. (defun image-compute-scaling-factor (scaling)
  407. (cond
  408. ((numberp scaling) scaling)
  409. ((eq scaling 'auto)
  410. (let ((width (/ (float (window-width nil t)) (window-width))))
  411. ;; If we assume that a typical character is 10 pixels in width,
  412. ;; then we should scale all images according to how wide they
  413. ;; are. But don't scale images down.
  414. (if (< width 10)
  415. 1
  416. (/ (float width) 10))))
  417. (t
  418. (error "Invalid scaling factor %s" scaling))))
  419. ;;;###autoload
  420. (defun put-image (image pos &optional string area)
  421. "Put image IMAGE in front of POS in the current buffer.
  422. IMAGE must be an image created with `create-image' or `defimage'.
  423. IMAGE is displayed by putting an overlay into the current buffer with a
  424. `before-string' STRING that has a `display' property whose value is the
  425. image. STRING is defaulted if you omit it.
  426. The overlay created will have the `put-image' property set to t.
  427. POS may be an integer or marker.
  428. AREA is where to display the image. AREA nil or omitted means
  429. display it in the text area, a value of `left-margin' means
  430. display it in the left marginal area, a value of `right-margin'
  431. means display it in the right marginal area."
  432. (unless string (setq string "x"))
  433. (let ((buffer (current-buffer)))
  434. (unless (eq (car-safe image) 'image)
  435. (error "Not an image: %s" image))
  436. (unless (or (null area) (memq area '(left-margin right-margin)))
  437. (error "Invalid area %s" area))
  438. (setq string (copy-sequence string))
  439. (let ((overlay (make-overlay pos pos buffer))
  440. (prop (if (null area) image (list (list 'margin area) image))))
  441. (put-text-property 0 (length string) 'display prop string)
  442. (overlay-put overlay 'put-image t)
  443. (overlay-put overlay 'before-string string)
  444. (overlay-put overlay 'map image-map)
  445. overlay)))
  446. ;;;###autoload
  447. (defun insert-image (image &optional string area slice)
  448. "Insert IMAGE into current buffer at point.
  449. IMAGE is displayed by inserting STRING into the current buffer
  450. with a `display' property whose value is the image. STRING
  451. defaults to a single space if you omit it.
  452. AREA is where to display the image. AREA nil or omitted means
  453. display it in the text area, a value of `left-margin' means
  454. display it in the left marginal area, a value of `right-margin'
  455. means display it in the right marginal area.
  456. SLICE specifies slice of IMAGE to insert. SLICE nil or omitted
  457. means insert whole image. SLICE is a list (X Y WIDTH HEIGHT)
  458. specifying the X and Y positions and WIDTH and HEIGHT of image area
  459. to insert. A float value 0.0 - 1.0 means relative to the width or
  460. height of the image; integer values are taken as pixel values."
  461. ;; Use a space as least likely to cause trouble when it's a hidden
  462. ;; character in the buffer.
  463. (unless string (setq string " "))
  464. (unless (eq (car-safe image) 'image)
  465. (error "Not an image: %s" image))
  466. (unless (or (null area) (memq area '(left-margin right-margin)))
  467. (error "Invalid area %s" area))
  468. (if area
  469. (setq image (list (list 'margin area) image))
  470. ;; Cons up a new spec equal but not eq to `image' so that
  471. ;; inserting it twice in a row (adjacently) displays two copies of
  472. ;; the image. Don't try to avoid this by looking at the display
  473. ;; properties on either side so that we DTRT more often with
  474. ;; cut-and-paste. (Yanking killed image text next to another copy
  475. ;; of it loses anyway.)
  476. (setq image (cons 'image (cdr image))))
  477. (let ((start (point)))
  478. (insert string)
  479. (add-text-properties start (point)
  480. `(display ,(if slice
  481. (list (cons 'slice slice) image)
  482. image)
  483. rear-nonsticky (display)
  484. keymap ,image-map))))
  485. ;;;###autoload
  486. (defun insert-sliced-image (image &optional string area rows cols)
  487. "Insert IMAGE into current buffer at point.
  488. IMAGE is displayed by inserting STRING into the current buffer
  489. with a `display' property whose value is the image. The default
  490. STRING is a single space.
  491. AREA is where to display the image. AREA nil or omitted means
  492. display it in the text area, a value of `left-margin' means
  493. display it in the left marginal area, a value of `right-margin'
  494. means display it in the right marginal area.
  495. The image is automatically split into ROWS x COLS slices."
  496. (unless string (setq string " "))
  497. (unless (eq (car-safe image) 'image)
  498. (error "Not an image: %s" image))
  499. (unless (or (null area) (memq area '(left-margin right-margin)))
  500. (error "Invalid area %s" area))
  501. (if area
  502. (setq image (list (list 'margin area) image))
  503. ;; Cons up a new spec equal but not eq to `image' so that
  504. ;; inserting it twice in a row (adjacently) displays two copies of
  505. ;; the image. Don't try to avoid this by looking at the display
  506. ;; properties on either side so that we DTRT more often with
  507. ;; cut-and-paste. (Yanking killed image text next to another copy
  508. ;; of it loses anyway.)
  509. (setq image (cons 'image (cdr image))))
  510. (let ((x 0.0) (dx (/ 1.0001 (or cols 1)))
  511. (y 0.0) (dy (/ 1.0001 (or rows 1))))
  512. (while (< y 1.0)
  513. (while (< x 1.0)
  514. (let ((start (point)))
  515. (insert string)
  516. (add-text-properties start (point)
  517. `(display ,(list (list 'slice x y dx dy) image)
  518. rear-nonsticky (display)
  519. keymap ,image-map))
  520. (setq x (+ x dx))))
  521. (setq x 0.0
  522. y (+ y dy))
  523. (insert (propertize "\n" 'line-height t)))))
  524. ;;;###autoload
  525. (defun remove-images (start end &optional buffer)
  526. "Remove images between START and END in BUFFER.
  527. Remove only images that were put in BUFFER with calls to `put-image'.
  528. BUFFER nil or omitted means use the current buffer."
  529. (unless buffer
  530. (setq buffer (current-buffer)))
  531. (let ((overlays (overlays-in start end)))
  532. (while overlays
  533. (let ((overlay (car overlays)))
  534. (when (overlay-get overlay 'put-image)
  535. (delete-overlay overlay)))
  536. (setq overlays (cdr overlays)))))
  537. (defun image-search-load-path (file &optional path)
  538. (unless path
  539. (setq path image-load-path))
  540. (let (element found filename)
  541. (while (and (not found) (consp path))
  542. (setq element (car path))
  543. (cond
  544. ((stringp element)
  545. (setq found
  546. (file-readable-p
  547. (setq filename (expand-file-name file element)))))
  548. ((and (symbolp element) (boundp element))
  549. (setq element (symbol-value element))
  550. (cond
  551. ((stringp element)
  552. (setq found
  553. (file-readable-p
  554. (setq filename (expand-file-name file element)))))
  555. ((consp element)
  556. (if (setq filename (image-search-load-path file element))
  557. (setq found t))))))
  558. (setq path (cdr path)))
  559. (if found filename)))
  560. ;;;###autoload
  561. (defun find-image (specs)
  562. "Find an image, choosing one of a list of image specifications.
  563. SPECS is a list of image specifications.
  564. Each image specification in SPECS is a property list. The contents of
  565. a specification are image type dependent. All specifications must at
  566. least contain the properties `:type TYPE' and either `:file FILE' or
  567. `:data DATA', where TYPE is a symbol specifying the image type,
  568. e.g. `xbm', FILE is the file to load the image from, and DATA is a
  569. string containing the actual image data. The specification whose TYPE
  570. is supported, and FILE exists, is used to construct the image
  571. specification to be returned. Return nil if no specification is
  572. satisfied.
  573. The image is looked for in `image-load-path'.
  574. Image files should not be larger than specified by `max-image-size'."
  575. (let (image)
  576. (while (and specs (null image))
  577. (let* ((spec (car specs))
  578. (type (plist-get spec :type))
  579. (data (plist-get spec :data))
  580. (file (plist-get spec :file))
  581. found)
  582. (when (image-type-available-p type)
  583. (cond ((stringp file)
  584. (if (setq found (image-search-load-path file))
  585. (setq image
  586. (cons 'image (plist-put (copy-sequence spec)
  587. :file found)))))
  588. ((not (null data))
  589. (setq image (cons 'image spec)))))
  590. (setq specs (cdr specs))))
  591. image))
  592. ;;;###autoload
  593. (defmacro defimage (symbol specs &optional doc)
  594. "Define SYMBOL as an image, and return SYMBOL.
  595. SPECS is a list of image specifications. DOC is an optional
  596. documentation string.
  597. Each image specification in SPECS is a property list. The contents of
  598. a specification are image type dependent. All specifications must at
  599. least contain the properties `:type TYPE' and either `:file FILE' or
  600. `:data DATA', where TYPE is a symbol specifying the image type,
  601. e.g. `xbm', FILE is the file to load the image from, and DATA is a
  602. string containing the actual image data. The first image
  603. specification whose TYPE is supported, and FILE exists, is used to
  604. define SYMBOL.
  605. Example:
  606. (defimage test-image ((:type xpm :file \"~/test1.xpm\")
  607. (:type xbm :file \"~/test1.xbm\")))"
  608. (declare (doc-string 3))
  609. `(defvar ,symbol (find-image ',specs) ,doc))
  610. ;;; Animated image API
  611. (defvar image-default-frame-delay 0.1
  612. "Default interval in seconds between frames of a multi-frame image.
  613. Only used if the image does not specify a value.")
  614. (defun image-multi-frame-p (image)
  615. "Return non-nil if IMAGE contains more than one frame.
  616. The actual return value is a cons (NIMAGES . DELAY), where NIMAGES is
  617. the number of frames (or sub-images) in the image and DELAY is the delay
  618. in seconds that the image specifies between each frame. DELAY may be nil,
  619. in which case you might want to use `image-default-frame-delay'."
  620. (when (fboundp 'image-metadata)
  621. (let* ((metadata (image-metadata image))
  622. (images (plist-get metadata 'count))
  623. (delay (plist-get metadata 'delay)))
  624. (when (and images (> images 1))
  625. (and delay (or (not (numberp delay)) (< delay 0))
  626. (setq delay image-default-frame-delay))
  627. (cons images delay)))))
  628. (defun image-animated-p (image)
  629. "Like `image-multi-frame-p', but returns nil if no delay is specified."
  630. (let ((multi (image-multi-frame-p image)))
  631. (and (cdr multi) multi)))
  632. (make-obsolete 'image-animated-p 'image-multi-frame-p "24.4")
  633. ;; "Destructively"?
  634. (defun image-animate (image &optional index limit)
  635. "Start animating IMAGE.
  636. Animation occurs by destructively altering the IMAGE spec list.
  637. With optional INDEX, begin animating from that animation frame.
  638. LIMIT specifies how long to animate the image. If omitted or
  639. nil, play the animation until the end. If t, loop forever. If a
  640. number, play until that number of seconds has elapsed."
  641. (let ((animation (image-multi-frame-p image))
  642. timer)
  643. (when animation
  644. (if (setq timer (image-animate-timer image))
  645. (cancel-timer timer))
  646. (plist-put (cdr image) :animate-buffer (current-buffer))
  647. (run-with-timer 0.2 nil #'image-animate-timeout
  648. image (or index 0) (car animation)
  649. 0 limit (+ (float-time) 0.2)))))
  650. (defun image-animate-timer (image)
  651. "Return the animation timer for image IMAGE."
  652. ;; See cancel-function-timers
  653. (let ((tail timer-list) timer)
  654. (while tail
  655. (setq timer (car tail)
  656. tail (cdr tail))
  657. (if (and (eq (timer--function timer) #'image-animate-timeout)
  658. (eq (car-safe (timer--args timer)) image))
  659. (setq tail nil)
  660. (setq timer nil)))
  661. timer))
  662. (defconst image-minimum-frame-delay 0.01
  663. "Minimum interval in seconds between frames of an animated image.")
  664. (defun image-current-frame (image)
  665. "The current frame number of IMAGE, indexed from 0."
  666. (or (plist-get (cdr image) :index) 0))
  667. (defun image-show-frame (image n &optional nocheck)
  668. "Show frame N of IMAGE.
  669. Frames are indexed from 0. Optional argument NOCHECK non-nil means
  670. do not check N is within the range of frames present in the image."
  671. (unless nocheck
  672. (if (< n 0) (setq n 0)
  673. (setq n (min n (1- (car (image-multi-frame-p image)))))))
  674. (plist-put (cdr image) :index n)
  675. (force-window-update))
  676. (defun image-animate-get-speed (image)
  677. "Return the speed factor for animating IMAGE."
  678. (or (plist-get (cdr image) :speed) 1))
  679. (defun image-animate-set-speed (image value &optional multiply)
  680. "Set the speed factor for animating IMAGE to VALUE.
  681. With optional argument MULTIPLY non-nil, treat VALUE as a
  682. multiplication factor for the current value."
  683. (plist-put (cdr image) :speed
  684. (if multiply
  685. (* value (image-animate-get-speed image))
  686. value)))
  687. ;; FIXME? The delay may not be the same for different sub-images,
  688. ;; hence we need to call image-multi-frame-p to return it.
  689. ;; But it also returns count, so why do we bother passing that as an
  690. ;; argument?
  691. (defun image-animate-timeout (image n count time-elapsed limit target-time)
  692. "Display animation frame N of IMAGE.
  693. N=0 refers to the initial animation frame.
  694. COUNT is the total number of frames in the animation.
  695. TIME-ELAPSED is the total time that has elapsed since
  696. `image-animate-start' was called.
  697. LIMIT determines when to stop. If t, loop forever. If nil, stop
  698. after displaying the last animation frame. Otherwise, stop
  699. after LIMIT seconds have elapsed.
  700. The minimum delay between successive frames is `image-minimum-frame-delay'.
  701. If the image has a non-nil :speed property, it acts as a multiplier
  702. for the animation speed. A negative value means to animate in reverse."
  703. (when (and (buffer-live-p (plist-get (cdr image) :animate-buffer))
  704. ;; Delayed more than two seconds more than expected.
  705. (or (<= (- (float-time) target-time) 2)
  706. (progn
  707. (message "Stopping animation; animation possibly too big")
  708. nil)))
  709. (image-show-frame image n t)
  710. (let* ((speed (image-animate-get-speed image))
  711. (time (float-time))
  712. (animation (image-multi-frame-p image))
  713. ;; Subtract off the time we took to load the image from the
  714. ;; stated delay time.
  715. (delay (max (+ (* (or (cdr animation) image-default-frame-delay)
  716. (/ 1.0 (abs speed)))
  717. time (- (float-time)))
  718. image-minimum-frame-delay))
  719. done)
  720. (setq n (if (< speed 0)
  721. (1- n)
  722. (1+ n)))
  723. (if limit
  724. (cond ((>= n count) (setq n 0))
  725. ((< n 0) (setq n (1- count))))
  726. (and (or (>= n count) (< n 0)) (setq done t)))
  727. (setq time-elapsed (+ delay time-elapsed))
  728. (if (numberp limit)
  729. (setq done (>= time-elapsed limit)))
  730. (unless done
  731. (run-with-timer delay nil #'image-animate-timeout
  732. image n count time-elapsed limit
  733. (+ (float-time) delay))))))
  734. (defvar imagemagick-types-inhibit)
  735. (defvar imagemagick-enabled-types)
  736. (defun imagemagick-filter-types ()
  737. "Return a list of the ImageMagick types to be treated as images, or nil.
  738. This is the result of `imagemagick-types', including only elements
  739. that match `imagemagick-enabled-types' and do not match
  740. `imagemagick-types-inhibit'."
  741. (when (fboundp 'imagemagick-types)
  742. (cond ((null imagemagick-enabled-types) nil)
  743. ((eq imagemagick-types-inhibit t) nil)
  744. (t
  745. (delq nil
  746. (mapcar
  747. (lambda (type)
  748. (unless (memq type imagemagick-types-inhibit)
  749. (if (eq imagemagick-enabled-types t) type
  750. (catch 'found
  751. (dolist (enable imagemagick-enabled-types nil)
  752. (if (cond ((symbolp enable) (eq enable type))
  753. ((stringp enable)
  754. (string-match enable
  755. (symbol-name type))))
  756. (throw 'found type)))))))
  757. (imagemagick-types)))))))
  758. (defvar imagemagick--file-regexp nil
  759. "File extension regexp for ImageMagick files, if any.
  760. This is the extension installed into `auto-mode-alist' and
  761. `image-type-file-name-regexps' by `imagemagick-register-types'.")
  762. ;;;###autoload
  763. (defun imagemagick-register-types ()
  764. "Register file types that can be handled by ImageMagick.
  765. This function is called at startup, after loading the init file.
  766. It registers the ImageMagick types returned by `imagemagick-filter-types'.
  767. Registered image types are added to `auto-mode-alist', so that
  768. Emacs visits them in Image mode. They are also added to
  769. `image-type-file-name-regexps', so that the `image-type' function
  770. recognizes these files as having image type `imagemagick'.
  771. If Emacs is compiled without ImageMagick support, this does nothing."
  772. (when (fboundp 'imagemagick-types)
  773. (let* ((types (mapcar (lambda (type) (downcase (symbol-name type)))
  774. (imagemagick-filter-types)))
  775. (re (if types (concat "\\." (regexp-opt types) "\\'")))
  776. (ama-elt (car (member (cons imagemagick--file-regexp 'image-mode)
  777. auto-mode-alist)))
  778. (itfnr-elt (car (member (cons imagemagick--file-regexp 'imagemagick)
  779. image-type-file-name-regexps))))
  780. (if (not re)
  781. (setq auto-mode-alist (delete ama-elt auto-mode-alist)
  782. image-type-file-name-regexps
  783. (delete itfnr-elt image-type-file-name-regexps))
  784. (if ama-elt
  785. (setcar ama-elt re)
  786. (push (cons re 'image-mode) auto-mode-alist))
  787. (if itfnr-elt
  788. (setcar itfnr-elt re)
  789. ;; Append to `image-type-file-name-regexps', so that we
  790. ;; preferentially use specialized image libraries.
  791. (add-to-list 'image-type-file-name-regexps
  792. (cons re 'imagemagick) t)))
  793. (setq imagemagick--file-regexp re))))
  794. (defcustom imagemagick-types-inhibit
  795. '(C HTML HTM INFO M TXT PDF)
  796. "List of ImageMagick types that should never be treated as images.
  797. This should be a list of symbols, each of which should be one of
  798. the ImageMagick types listed by `imagemagick-types'. The listed
  799. image types are not registered by `imagemagick-register-types'.
  800. If the value is t, inhibit the use of ImageMagick for images.
  801. If you change this without using customize, you must call
  802. `imagemagick-register-types' afterwards.
  803. If Emacs is compiled without ImageMagick support, this variable
  804. has no effect."
  805. :type '(choice (const :tag "Support all ImageMagick types" nil)
  806. (const :tag "Disable all ImageMagick types" t)
  807. (repeat symbol))
  808. :initialize #'custom-initialize-default
  809. :set (lambda (symbol value)
  810. (set-default symbol value)
  811. (imagemagick-register-types))
  812. :version "24.3")
  813. (defcustom imagemagick-enabled-types
  814. '(3FR ART ARW AVS BMP BMP2 BMP3 CAL CALS CMYK CMYKA CR2 CRW
  815. CUR CUT DCM DCR DCX DDS DJVU DNG DPX EXR FAX FITS GBR GIF
  816. GIF87 GRB HRZ ICB ICO ICON J2C JNG JP2 JPC JPEG JPG JPX K25
  817. KDC MIFF MNG MRW MSL MSVG MTV NEF ORF OTB PBM PCD PCDS PCL
  818. PCT PCX PDB PEF PGM PICT PIX PJPEG PNG PNG24 PNG32 PNG8 PNM
  819. PPM PSD PTIF PWP RAF RAS RBG RGB RGBA RGBO RLA RLE SCR SCT
  820. SFW SGI SR2 SRF SUN SVG SVGZ TGA TIFF TIFF64 TILE TIM TTF
  821. UYVY VDA VICAR VID VIFF VST WBMP WPG X3F XBM XC XCF XPM XV
  822. XWD YCbCr YCbCrA YUV)
  823. "List of ImageMagick types to treat as images.
  824. Each list element should be a string or symbol, representing one
  825. of the image types returned by `imagemagick-types'. If the
  826. element is a string, it is handled as a regexp that enables all
  827. matching types.
  828. The value of `imagemagick-enabled-types' may also be t, meaning
  829. to enable all types that ImageMagick supports.
  830. The variable `imagemagick-types-inhibit' overrides this variable.
  831. If you change this without using customize, you must call
  832. `imagemagick-register-types' afterwards.
  833. If Emacs is compiled without ImageMagick support, this variable
  834. has no effect."
  835. :type '(choice (const :tag "Support all ImageMagick types" t)
  836. (const :tag "Disable all ImageMagick types" nil)
  837. (repeat :tag "List of types"
  838. (choice (symbol :tag "type")
  839. (regexp :tag "regexp"))))
  840. :initialize #'custom-initialize-default
  841. :set (lambda (symbol value)
  842. (set-default symbol value)
  843. (imagemagick-register-types))
  844. :version "24.3")
  845. (imagemagick-register-types)
  846. (defun image-increase-size (n)
  847. "Increase the image size by a factor of N.
  848. If N is 3, then the image size will be increased by 30%. The
  849. default is 20%."
  850. (interactive "P")
  851. (image--change-size (if n
  852. (1+ (/ n 10.0))
  853. 1.2)))
  854. (defun image-decrease-size (n)
  855. "Decrease the image size by a factor of N.
  856. If N is 3, then the image size will be decreased by 30%. The
  857. default is 20%."
  858. (interactive "P")
  859. (image--change-size (if n
  860. (- 1 (/ n 10.0))
  861. 0.8)))
  862. (defun image--get-image ()
  863. (let ((image (get-text-property (point) 'display)))
  864. (unless (eq (car-safe image) 'image)
  865. (error "No image under point"))
  866. image))
  867. (defun image--get-imagemagick-and-warn ()
  868. (unless (fboundp 'imagemagick-types)
  869. (error "Can't rescale images without ImageMagick support"))
  870. (let ((image (image--get-image)))
  871. (image-flush image)
  872. (plist-put (cdr image) :type 'imagemagick)
  873. image))
  874. (defun image--change-size (factor)
  875. (let* ((image (image--get-imagemagick-and-warn))
  876. (new-image (image--image-without-parameters image))
  877. (scale (image--current-scaling image new-image)))
  878. (setcdr image (cdr new-image))
  879. (plist-put (cdr image) :scale (* scale factor))))
  880. (defun image--image-without-parameters (image)
  881. (cons (pop image)
  882. (let ((new nil))
  883. (while image
  884. (let ((key (pop image))
  885. (val (pop image)))
  886. (unless (memq key '(:scale :width :height :max-width :max-height))
  887. (setq new (nconc new (list key val))))))
  888. new)))
  889. (defun image--current-scaling (image new-image)
  890. ;; The image may be scaled due to many reasons (:scale, :max-width,
  891. ;; etc), so find out what the current scaling is based on the
  892. ;; original image size and the displayed size.
  893. (let ((image-width (car (image-size new-image t)))
  894. (display-width (car (image-size image t))))
  895. (/ (float display-width) image-width)))
  896. (defun image-rotate ()
  897. "Rotate the image under point by 90 degrees clockwise."
  898. (interactive)
  899. (let ((image (image--get-imagemagick-and-warn)))
  900. (plist-put (cdr image) :rotation
  901. (float (mod (+ (or (plist-get (cdr image) :rotation) 0) 90)
  902. ;; We don't want to exceed 360 degrees
  903. ;; rotation, because it's not seen as valid
  904. ;; in exif data.
  905. 360)))))
  906. (defun image-save ()
  907. "Save the image under point."
  908. (interactive)
  909. (let ((image (get-text-property (point) 'display)))
  910. (when (or (not (consp image))
  911. (not (eq (car image) 'image)))
  912. (error "No image under point"))
  913. (with-temp-buffer
  914. (let ((file (plist-get (cdr image) :file)))
  915. (if file
  916. (if (not (file-exists-p file))
  917. (error "File %s no longer exists" file)
  918. (insert-file-contents-literally file))
  919. (insert (plist-get (cdr image) :data))))
  920. (write-region (point-min) (point-max)
  921. (read-file-name "Write image to file: ")))))
  922. (provide 'image)
  923. ;;; image.el ends here