XEmacs 21.2.5
[chise/xemacs-chise.git.1] / lisp / font.el
1 ;;; font.el --- New font model
2 ;; Author: wmperry
3 ;; Created: 1997/09/05 15:44:37
4 ;; Version: 1.52
5 ;; Keywords: faces
6
7 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8 ;;; Copyright (c) 1995, 1996 by William M. Perry (wmperry@cs.indiana.edu)
9 ;;; Copyright (c) 1996, 1997 Free Software Foundation, Inc.
10 ;;;
11 ;;; This file is part of GNU Emacs.
12 ;;;
13 ;;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;;; it under the terms of the GNU General Public License as published by
15 ;;; the Free Software Foundation; either version 2, or (at your option)
16 ;;; any later version.
17 ;;;
18 ;;; GNU Emacs is distributed in the hope that it will be useful,
19 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;;; GNU General Public License for more details.
22 ;;;
23 ;;; You should have received a copy of the GNU General Public License
24 ;;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;;; Boston, MA 02111-1307, USA.
27 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28
29 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;;; The emacsen compatibility package - load it up before anything else
31 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
32 (require 'cl)
33
34 (eval-and-compile
35   (defvar device-fonts-cache)
36   (condition-case ()
37       (require 'custom)
38     (error nil))
39   (if (and (featurep 'custom) (fboundp 'custom-declare-variable))
40       nil ;; We've got what we needed
41     ;; We have the old custom-library, hack around it!
42     (defmacro defgroup (&rest args)
43       nil)
44     (defmacro defcustom (var value doc &rest args)
45       `(defvar ,var ,value ,doc))))
46
47 (if (not (fboundp 'try-font-name))
48     (defun try-font-name (fontname &rest args)
49       (case window-system
50         ((x pm) (car-safe (x-list-fonts fontname)))
51         (mswindows (car-safe (mswindows-list-fonts fontname)))
52         (ns (car-safe (ns-list-fonts fontname)))
53         (otherwise nil))))
54
55 (if (not (fboundp 'facep))
56     (defun facep (face)
57       "Return t if X is a face name or an internal face vector."
58       (if (not window-system)
59           nil                           ; FIXME if FSF ever does TTY faces
60         (and (or (internal-facep face)
61                  (and (symbolp face) (assq face global-face-data)))
62              t))))
63
64 (if (not (fboundp 'set-face-property))
65     (defun set-face-property (face property value &optional locale
66                                    tag-set how-to-add)
67       "Change a property of FACE."
68       (and (symbolp face)
69            (put face property value))))
70
71 (if (not (fboundp 'face-property))
72     (defun face-property (face property &optional locale tag-set exact-p)
73       "Return FACE's value of the given PROPERTY."
74       (and (symbolp face) (get face property))))
75
76 (require 'disp-table)
77
78 (if (not (fboundp '<<))   (fset '<< 'lsh))
79 (if (not (fboundp '&))    (fset '& 'logand))
80 (if (not (fboundp '|))    (fset '| 'logior))
81 (if (not (fboundp '~))    (fset '~ 'lognot))
82 (if (not (fboundp '>>))   (defun >> (value count) (<< value (- count))))
83
84 \f
85 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
86 ;;; Lots of variables / keywords for use later in the program
87 ;;; Not much should need to be modified
88 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
89 (defconst font-running-xemacs (string-match "XEmacs" (emacs-version))
90   "Whether we are running in XEmacs or not.")
91
92 (defmacro define-font-keywords (&rest keys)
93   `(eval-and-compile
94      (let ((keywords (quote ,keys)))
95        (while keywords
96          (or (boundp (car keywords))
97              (set (car keywords) (car keywords)))
98          (setq keywords (cdr keywords))))))
99
100 (defconst font-window-system-mappings
101   '((x         . (x-font-create-name x-font-create-object))
102     (ns        . (ns-font-create-name ns-font-create-object))
103     (mswindows . (mswindows-font-create-name mswindows-font-create-object))
104     (pm        . (x-font-create-name x-font-create-object)) ; Change? FIXME
105     (tty       . (tty-font-create-plist tty-font-create-object)))
106   "An assoc list mapping device types to the function used to create
107 a font name from a font structure.")
108
109 (defconst ns-font-weight-mappings
110   '((:extra-light . "extralight")
111     (:light       . "light")
112     (:demi-light  . "demilight")
113     (:medium      . "medium")
114     (:normal      . "medium")
115     (:demi-bold   . "demibold")
116     (:bold        . "bold")
117     (:extra-bold  . "extrabold"))
118   "An assoc list mapping keywords to actual NeXTstep specific
119 information to use")
120
121 (defconst x-font-weight-mappings
122   '((:extra-light . "extralight")
123     (:light       . "light")
124     (:demi-light  . "demilight")
125     (:demi        . "demi")
126     (:book        . "book")
127     (:medium      . "medium")
128     (:normal      . "medium")
129     (:demi-bold   . "demibold")
130     (:bold        . "bold")
131     (:extra-bold  . "extrabold"))
132   "An assoc list mapping keywords to actual Xwindow specific strings
133 for use in the 'weight' field of an X font string.")
134
135 (defconst font-possible-weights
136   (mapcar 'car x-font-weight-mappings))
137
138 (defvar font-rgb-file nil
139   "Where the RGB file was found.")
140
141 (defvar font-maximum-slippage "1pt"
142   "How much a font is allowed to vary from the desired size.")
143
144 (define-font-keywords :family :style :size :registry :encoding)
145
146 (define-font-keywords
147   :weight :extra-light :light :demi-light :medium :normal :demi-bold
148   :bold :extra-bold)
149
150 (defvar font-style-keywords nil)
151
152 (defsubst set-font-family (fontobj family)
153   (aset fontobj 1 family))
154
155 (defsubst set-font-weight (fontobj weight)
156   (aset fontobj 3 weight))
157
158 (defsubst set-font-style (fontobj style)
159   (aset fontobj 5 style))
160
161 (defsubst set-font-size (fontobj size)
162   (aset fontobj 7 size))
163
164 (defsubst set-font-registry (fontobj reg)
165   (aset fontobj 9 reg))
166
167 (defsubst set-font-encoding (fontobj enc)
168   (aset fontobj 11 enc))
169
170 (defsubst font-family (fontobj)
171   (aref fontobj 1))
172
173 (defsubst font-weight (fontobj)
174   (aref fontobj 3))
175
176 (defsubst font-style (fontobj)
177   (aref fontobj 5))
178
179 (defsubst font-size (fontobj)
180   (aref fontobj 7))
181
182 (defsubst font-registry (fontobj)
183   (aref fontobj 9))
184
185 (defsubst font-encoding (fontobj)
186   (aref fontobj 11))
187
188 (eval-when-compile
189   (defmacro define-new-mask (attr mask)
190     `(progn
191        (setq font-style-keywords
192              (cons (cons (quote ,attr)
193                          (cons
194                           (quote ,(intern (format "set-font-%s-p" attr)))
195                           (quote ,(intern (format "font-%s-p" attr)))))
196                    font-style-keywords))
197        (defconst ,(intern (format "font-%s-mask" attr)) (<< 1 ,mask)
198          ,(format
199            "Bitmask for whether a font is to be rendered in %s or not."
200            attr))
201        (defun ,(intern (format "font-%s-p" attr)) (fontobj)
202          ,(format "Whether FONTOBJ will be renderd in `%s' or not." attr)
203          (if (/= 0 (& (font-style fontobj)
204                       ,(intern (format "font-%s-mask" attr))))
205              t
206            nil))
207        (defun ,(intern (format "set-font-%s-p" attr)) (fontobj val)
208          ,(format "Set whether FONTOBJ will be renderd in `%s' or not."
209                   attr)
210          (cond
211           (val
212            (set-font-style fontobj (| (font-style fontobj)
213                                       ,(intern
214                                         (format "font-%s-mask" attr)))))
215           ((,(intern (format "font-%s-p" attr)) fontobj)
216            (set-font-style fontobj (- (font-style fontobj)
217                                       ,(intern
218                                         (format "font-%s-mask" attr)))))))
219        )))
220
221 (let ((mask 0))
222   (define-new-mask bold        (setq mask (1+ mask)))
223   (define-new-mask italic      (setq mask (1+ mask)))
224   (define-new-mask oblique     (setq mask (1+ mask)))
225   (define-new-mask dim         (setq mask (1+ mask)))
226   (define-new-mask underline   (setq mask (1+ mask)))
227   (define-new-mask overline    (setq mask (1+ mask)))
228   (define-new-mask linethrough (setq mask (1+ mask)))
229   (define-new-mask strikethru  (setq mask (1+ mask)))
230   (define-new-mask reverse     (setq mask (1+ mask)))
231   (define-new-mask blink       (setq mask (1+ mask)))
232   (define-new-mask smallcaps   (setq mask (1+ mask)))
233   (define-new-mask bigcaps     (setq mask (1+ mask)))
234   (define-new-mask dropcaps    (setq mask (1+ mask))))
235
236 (defvar font-caps-display-table
237   (let ((table (make-display-table))
238         (i 0))
239     ;; Standard ASCII characters
240     (while (< i 26)
241       (aset table (+ i ?a) (+ i ?A))
242       (setq i (1+ i)))
243     ;; Now ISO translations
244     (setq i 224)
245     (while (< i 247)                    ;; Agrave - Ouml
246       (aset table i (- i 32))
247       (setq i (1+ i)))
248     (setq i 248)
249     (while (< i 255)                    ;; Oslash - Thorn
250       (aset table i (- i 32))
251       (setq i (1+ i)))
252     table))
253 \f
254 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
255 ;;; Utility functions
256 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
257 (defsubst set-font-style-by-keywords (fontobj styles)
258   (make-local-variable 'font-func)
259   (declare (special font-func))
260   (if (listp styles)
261       (while styles
262         (setq font-func (car-safe (cdr-safe (assq (car styles) font-style-keywords)))
263               styles (cdr styles))
264         (and (fboundp font-func) (funcall font-func fontobj t)))
265     (setq font-func (car-safe (cdr-safe (assq styles font-style-keywords))))
266     (and (fboundp font-func) (funcall font-func fontobj t))))
267
268 (defsubst font-properties-from-style (fontobj)
269   (let ((style (font-style fontobj))
270         (todo font-style-keywords)
271         type func retval)
272     (while todo
273       (setq func (cdr (cdr (car todo)))
274             type (car (pop todo)))
275       (if (funcall func fontobj)
276           (setq retval (cons type retval))))
277     retval))
278
279 (defun font-unique (list)
280   (let ((retval)
281         (cur))
282     (while list
283       (setq cur (car list)
284             list (cdr list))
285       (if (member cur retval)
286           nil
287         (setq retval (cons cur retval))))
288     (nreverse retval)))
289
290 (defun font-higher-weight (w1 w2)
291   (let ((index1 (length (memq w1 font-possible-weights)))
292         (index2 (length (memq w2 font-possible-weights))))
293     (cond
294      ((<= index1 index2)
295       (or w1 w2))
296      ((not w2)
297       w1)
298      (t
299       w2))))
300
301 (defun font-spatial-to-canonical (spec &optional device)
302   "Convert SPEC (in inches, millimeters, points, or picas) into points"
303   ;; 1 in = 6 pa = 25.4 mm = 72 pt
304   (cond
305    ((numberp spec)
306     spec)
307    ((null spec)
308     nil)
309    (t
310     (let ((num nil)
311           (type nil)
312           ;; If for any reason we get null for any of this, default
313           ;; to 1024x768 resolution on a 17" screen
314           (pix-width (float (or (device-pixel-width device) 1024)))
315           (mm-width (float (or (device-mm-width device) 293)))
316           (retval nil))
317       (cond
318        ((string-match "^ *\\([-+*/]\\) *" spec) ; math!  whee!
319         (let ((math-func (intern (match-string 1 spec)))
320               (other (font-spatial-to-canonical
321                       (substring spec (match-end 0) nil)))
322               (default (font-spatial-to-canonical
323                         (font-default-size-for-device device))))
324           (if (fboundp math-func)
325               (setq type "px"
326                     spec (int-to-string (funcall math-func default other)))
327             (setq type "px"
328                   spec (int-to-string other)))))
329        ((string-match "[^0-9.]+$" spec)
330         (setq type (substring spec (match-beginning 0))
331               spec (substring spec 0 (match-beginning 0))))
332        (t
333         (setq type "px"
334               spec spec)))
335       (setq num (string-to-number spec))
336       (cond
337        ((member type '("pixel" "px" "pix"))
338         (setq retval (* num (/ pix-width mm-width) (/ 25.4 72.0))))
339        ((member type '("point" "pt"))
340         (setq retval num))
341        ((member type '("pica" "pa"))
342         (setq retval (* num 12.0)))
343        ((member type '("inch" "in"))
344         (setq retval (* num 72.0)))
345        ((string= type "mm")
346         (setq retval (* num (/ 72.0 25.4))))
347        ((string= type "cm")
348         (setq retval (* num 10 (/ 72.0 25.4))))
349        (t
350         (setq retval num))
351        )
352       retval))))
353
354 \f
355 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
356 ;;; The main interface routines - constructors and accessor functions
357 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
358 (defun make-font (&rest args)
359   (vector :family
360           (if (stringp (plist-get args :family))
361               (list (plist-get args :family))
362             (plist-get args :family))
363           :weight
364           (plist-get args :weight)
365           :style
366           (if (numberp (plist-get args :style))
367               (plist-get args :style)
368             0)
369           :size
370           (plist-get args :size)
371           :registry
372           (plist-get args :registry)
373           :encoding
374           (plist-get args :encoding)))
375
376 (defun font-create-name (fontobj &optional device)
377   (let* ((type (device-type device))
378          (func (car (cdr-safe (assq type font-window-system-mappings)))))
379     (and func (fboundp func) (funcall func fontobj device))))
380
381 ;;;###autoload
382 (defun font-create-object (fontname &optional device)
383   (let* ((type (device-type device))
384          (func (car (cdr (cdr-safe (assq type font-window-system-mappings))))))
385     (and func (fboundp func) (funcall func fontname device))))
386
387 (defun font-combine-fonts-internal (fontobj-1 fontobj-2)
388   (let ((retval (make-font))
389         (size-1 (and (font-size fontobj-1)
390                      (font-spatial-to-canonical (font-size fontobj-1))))
391         (size-2 (and (font-size fontobj-2)
392                      (font-spatial-to-canonical (font-size fontobj-2)))))
393     (set-font-weight retval (font-higher-weight (font-weight fontobj-1)
394                                                 (font-weight fontobj-2)))
395     (set-font-family retval (font-unique (append (font-family fontobj-1)
396                                                  (font-family fontobj-2))))
397     (set-font-style retval (| (font-style fontobj-1) (font-style fontobj-2)))
398     (set-font-registry retval (or (font-registry fontobj-1)
399                                   (font-registry fontobj-2)))
400     (set-font-encoding retval (or (font-encoding fontobj-1)
401                                   (font-encoding fontobj-2)))
402     (set-font-size retval (cond
403                            ((and size-1 size-2 (>= size-2 size-1))
404                             (font-size fontobj-2))
405                            ((and size-1 size-2)
406                             (font-size fontobj-1))
407                            (size-1
408                             (font-size fontobj-1))
409                            (size-2
410                             (font-size fontobj-2))
411                            (t nil)))
412
413     retval))
414
415 (defun font-combine-fonts (&rest args)
416   (cond
417    ((null args)
418     (error "Wrong number of arguments to font-combine-fonts"))
419    ((= (length args) 1)
420     (car args))
421    (t
422     (let ((retval (font-combine-fonts-internal (nth 0 args) (nth 1 args))))
423       (setq args (cdr (cdr args)))
424       (while args
425         (setq retval (font-combine-fonts-internal retval (car args))
426               args (cdr args)))
427       retval))))
428
429 \f
430 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
431 ;;; The window-system dependent code (TTY-style)
432 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
433 (defun tty-font-create-object (fontname &optional device)
434   (make-font :size "12pt"))
435
436 (defun tty-font-create-plist (fontobj &optional device)
437   (list
438    (cons 'underline (font-underline-p fontobj))
439    (cons 'highlight (if (or (font-bold-p fontobj)
440                             (memq (font-weight fontobj) '(:bold :demi-bold)))
441                         t))
442    (cons 'dim       (font-dim-p fontobj))
443    (cons 'blinking  (font-blink-p fontobj))
444    (cons 'reverse   (font-reverse-p fontobj))))
445
446 \f
447 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
448 ;;; The window-system dependent code (X-style)
449 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
450 (defvar font-x-font-regexp (or (and font-running-xemacs
451                                     (boundp 'x-font-regexp)
452                                     x-font-regexp)
453  (let
454      ((-                "[-?]")
455       (foundry          "[^-]*")
456       (family           "[^-]*")
457       (weight           "\\(bold\\|demibold\\|medium\\|black\\)")
458       (weight\?         "\\([^-]*\\)")
459       (slant            "\\([ior]\\)")
460       (slant\?          "\\([^-]?\\)")
461       (swidth           "\\([^-]*\\)")
462       (adstyle          "\\([^-]*\\)")
463       (pixelsize        "\\(\\*\\|[0-9]+\\)")
464       (pointsize        "\\(\\*\\|0\\|[0-9][0-9]+\\)")
465       (resx             "\\([*0]\\|[0-9][0-9]+\\)")
466       (resy             "\\([*0]\\|[0-9][0-9]+\\)")
467       (spacing          "[cmp?*]")
468       (avgwidth         "\\(\\*\\|[0-9]+\\)")
469       (registry         "[^-]*")
470       (encoding "[^-]+")
471       )
472    (concat "\\`\\*?[-?*]"
473            foundry - family - weight\? - slant\? - swidth - adstyle -
474            pixelsize - pointsize - resx - resy - spacing - avgwidth -
475            registry - encoding "\\'"
476            ))))
477
478 (defvar font-x-registry-and-encoding-regexp
479   (or (and font-running-xemacs
480            (boundp 'x-font-regexp-registry-and-encoding)
481            (symbol-value 'x-font-regexp-registry-and-encoding))
482       (let ((- "[-?]")
483             (registry "[^-]*")
484             (encoding "[^-]+"))
485         (concat - "\\(" registry "\\)" - "\\(" encoding "\\)\\'"))))
486
487 (defvar font-x-family-mappings
488   '(
489     ("serif"        . ("new century schoolbook"
490                        "utopia"
491                        "charter"
492                        "times"
493                        "lucidabright"
494                        "garamond"
495                        "palatino"
496                        "times new roman"
497                        "baskerville"
498                        "bookman"
499                        "bodoni"
500                        "computer modern"
501                        "rockwell"
502                        ))
503     ("sans-serif"   . ("lucida"
504                        "helvetica"
505                        "gills-sans"
506                        "avant-garde"
507                        "univers"
508                        "optima"))
509     ("elfin"        . ("tymes"))
510     ("monospace"    . ("courier"
511                        "fixed"
512                        "lucidatypewriter"
513                        "clean"
514                        "terminal"))
515     ("cursive"      . ("sirene"
516                        "zapf chancery"))
517     )
518   "A list of font family mappings on X devices.")
519
520 (defun x-font-create-object (fontname &optional device)
521   (let ((case-fold-search t))
522     (if (or (not (stringp fontname))
523             (not (string-match font-x-font-regexp fontname)))
524         (make-font)
525       (let ((family nil)
526             (style nil)
527             (size nil)
528             (weight  (match-string 1 fontname))
529             (slant   (match-string 2 fontname))
530             (swidth  (match-string 3 fontname))
531             (adstyle (match-string 4 fontname))
532             (pxsize  (match-string 5 fontname))
533             (ptsize  (match-string 6 fontname))
534             (retval nil)
535             (case-fold-search t)
536             )
537         (if (not (string-match x-font-regexp-foundry-and-family fontname))
538             nil
539           (setq family (list (downcase (match-string 1 fontname)))))
540         (if (string= "*" weight)  (setq weight  nil))
541         (if (string= "*" slant)   (setq slant   nil))
542         (if (string= "*" swidth)  (setq swidth  nil))
543         (if (string= "*" adstyle) (setq adstyle nil))
544         (if (string= "*" pxsize)  (setq pxsize  nil))
545         (if (string= "*" ptsize)  (setq ptsize  nil))
546         (if ptsize (setq size (/ (string-to-int ptsize) 10)))
547         (if (and (not size) pxsize) (setq size (concat pxsize "px")))
548         (if weight (setq weight (intern-soft (concat ":" (downcase weight)))))
549         (if (and adstyle (not (equal adstyle "")))
550             (setq family (append family (list (downcase adstyle)))))
551         (setq retval (make-font :family family
552                                 :weight weight
553                                 :size size))
554         (set-font-bold-p retval (eq :bold weight))
555         (cond
556          ((null slant) nil)
557          ((member slant '("i" "I"))
558           (set-font-italic-p retval t))
559          ((member slant '("o" "O"))
560           (set-font-oblique-p retval t)))
561         (when (string-match font-x-registry-and-encoding-regexp fontname)
562           (set-font-registry retval (match-string 1 fontname))
563           (set-font-encoding retval (match-string 2 fontname)))
564         retval))))
565
566 (defun x-font-families-for-device (&optional device no-resetp)
567   (ignore-errors (require 'x-font-menu))
568   (or device (setq device (selected-device)))
569   (if (boundp 'device-fonts-cache)
570       (let ((menu (or (cdr-safe (assq device device-fonts-cache)))))
571         (if (and (not menu) (not no-resetp))
572             (progn
573               (reset-device-font-menus device)
574               (x-font-families-for-device device t))
575           (let ((scaled (mapcar #'(lambda (x) (if x (aref x 0)))
576                                 (aref menu 0)))
577                 (normal (mapcar #'(lambda (x) (if x (aref x 0)))
578                                 (aref menu 1))))
579             (sort (font-unique (nconc scaled normal)) 'string-lessp))))
580     (cons "monospace" (mapcar 'car font-x-family-mappings))))
581
582 (defvar font-default-cache nil)
583
584 ;;;###autoload
585 (defun font-default-font-for-device (&optional device)
586   (or device (setq device (selected-device)))
587   (if font-running-xemacs
588       (font-truename
589        (make-font-specifier
590         (face-font-name 'default device)))
591     (let ((font (cdr-safe (assq 'font (frame-parameters device)))))
592       (if (and (fboundp 'fontsetp) (fontsetp font))
593           (aref (get-font-info (aref (cdr (get-fontset-info font)) 0)) 2)
594         font))))
595
596 ;;;###autoload
597 (defun font-default-object-for-device (&optional device)
598   (let ((font (font-default-font-for-device device)))
599     (unless (cdr-safe (assoc font font-default-cache))
600       (push (cons font (font-create-object font)) font-default-cache)
601       (cdr-safe (assoc font font-default-cache)))))
602
603 ;;;###autoload
604 (defun font-default-family-for-device (&optional device)
605   (font-family (font-default-object-for-device (or device (selected-device)))))
606
607 ;;;###autoload
608 (defun font-default-registry-for-device (&optional device)
609   (font-registry (font-default-object-for-device (or device (selected-device)))))
610
611 ;;;###autoload
612 (defun font-default-encoding-for-device (&optional device)
613   (font-encoding (font-default-object-for-device (or device (selected-device)))))
614
615 ;;;###autoload
616 (defun font-default-size-for-device (&optional device)
617   ;; face-height isn't the right thing (always 1 pixel too high?)
618   ;; (if font-running-xemacs
619   ;;    (format "%dpx" (face-height 'default device))
620   (font-size (font-default-object-for-device (or device (selected-device)))))
621
622 (defun x-font-create-name (fontobj &optional device)
623   (if (and (not (or (font-family fontobj)
624                     (font-weight fontobj)
625                     (font-size fontobj)
626                     (font-registry fontobj)
627                     (font-encoding fontobj)))
628            (= (font-style fontobj) 0))
629       (face-font 'default)
630     (or device (setq device (selected-device)))
631     (let* ((default (font-default-object-for-device device))
632            (family (or (font-family fontobj)
633                        (font-family default)
634                        (x-font-families-for-device device)))
635            (weight (or (font-weight fontobj) :medium))
636            (style (font-style fontobj))
637            (size (or (if font-running-xemacs
638                          (font-size fontobj))
639                      (font-size default)))
640            (registry (or (font-registry fontobj)
641                          (font-registry default)
642                          "*"))
643            (encoding (or (font-encoding fontobj)
644                          (font-encoding default)
645                          "*")))
646       (if (stringp family)
647           (setq family (list family)))
648       (setq weight (font-higher-weight weight
649                                        (and (font-bold-p fontobj) :bold)))
650       (if (stringp size)
651           (setq size (truncate (font-spatial-to-canonical size device))))
652       (setq weight (or (cdr-safe (assq weight x-font-weight-mappings)) "*"))
653       (let ((done nil)                  ; Did we find a good font yet?
654             (font-name nil)             ; font name we are currently checking
655             (cur-family nil)            ; current family we are checking
656             )
657         (while (and family (not done))
658           (setq cur-family (car family)
659                 family (cdr family))
660           (if (assoc cur-family font-x-family-mappings)
661               ;; If the family name is an alias as defined by
662               ;; font-x-family-mappings, then append those families
663               ;; to the front of 'family' and continue in the loop.
664               (setq family (append
665                             (cdr-safe (assoc cur-family
666                                              font-x-family-mappings))
667                             family))
668             ;; Not an alias for a list of fonts, so we just check it.
669             ;; First, convert all '-' to spaces so that we don't screw up
670             ;; the oh-so wonderful X font model.  Wheee.
671             (let ((x (length cur-family)))
672               (while (> x 0)
673                 (if (= ?- (aref cur-family (1- x)))
674                     (aset cur-family (1- x) ? ))
675                 (setq x (1- x))))
676             ;; We treat oblique and italic as equivalent.  Don't ask.
677             (let ((slants '("o" "i")))
678               (while (and slants (not done))
679                 (setq font-name (format "-*-%s-%s-%s-*-*-*-%s-*-*-*-*-%s-%s"
680                                         cur-family weight
681                                         (if (or (font-italic-p fontobj)
682                                                 (font-oblique-p fontobj))
683                                             (car slants)
684                                           "r")
685                                         (if size
686                                             (int-to-string (* 10 size)) "*")
687                                         registry
688                                         encoding
689                                         )
690                       slants (cdr slants)
691                       done (try-font-name font-name device))))))
692         (if done font-name)))))
693
694 \f
695 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
696 ;;; The window-system dependent code (NS-style)
697 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
698 (defun ns-font-families-for-device (&optional device no-resetp)
699   ;; For right now, assume we are going to have the same storage for
700   ;; device fonts for NS as we do for X.  Is this a valid assumption?
701   (or device (setq device (selected-device)))
702   (if (boundp 'device-fonts-cache)
703       (let ((menu (or (cdr-safe (assq device device-fonts-cache)))))
704         (if (and (not menu) (not no-resetp))
705             (progn
706               (reset-device-font-menus device)
707               (ns-font-families-for-device device t))
708           (let ((scaled (mapcar #'(lambda (x) (if x (aref x 0)))
709                                 (aref menu 0)))
710                 (normal (mapcar #'(lambda (x) (if x (aref x 0)))
711                                 (aref menu 1))))
712             (sort (font-unique (nconc scaled normal)) 'string-lessp))))))
713
714 (defun ns-font-create-name (fontobj &optional device)
715   (let ((family (or (font-family fontobj)
716                     (ns-font-families-for-device device)))
717         (weight (or (font-weight fontobj) :medium))
718         (style (or (font-style fontobj) (list :normal)))
719         (size (font-size fontobj))
720         (registry (or (font-registry fontobj) "*"))
721         (encoding (or (font-encoding fontobj) "*")))
722     ;; Create a font, wow!
723     (if (stringp family)
724         (setq family (list family)))
725     (if (or (symbolp style) (numberp style))
726         (setq style (list style)))
727     (setq weight (font-higher-weight weight (car-safe (memq :bold style))))
728     (if (stringp size)
729         (setq size (font-spatial-to-canonical size device)))
730     (setq weight (or (cdr-safe (assq weight ns-font-weight-mappings))
731                      "medium"))
732     (let ((done nil)                    ; Did we find a good font yet?
733           (font-name nil)               ; font name we are currently checking
734           (cur-family nil)              ; current family we are checking
735           )
736       (while (and family (not done))
737         (setq cur-family (car family)
738               family (cdr family))
739         (if (assoc cur-family font-x-family-mappings)
740             ;; If the family name is an alias as defined by
741             ;; font-x-family-mappings, then append those families
742             ;; to the front of 'family' and continue in the loop.
743             ;; #### jhar: I don't know about ns font names, so using X mappings
744             (setq family (append
745                           (cdr-safe (assoc cur-family
746                                            font-x-family-mappings))
747                           family))
748           ;; CARL: Need help here - I am not familiar with the NS font
749           ;; model
750           (setq font-name "UNKNOWN FORMULA GOES HERE"
751                 done (try-font-name font-name device))))
752       (if done font-name))))
753
754 \f
755 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
756 ;;; The window-system dependent code (mswindows-style)
757 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
758
759 ;;; mswindows fonts look like:
760 ;;;     fontname[:[weight][ style][:pointsize[:effects]]][:charset]
761 ;;; A minimal mswindows font spec looks like:
762 ;;;     Courier New
763 ;;; A maximal mswindows font spec looks like:
764 ;;;     Courier New:Bold Italic:10:underline strikeout:western
765 ;;; Missing parts of the font spec should be filled in with these values:
766 ;;;     Courier New:Regular:10::western
767 ;;  "^[a-zA-Z ]+:[a-zA-Z ]*:[0-9]+:[a-zA-Z ]*:[a-zA-Z 0-9]*$"
768 (defvar font-mswindows-font-regexp
769   (let
770       ((-               ":")
771        (fontname        "\\([a-zA-Z ]+\\)")
772        (weight          "\\([a-zA-Z]*\\)")
773        (style           "\\( [a-zA-Z]*\\)?")
774        (pointsize       "\\([0-9]+\\)")
775        (effects         "\\([a-zA-Z ]*\\)")
776        (charset         "\\([a-zA-Z 0-9]*\\)")
777        )
778     (concat "^"
779             fontname - weight style - pointsize - effects - charset "$")))
780
781 (defconst mswindows-font-weight-mappings
782   '((:extra-light . "Extralight")
783     (:light       . "Light")
784     (:demi-light  . "Demilight")
785     (:demi        . "Demi")
786     (:book        . "Book")
787     (:medium      . "Medium")
788     (:normal      . "Normal")
789     (:demi-bold   . "Demibold")
790     (:bold        . "Bold")
791     (:regular     . "Regular")
792     (:extra-bold  . "Extrabold"))
793   "An assoc list mapping keywords to actual mswindows specific strings
794 for use in the 'weight' field of an mswindows font string.")
795
796 (defvar font-mswindows-family-mappings
797   '(
798     ("serif"        . ("times new roman"
799                        "century schoolbook"
800                        "book antiqua"
801                        "bookman old style"))
802     ("sans-serif"   . ("arial"
803                        "verdana"
804                        "lucida sans unicode"))
805     ("monospace"    . ("courier new"
806                        "lucida console"
807                        "courier"
808                        "terminal"))
809     ("cursive"      . ("roman"
810                        "script"))
811     )
812   "A list of font family mappings on mswindows devices.")
813
814 (defun mswindows-font-create-object (fontname &optional device)
815   (let ((case-fold-search t)
816         (font (mswindows-font-canonicalize-name fontname)))
817     (if (or (not (stringp font))
818             (not (string-match font-mswindows-font-regexp font)))
819         (make-font)
820       (let ((family     (match-string 1 font))
821             (weight     (match-string 2 font))
822             (style      (match-string 3 font))
823             (pointsize  (match-string 4 font))
824             (effects    (match-string 5 font))
825             (charset    (match-string 6 font))
826             (retval nil)
827             (size nil)
828             (case-fold-search t)
829             )
830         (if pointsize (setq size (concat pointsize "pt")))
831         (if weight (setq weight (intern-soft (concat ":" (downcase weight)))))
832         (setq retval (make-font :family family
833                                 :weight weight
834                                 :size size
835                                 :encoding charset))
836         (set-font-bold-p retval (eq :bold weight))
837         (cond
838          ((null style) nil)
839          ((string-match "^ *[iI]talic" style)
840           (set-font-italic-p retval t)))
841         (cond
842          ((null effects) nil)
843          ((string-match "^[uU]nderline [sS]trikeout" effects)
844           (set-font-underline-p retval t)
845           (set-font-strikethru-p retval t))
846          ((string-match "[uU]nderline" effects)
847           (set-font-underline-p retval t))
848          ((string-match "[sS]trikeout" effects)
849           (set-font-strikethru-p retval t)))
850         retval))))
851
852 (defun mswindows-font-create-name (fontobj &optional device)
853   (if (and (not (or (font-family fontobj)
854                     (font-weight fontobj)
855                     (font-size fontobj)
856                     (font-registry fontobj)
857                     (font-encoding fontobj)))
858            (= (font-style fontobj) 0))
859       (face-font 'default)
860     (or device (setq device (selected-device)))
861     (let* ((default (font-default-object-for-device device))
862            (family (or (font-family fontobj)
863                        (font-family default)))
864            (weight (or (font-weight fontobj) :regular))
865            (style (font-style fontobj))
866            (size (or (if font-running-xemacs
867                          (font-size fontobj))
868                      (font-size default)))
869            (underline-p (font-underline-p fontobj))
870            (strikeout-p (font-strikethru-p fontobj))
871            (encoding (or (font-encoding fontobj)
872                          (font-encoding default))))
873       (if (stringp family)
874           (setq family (list family)))
875       (setq weight (font-higher-weight weight
876                                        (and (font-bold-p fontobj) :bold)))
877       (if (stringp size)
878           (setq size (truncate (font-spatial-to-canonical size device))))
879       (setq weight (or (cdr-safe
880                         (assq weight mswindows-font-weight-mappings)) ""))
881       (let ((done nil)                  ; Did we find a good font yet?
882             (font-name nil)             ; font name we are currently checking
883             (cur-family nil)            ; current family we are checking
884             )
885         (while (and family (not done))
886           (setq cur-family (car family)
887                 family (cdr family))
888           (if (assoc cur-family font-mswindows-family-mappings)
889               ;; If the family name is an alias as defined by
890               ;; font-mswindows-family-mappings, then append those families
891               ;; to the front of 'family' and continue in the loop.
892               (setq family (append
893                             (cdr-safe (assoc cur-family
894                                              font-mswindows-family-mappings))
895                             family))
896             ;; We treat oblique and italic as equivalent.  Don't ask.
897             ;; Courier New:Bold Italic:10:underline strikeout:western
898             (setq font-name (format "%s:%s%s:%s:%s:%s"
899                                     cur-family weight
900                                     (if (font-italic-p fontobj)
901                                         " Italic" "")
902                                     (if size
903                                         (int-to-string size) "10")
904                                     (if underline-p
905                                         (if strikeout-p
906                                             "underline strikeout"
907                                           "underline")
908                                       (if strikeout-p "strikeout" ""))
909                                     (if encoding
910                                         encoding ""))
911                   done (try-font-name font-name device))))
912         (if done font-name)))))
913
914 \f
915 ;;; Cache building code
916 ;;;###autoload
917 (defun x-font-build-cache (&optional device)
918   (let ((hash-table (make-hash-table :test 'equal :size 15))
919         (fonts (mapcar 'x-font-create-object
920                        (x-list-fonts "-*-*-*-*-*-*-*-*-*-*-*-*-*-*")))
921         (plist nil)
922         (cur nil))
923     (while fonts
924       (setq cur (car fonts)
925             fonts (cdr fonts)
926             plist (cl-gethash (car (font-family cur)) hash-table))
927       (if (not (memq (font-weight cur) (plist-get plist 'weights)))
928           (setq plist (plist-put plist 'weights (cons (font-weight cur)
929                                                       (plist-get plist 'weights)))))
930       (if (not (member (font-size cur) (plist-get plist 'sizes)))
931           (setq plist (plist-put plist 'sizes (cons (font-size cur)
932                                                     (plist-get plist 'sizes)))))
933       (if (and (font-oblique-p cur)
934                (not (memq 'oblique (plist-get plist 'styles))))
935           (setq plist (plist-put plist 'styles (cons 'oblique (plist-get plist 'styles)))))
936       (if (and (font-italic-p cur)
937                (not (memq 'italic (plist-get plist 'styles))))
938           (setq plist (plist-put plist 'styles (cons 'italic (plist-get plist 'styles)))))
939       (cl-puthash (car (font-family cur)) plist hash-table))
940     hash-table))
941
942 \f
943 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
944 ;;; Now overwrite the original copy of set-face-font with our own copy that
945 ;;; can deal with either syntax.
946 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
947 ;;; ###autoload
948 (defun font-set-face-font (&optional face font &rest args)
949   (cond
950    ((and (vectorp font) (= (length font) 12))
951     (let ((font-name (font-create-name font)))
952       (set-face-property face 'font-specification font)
953       (cond
954        ((null font-name)                ; No matching font!
955         nil)
956        ((listp font-name)               ; For TTYs
957         (let (cur)
958           (while font-name
959             (setq cur (car font-name)
960                   font-name (cdr font-name))
961             (apply 'set-face-property face (car cur) (cdr cur) args))))
962        (font-running-xemacs
963         (apply 'set-face-font face font-name args)
964         (apply 'set-face-underline-p face (font-underline-p font) args)
965         (if (and (or (font-smallcaps-p font) (font-bigcaps-p font))
966                  (fboundp 'set-face-display-table))
967             (apply 'set-face-display-table
968                    face font-caps-display-table args))
969         (apply 'set-face-property face 'strikethru (or
970                                                     (font-linethrough-p font)
971                                                     (font-strikethru-p font))
972                args))
973        (t
974         (condition-case nil
975             (apply 'set-face-font face font-name args)
976           (error
977            (let ((args (car-safe args)))
978              (and (or (font-bold-p font)
979                       (memq (font-weight font) '(:bold :demi-bold)))
980                   (make-face-bold face args t))
981              (and (font-italic-p font) (make-face-italic face args t)))))
982         (apply 'set-face-underline-p face (font-underline-p font) args)))))
983    (t
984     ;; Let the original set-face-font signal any errors
985     (set-face-property face 'font-specification nil)
986     (apply 'set-face-font face font args))))
987
988 \f
989 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
990 ;;; Now for emacsen specific stuff
991 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
992 (defun font-update-device-fonts (device)
993   ;; Update all faces that were created with the 'font' package
994   ;; to appear correctly on the new device.  This should be in the
995   ;; create-device-hook.  This is XEmacs 19.12+ specific
996   (let ((faces (face-list 2))
997         (cur nil)
998         (font nil)
999         (font-spec nil))
1000     (while faces
1001       (setq cur (car faces)
1002             faces (cdr faces)
1003             font-spec (face-property cur 'font-specification))
1004       (if font-spec
1005           (set-face-font cur font-spec device)))))
1006
1007 (defun font-update-one-face (face &optional device-list)
1008   ;; Update FACE on all devices in DEVICE-LIST
1009   ;; DEVICE_LIST defaults to a list of all active devices
1010   (setq device-list (or device-list (device-list)))
1011   (if (devicep device-list)
1012       (setq device-list (list device-list)))
1013   (let* ((cur-device nil)
1014          (font-spec (face-property face 'font-specification))
1015          (font nil))
1016     (if (not font-spec)
1017         ;; Hey!  Don't mess with fonts we didn't create in the
1018         ;; first place.
1019         nil
1020       (while device-list
1021         (setq cur-device (car device-list)
1022               device-list (cdr device-list))
1023         (if (not (device-live-p cur-device))
1024             ;; Whoah!
1025             nil
1026           (if font-spec
1027               (set-face-font face font-spec cur-device)))))))
1028
1029 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1030 ;;; Various color related things
1031 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1032 (cond
1033  ((fboundp 'display-warning)
1034   (fset 'font-warn 'display-warning))
1035  ((fboundp 'w3-warn)
1036   (fset 'font-warn 'w3-warn))
1037  ((fboundp 'url-warn)
1038   (fset 'font-warn 'url-warn))
1039  ((fboundp 'warn)
1040   (defun font-warn (class message &optional level)
1041     (warn "(%s/%s) %s" class (or level 'warning) message)))
1042  (t
1043   (defun font-warn (class message &optional level)
1044     (save-excursion
1045       (set-buffer (get-buffer-create "*W3-WARNINGS*"))
1046       (goto-char (point-max))
1047       (save-excursion
1048         (insert (format "(%s/%s) %s\n" class (or level 'warning) message)))
1049       (display-buffer (current-buffer))))))
1050
1051 (defun font-lookup-rgb-components (color)
1052   "Lookup COLOR (a color name) in rgb.txt and return a list of RGB values.
1053 The list (R G B) is returned, or an error is signaled if the lookup fails."
1054   (let ((lib-list (if (boundp 'x-library-search-path)
1055                       x-library-search-path
1056                     ;; This default is from XEmacs 19.13 - hope it covers
1057                     ;; everyone.
1058                     (list "/usr/X11R6/lib/X11/"
1059                           "/usr/X11R5/lib/X11/"
1060                           "/usr/lib/X11R6/X11/"
1061                           "/usr/lib/X11R5/X11/"
1062                           "/usr/local/X11R6/lib/X11/"
1063                           "/usr/local/X11R5/lib/X11/"
1064                           "/usr/local/lib/X11R6/X11/"
1065                           "/usr/local/lib/X11R5/X11/"
1066                           "/usr/X11/lib/X11/"
1067                           "/usr/lib/X11/"
1068                           "/usr/local/lib/X11/"
1069                           "/usr/X386/lib/X11/"
1070                           "/usr/x386/lib/X11/"
1071                           "/usr/XFree86/lib/X11/"
1072                           "/usr/unsupported/lib/X11/"
1073                           "/usr/athena/lib/X11/"
1074                           "/usr/local/x11r5/lib/X11/"
1075                           "/usr/lpp/Xamples/lib/X11/"
1076                           "/usr/openwin/lib/X11/"
1077                           "/usr/openwin/share/lib/X11/")))
1078         (file font-rgb-file)
1079         r g b)
1080     (if (not file)
1081         (while lib-list
1082           (setq file (expand-file-name "rgb.txt" (car lib-list)))
1083           (if (file-readable-p file)
1084               (setq lib-list nil
1085                     font-rgb-file file)
1086             (setq lib-list (cdr lib-list)
1087                   file nil))))
1088     (if (null file)
1089         (list 0 0 0)
1090       (save-excursion
1091         (set-buffer (find-file-noselect file))
1092         (if (not (= (aref (buffer-name) 0) ? ))
1093             (rename-buffer (generate-new-buffer-name " *rgb-tmp-buffer*")))
1094         (save-excursion
1095           (save-restriction
1096             (widen)
1097             (goto-char (point-min))
1098             (if (re-search-forward (format "\t%s$" (regexp-quote color)) nil t)
1099                 (progn
1100                   (beginning-of-line)
1101                   (setq r (* (read (current-buffer)) 256)
1102                         g (* (read (current-buffer)) 256)
1103                         b (* (read (current-buffer)) 256)))
1104               (font-warn 'color (format "No such color: %s" color))
1105               (setq r 0
1106                     g 0
1107                     b 0))
1108             (list r g b) ))))))
1109
1110 (defun font-hex-string-to-number (string)
1111   "Convert STRING to an integer by parsing it as a hexadecimal number."
1112   (let ((conv-list '((?0 . 0) (?a . 10) (?A . 10)
1113                      (?1 . 1) (?b . 11) (?B . 11)
1114                      (?2 . 2) (?c . 12) (?C . 12)
1115                      (?3 . 3) (?d . 13) (?D . 13)
1116                      (?4 . 4) (?e . 14) (?E . 14)
1117                      (?5 . 5) (?f . 15) (?F . 15)
1118                      (?6 . 6)
1119                      (?7 . 7)
1120                      (?8 . 8)
1121                      (?9 . 9)))
1122         (n 0)
1123         (i 0)
1124         (lim (length string)))
1125     (while (< i lim)
1126       (setq n (+ (* n 16) (or (cdr (assq (aref string i) conv-list)) 0))
1127             i (1+ i)))
1128     n ))
1129
1130 (defun font-parse-rgb-components (color)
1131   "Parse RGB color specification and return a list of integers (R G B).
1132 #FEFEFE and rgb:fe/fe/fe style specifications are parsed."
1133   (let ((case-fold-search t)
1134         r g b str)
1135   (cond ((string-match "^#[0-9a-f]+$" color)
1136          (cond
1137           ((= (length color) 4)
1138            (setq r (font-hex-string-to-number (substring color 1 2))
1139                  g (font-hex-string-to-number (substring color 2 3))
1140                  b (font-hex-string-to-number (substring color 3 4))
1141                  r (* r 4096)
1142                  g (* g 4096)
1143                  b (* b 4096)))
1144           ((= (length color) 7)
1145            (setq r (font-hex-string-to-number (substring color 1 3))
1146                  g (font-hex-string-to-number (substring color 3 5))
1147                  b (font-hex-string-to-number (substring color 5 7))
1148                  r (* r 256)
1149                  g (* g 256)
1150                  b (* b 256)))
1151           ((= (length color) 10)
1152            (setq r (font-hex-string-to-number (substring color 1 4))
1153                  g (font-hex-string-to-number (substring color 4 7))
1154                  b (font-hex-string-to-number (substring color 7 10))
1155                  r (* r 16)
1156                  g (* g 16)
1157                  b (* b 16)))
1158           ((= (length color) 13)
1159            (setq r (font-hex-string-to-number (substring color 1 5))
1160                  g (font-hex-string-to-number (substring color 5 9))
1161                  b (font-hex-string-to-number (substring color 9 13))))
1162           (t
1163            (font-warn 'color (format "Invalid RGB color specification: %s"
1164                                      color))
1165            (setq r 0
1166                  g 0
1167                  b 0))))
1168         ((string-match "rgb:\\([0-9a-f]+\\)/\\([0-9a-f]+\\)/\\([0-9a-f]+\\)"
1169                        color)
1170          (if (or (> (- (match-end 1) (match-beginning 1)) 4)
1171                  (> (- (match-end 2) (match-beginning 2)) 4)
1172                  (> (- (match-end 3) (match-beginning 3)) 4))
1173              (error "Invalid RGB color specification: %s" color)
1174            (setq str (match-string 1 color)
1175                  r (* (font-hex-string-to-number str)
1176                       (expt 16 (- 4 (length str))))
1177                  str (match-string 2 color)
1178                  g (* (font-hex-string-to-number str)
1179                       (expt 16 (- 4 (length str))))
1180                  str (match-string 3 color)
1181                  b (* (font-hex-string-to-number str)
1182                       (expt 16 (- 4 (length str)))))))
1183         (t
1184          (font-warn 'html (format "Invalid RGB color specification: %s"
1185                                 color))
1186          (setq r 0
1187                g 0
1188                b 0)))
1189   (list r g b) ))
1190
1191 (defsubst font-rgb-color-p (obj)
1192   (or (and (vectorp obj)
1193            (= (length obj) 4)
1194            (eq (aref obj 0) 'rgb))))
1195
1196 (defsubst font-rgb-color-red (obj) (aref obj 1))
1197 (defsubst font-rgb-color-green (obj) (aref obj 2))
1198 (defsubst font-rgb-color-blue (obj) (aref obj 3))
1199
1200 (defun font-color-rgb-components (color)
1201   "Return the RGB components of COLOR as a list of integers (R G B).
1202 16-bit values are always returned.
1203 #FEFEFE and rgb:fe/fe/fe style color specifications are parsed directly
1204 into their components.
1205 RGB values for color names are looked up in the rgb.txt file.
1206 The variable x-library-search-path is use to locate the rgb.txt file."
1207   (let ((case-fold-search t))
1208     (cond
1209      ((and (font-rgb-color-p color) (floatp (aref color 1)))
1210       (list (* 65535 (aref color 0))
1211             (* 65535 (aref color 1))
1212             (* 65535 (aref color 2))))
1213      ((font-rgb-color-p color)
1214       (list (font-rgb-color-red color)
1215             (font-rgb-color-green color)
1216             (font-rgb-color-blue color)))
1217      ((and (vectorp color) (= 3 (length color)))
1218       (list (aref color 0) (aref color 1) (aref color 2)))
1219      ((and (listp color) (= 3 (length color)) (floatp (car color)))
1220       (mapcar #'(lambda (x) (* x 65535)) color))
1221      ((and (listp color) (= 3 (length color)))
1222       color)
1223      ((or (string-match "^#" color)
1224           (string-match "^rgb:" color))
1225       (font-parse-rgb-components color))
1226      ((string-match "\\([0-9.]+\\)[ \t]\\([0-9.]+\\)[ \t]\\([0-9.]+\\)"
1227                     color)
1228       (let ((r (string-to-number (match-string 1 color)))
1229             (g (string-to-number (match-string 2 color)))
1230             (b (string-to-number (match-string 3 color))))
1231         (if (floatp r)
1232             (setq r (round (* 255 r))
1233                   g (round (* 255 g))
1234                   b (round (* 255 b))))
1235         (font-parse-rgb-components (format "#%02x%02x%02x" r g b))))
1236      (t
1237       (font-lookup-rgb-components color)))))
1238
1239 (defsubst font-tty-compute-color-delta (col1 col2)
1240   (+
1241    (* (- (aref col1 0) (aref col2 0))
1242       (- (aref col1 0) (aref col2 0)))
1243    (* (- (aref col1 1) (aref col2 1))
1244       (- (aref col1 1) (aref col2 1)))
1245    (* (- (aref col1 2) (aref col2 2))
1246       (- (aref col1 2) (aref col2 2)))))
1247
1248 (defun font-tty-find-closest-color (r g b)
1249   ;; This is basically just a lisp copy of allocate_nearest_color
1250   ;; from objects-x.c from Emacs 19
1251   ;; We really should just check tty-color-list, but unfortunately
1252   ;; that does not include any RGB information at all.
1253   ;; So for now we just hardwire in the default list and call it
1254   ;; good for now.
1255   (setq r (/ r 65535.0)
1256         g (/ g 65535.0)
1257         b (/ b 65535.0))
1258   (let* ((color_def (vector r g b))
1259          (colors [([1.0 1.0 1.0] . "white")
1260                   ([0.0 1.0 1.0] . "cyan")
1261                   ([1.0 0.0 1.0] . "magenta")
1262                   ([0.0 0.0 1.0] . "blue")
1263                   ([1.0 1.0 0.0] . "yellow")
1264                   ([0.0 1.0 0.0] . "green")
1265                   ([1.0 0.0 0.0] . "red")
1266                   ([0.0 0.0 0.0] . "black")])
1267          (no_cells (length colors))
1268          (x 1)
1269          (nearest 0)
1270          (nearest_delta 0)
1271          (trial_delta 0))
1272     (setq nearest_delta (font-tty-compute-color-delta (car (aref colors 0))
1273                                                       color_def))
1274     (while (/= no_cells x)
1275       (setq trial_delta (font-tty-compute-color-delta (car (aref colors x))
1276                                                       color_def))
1277       (if (< trial_delta nearest_delta)
1278           (setq nearest x
1279                 nearest_delta trial_delta))
1280       (setq x (1+ x)))
1281     (cdr-safe (aref colors nearest))))
1282
1283 (defun font-normalize-color (color &optional device)
1284   "Return an RGB tuple, given any form of input.  If an error occurs, black
1285 is returned."
1286   (case (device-type device)
1287    ((x pm)
1288     (apply 'format "#%02x%02x%02x" (font-color-rgb-components color)))
1289    (mswindows
1290     (let* ((rgb (font-color-rgb-components color))
1291            (color (apply 'format "#%02x%02x%02x" rgb)))
1292       (mswindows-define-rgb-color (nth 0 rgb) (nth 1 rgb) (nth 2 rgb) color)
1293       color))
1294    (tty
1295     (apply 'font-tty-find-closest-color (font-color-rgb-components color)))
1296    (ns
1297     (let ((vals (mapcar #'(lambda (x) (>> x 8))
1298                         (font-color-rgb-components color))))
1299       (apply 'format "RGB%02x%02x%02xff" vals)))
1300    (otherwise
1301     color)))
1302
1303 (defun font-set-face-background (&optional face color &rest args)
1304   (interactive)
1305   (condition-case nil
1306       (cond
1307        ((or (font-rgb-color-p color)
1308             (string-match "^#[0-9a-fA-F]+$" color))
1309         (apply 'set-face-background face
1310                (font-normalize-color color) args))
1311        (t
1312         (apply 'set-face-background face color args)))
1313     (error nil)))
1314
1315 (defun font-set-face-foreground (&optional face color &rest args)
1316   (interactive)
1317   (condition-case nil
1318       (cond
1319        ((or (font-rgb-color-p color)
1320             (string-match "^#[0-9a-fA-F]+$" color))
1321         (apply 'set-face-foreground face (font-normalize-color color) args))
1322        (t
1323         (apply 'set-face-foreground face color args)))
1324     (error nil)))
1325
1326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1327 ;;; Support for 'blinking' fonts
1328 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1329 (defun font-map-windows (func &optional arg frame)
1330   (let* ((start (selected-window))
1331          (cur start)
1332          (result nil))
1333     (push (funcall func start arg) result)
1334     (while (not (eq start (setq cur (next-window cur))))
1335       (push (funcall func cur arg) result))
1336     result))
1337
1338 (defun font-face-visible-in-window-p (window face)
1339   (let ((st (window-start window))
1340         (nd (window-end window))
1341         (found nil)
1342         (face-at nil))
1343     (setq face-at (get-text-property st 'face (window-buffer window)))
1344     (if (or (eq face face-at) (and (listp face-at) (memq face face-at)))
1345         (setq found t))
1346     (while (and (not found)
1347                 (/= nd
1348                     (setq st (next-single-property-change
1349                               st 'face
1350                               (window-buffer window) nd))))
1351       (setq face-at (get-text-property st 'face (window-buffer window)))
1352       (if (or (eq face face-at) (and (listp face-at) (memq face face-at)))
1353           (setq found t)))
1354     found))
1355
1356 (defun font-blink-callback ()
1357   ;; Optimized to never invert the face unless one of the visible windows
1358   ;; is showing it.
1359   (let ((faces (if font-running-xemacs (face-list t) (face-list)))
1360         (obj nil))
1361     (while faces
1362       (if (and (setq obj (face-property (car faces) 'font-specification))
1363                (font-blink-p obj)
1364                (memq t
1365                      (font-map-windows 'font-face-visible-in-window-p (car faces))))
1366           (invert-face (car faces)))
1367       (pop faces))))
1368
1369 (defcustom font-blink-interval 0.5
1370   "How often to blink faces"
1371   :type 'number
1372   :group 'faces)
1373
1374 (defun font-blink-initialize ()
1375   (cond
1376    ((featurep 'itimer)
1377     (if (get-itimer "font-blinker")
1378         (delete-itimer (get-itimer "font-blinker")))
1379     (start-itimer "font-blinker" 'font-blink-callback
1380                   font-blink-interval
1381                   font-blink-interval))
1382    ((fboundp 'run-at-time)
1383     (cancel-function-timers 'font-blink-callback)
1384     (run-at-time font-blink-interval
1385                  font-blink-interval
1386                  'font-blink-callback))
1387    (t nil)))
1388
1389 (provide 'font)