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