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