(Fforward_comment): Undo the previous change, since cc-mode
[emacs.git] / src / w32fns.c
blobea52c2d3808a243bb2089e3bb1f8ac70d1e47ae0
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 92, 93, 94, 95, 1996, 1997, 1998, 1999
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 /* Added by Kevin Gallo */
24 #include <config.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <limits.h>
29 #include <errno.h>
31 #include "lisp.h"
32 #include "charset.h"
33 #include "fontset.h"
34 #include "w32term.h"
35 #include "frame.h"
36 #include "window.h"
37 #include "buffer.h"
38 #include "dispextern.h"
39 #include "intervals.h"
40 #include "keyboard.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "w32heap.h"
44 #include "termhooks.h"
45 #include "coding.h"
46 #include "ccl.h"
47 #include "systime.h"
49 #include "bitmaps/gray.xbm"
51 #include <commdlg.h>
52 #include <shellapi.h>
53 #include <ctype.h>
55 extern void free_frame_menubar ();
56 extern double atof ();
57 extern struct scroll_bar *x_window_to_scroll_bar ();
58 extern int w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state);
59 extern int quit_char;
61 /* A definition of XColor for non-X frames. */
62 #ifndef HAVE_X_WINDOWS
63 typedef struct {
64 unsigned long pixel;
65 unsigned short red, green, blue;
66 char flags;
67 char pad;
68 } XColor;
69 #endif
71 extern char *lispy_function_keys[];
73 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
74 it, and including `bitmaps/gray' more than once is a problem when
75 config.h defines `static' as an empty replacement string. */
77 int gray_bitmap_width = gray_width;
78 int gray_bitmap_height = gray_height;
79 unsigned char *gray_bitmap_bits = gray_bits;
81 /* The colormap for converting color names to RGB values */
82 Lisp_Object Vw32_color_map;
84 /* Non nil if alt key presses are passed on to Windows. */
85 Lisp_Object Vw32_pass_alt_to_system;
87 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
88 to alt_modifier. */
89 Lisp_Object Vw32_alt_is_meta;
91 /* If non-zero, the windows virtual key code for an alternative quit key. */
92 Lisp_Object Vw32_quit_key;
94 /* Non nil if left window key events are passed on to Windows (this only
95 affects whether "tapping" the key opens the Start menu). */
96 Lisp_Object Vw32_pass_lwindow_to_system;
98 /* Non nil if right window key events are passed on to Windows (this
99 only affects whether "tapping" the key opens the Start menu). */
100 Lisp_Object Vw32_pass_rwindow_to_system;
102 /* Virtual key code used to generate "phantom" key presses in order
103 to stop system from acting on Windows key events. */
104 Lisp_Object Vw32_phantom_key_code;
106 /* Modifier associated with the left "Windows" key, or nil to act as a
107 normal key. */
108 Lisp_Object Vw32_lwindow_modifier;
110 /* Modifier associated with the right "Windows" key, or nil to act as a
111 normal key. */
112 Lisp_Object Vw32_rwindow_modifier;
114 /* Modifier associated with the "Apps" key, or nil to act as a normal
115 key. */
116 Lisp_Object Vw32_apps_modifier;
118 /* Value is nil if Num Lock acts as a function key. */
119 Lisp_Object Vw32_enable_num_lock;
121 /* Value is nil if Caps Lock acts as a function key. */
122 Lisp_Object Vw32_enable_caps_lock;
124 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
125 Lisp_Object Vw32_scroll_lock_modifier;
127 /* Switch to control whether we inhibit requests for synthesyzed bold
128 and italic versions of fonts. */
129 Lisp_Object Vw32_enable_synthesized_fonts;
131 /* Enable palette management. */
132 Lisp_Object Vw32_enable_palette;
134 /* Control how close left/right button down events must be to
135 be converted to a middle button down event. */
136 Lisp_Object Vw32_mouse_button_tolerance;
138 /* Minimum interval between mouse movement (and scroll bar drag)
139 events that are passed on to the event loop. */
140 Lisp_Object Vw32_mouse_move_interval;
142 /* The name we're using in resource queries. */
143 Lisp_Object Vx_resource_name;
145 /* Non nil if no window manager is in use. */
146 Lisp_Object Vx_no_window_manager;
148 /* Non-zero means we're allowed to display a busy cursor. */
149 int display_busy_cursor_p;
151 /* The background and shape of the mouse pointer, and shape when not
152 over text or in the modeline. */
153 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
154 Lisp_Object Vx_busy_pointer_shape;
156 /* The shape when over mouse-sensitive text. */
157 Lisp_Object Vx_sensitive_text_pointer_shape;
159 /* Color of chars displayed in cursor box. */
160 Lisp_Object Vx_cursor_fore_pixel;
162 /* Nonzero if using Windows. */
163 static int w32_in_use;
165 /* Search path for bitmap files. */
166 Lisp_Object Vx_bitmap_file_path;
168 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
169 Lisp_Object Vx_pixel_size_width_font_regexp;
171 /* Alist of bdf fonts and the files that define them. */
172 Lisp_Object Vw32_bdf_filename_alist;
174 Lisp_Object Vw32_system_coding_system;
176 /* A flag to control whether fonts are matched strictly or not. */
177 int w32_strict_fontnames;
179 /* A flag to control whether we should only repaint if GetUpdateRect
180 indicates there is an update region. */
181 int w32_strict_painting;
183 /* Evaluate this expression to rebuild the section of syms_of_w32fns
184 that initializes and staticpros the symbols declared below. Note
185 that Emacs 18 has a bug that keeps C-x C-e from being able to
186 evaluate this expression.
188 (progn
189 ;; Accumulate a list of the symbols we want to initialize from the
190 ;; declarations at the top of the file.
191 (goto-char (point-min))
192 (search-forward "/\*&&& symbols declared here &&&*\/\n")
193 (let (symbol-list)
194 (while (looking-at "Lisp_Object \\(Q[a-z_]+\\)")
195 (setq symbol-list
196 (cons (buffer-substring (match-beginning 1) (match-end 1))
197 symbol-list))
198 (forward-line 1))
199 (setq symbol-list (nreverse symbol-list))
200 ;; Delete the section of syms_of_... where we initialize the symbols.
201 (search-forward "\n /\*&&& init symbols here &&&*\/\n")
202 (let ((start (point)))
203 (while (looking-at "^ Q")
204 (forward-line 2))
205 (kill-region start (point)))
206 ;; Write a new symbol initialization section.
207 (while symbol-list
208 (insert (format " %s = intern (\"" (car symbol-list)))
209 (let ((start (point)))
210 (insert (substring (car symbol-list) 1))
211 (subst-char-in-region start (point) ?_ ?-))
212 (insert (format "\");\n staticpro (&%s);\n" (car symbol-list)))
213 (setq symbol-list (cdr symbol-list)))))
217 /*&&& symbols declared here &&&*/
218 Lisp_Object Qauto_raise;
219 Lisp_Object Qauto_lower;
220 Lisp_Object Qbar;
221 Lisp_Object Qborder_color;
222 Lisp_Object Qborder_width;
223 Lisp_Object Qbox;
224 Lisp_Object Qcursor_color;
225 Lisp_Object Qcursor_type;
226 Lisp_Object Qgeometry;
227 Lisp_Object Qicon_left;
228 Lisp_Object Qicon_top;
229 Lisp_Object Qicon_type;
230 Lisp_Object Qicon_name;
231 Lisp_Object Qinternal_border_width;
232 Lisp_Object Qleft;
233 Lisp_Object Qright;
234 Lisp_Object Qmouse_color;
235 Lisp_Object Qnone;
236 Lisp_Object Qparent_id;
237 Lisp_Object Qscroll_bar_width;
238 Lisp_Object Qsuppress_icon;
239 Lisp_Object Qundefined_color;
240 Lisp_Object Qvertical_scroll_bars;
241 Lisp_Object Qvisibility;
242 Lisp_Object Qwindow_id;
243 Lisp_Object Qx_frame_parameter;
244 Lisp_Object Qx_resource_name;
245 Lisp_Object Quser_position;
246 Lisp_Object Quser_size;
247 Lisp_Object Qscreen_gamma;
248 Lisp_Object Qhyper;
249 Lisp_Object Qsuper;
250 Lisp_Object Qmeta;
251 Lisp_Object Qalt;
252 Lisp_Object Qctrl;
253 Lisp_Object Qcontrol;
254 Lisp_Object Qshift;
256 extern Lisp_Object Qtop;
257 extern Lisp_Object Qdisplay;
258 extern Lisp_Object Qtool_bar_lines;
260 /* State variables for emulating a three button mouse. */
261 #define LMOUSE 1
262 #define MMOUSE 2
263 #define RMOUSE 4
265 static int button_state = 0;
266 static W32Msg saved_mouse_button_msg;
267 static unsigned mouse_button_timer; /* non-zero when timer is active */
268 static W32Msg saved_mouse_move_msg;
269 static unsigned mouse_move_timer;
271 /* W95 mousewheel handler */
272 unsigned int msh_mousewheel = 0;
274 #define MOUSE_BUTTON_ID 1
275 #define MOUSE_MOVE_ID 2
277 /* The below are defined in frame.c. */
278 extern Lisp_Object Qheight, Qminibuffer, Qname, Qonly, Qwidth;
279 extern Lisp_Object Qunsplittable, Qmenu_bar_lines, Qbuffer_predicate, Qtitle;
280 extern Lisp_Object Qtool_bar_lines;
282 extern Lisp_Object Vwindow_system_version;
284 Lisp_Object Qface_set_after_frame_default;
286 extern Lisp_Object last_mouse_scroll_bar;
287 extern int last_mouse_scroll_bar_pos;
289 /* From w32term.c. */
290 extern Lisp_Object Vw32_num_mouse_buttons;
291 extern Lisp_Object Vw32_recognize_altgr;
294 /* Error if we are not connected to MS-Windows. */
295 void
296 check_w32 ()
298 if (! w32_in_use)
299 error ("MS-Windows not in use or not initialized");
302 /* Nonzero if we can use mouse menus.
303 You should not call this unless HAVE_MENUS is defined. */
306 have_menus_p ()
308 return w32_in_use;
311 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
312 and checking validity for W32. */
314 FRAME_PTR
315 check_x_frame (frame)
316 Lisp_Object frame;
318 FRAME_PTR f;
320 if (NILP (frame))
321 frame = selected_frame;
322 CHECK_LIVE_FRAME (frame, 0);
323 f = XFRAME (frame);
324 if (! FRAME_W32_P (f))
325 error ("non-w32 frame used");
326 return f;
329 /* Let the user specify an display with a frame.
330 nil stands for the selected frame--or, if that is not a w32 frame,
331 the first display on the list. */
333 static struct w32_display_info *
334 check_x_display_info (frame)
335 Lisp_Object frame;
337 if (NILP (frame))
339 struct frame *sf = XFRAME (selected_frame);
341 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
342 return FRAME_W32_DISPLAY_INFO (sf);
343 else
344 return &one_w32_display_info;
346 else if (STRINGP (frame))
347 return x_display_info_for_name (frame);
348 else
350 FRAME_PTR f;
352 CHECK_LIVE_FRAME (frame, 0);
353 f = XFRAME (frame);
354 if (! FRAME_W32_P (f))
355 error ("non-w32 frame used");
356 return FRAME_W32_DISPLAY_INFO (f);
360 /* Return the Emacs frame-object corresponding to an w32 window.
361 It could be the frame's main window or an icon window. */
363 /* This function can be called during GC, so use GC_xxx type test macros. */
365 struct frame *
366 x_window_to_frame (dpyinfo, wdesc)
367 struct w32_display_info *dpyinfo;
368 HWND wdesc;
370 Lisp_Object tail, frame;
371 struct frame *f;
373 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
375 frame = XCAR (tail);
376 if (!GC_FRAMEP (frame))
377 continue;
378 f = XFRAME (frame);
379 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
380 continue;
381 if (FRAME_W32_WINDOW (f) == wdesc)
382 return f;
384 return 0;
389 /* Code to deal with bitmaps. Bitmaps are referenced by their bitmap
390 id, which is just an int that this section returns. Bitmaps are
391 reference counted so they can be shared among frames.
393 Bitmap indices are guaranteed to be > 0, so a negative number can
394 be used to indicate no bitmap.
396 If you use x_create_bitmap_from_data, then you must keep track of
397 the bitmaps yourself. That is, creating a bitmap from the same
398 data more than once will not be caught. */
401 /* Functions to access the contents of a bitmap, given an id. */
404 x_bitmap_height (f, id)
405 FRAME_PTR f;
406 int id;
408 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].height;
412 x_bitmap_width (f, id)
413 FRAME_PTR f;
414 int id;
416 return FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].width;
420 x_bitmap_pixmap (f, id)
421 FRAME_PTR f;
422 int id;
424 return (int) FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].pixmap;
428 /* Allocate a new bitmap record. Returns index of new record. */
430 static int
431 x_allocate_bitmap_record (f)
432 FRAME_PTR f;
434 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
435 int i;
437 if (dpyinfo->bitmaps == NULL)
439 dpyinfo->bitmaps_size = 10;
440 dpyinfo->bitmaps
441 = (struct w32_bitmap_record *) xmalloc (dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
442 dpyinfo->bitmaps_last = 1;
443 return 1;
446 if (dpyinfo->bitmaps_last < dpyinfo->bitmaps_size)
447 return ++dpyinfo->bitmaps_last;
449 for (i = 0; i < dpyinfo->bitmaps_size; ++i)
450 if (dpyinfo->bitmaps[i].refcount == 0)
451 return i + 1;
453 dpyinfo->bitmaps_size *= 2;
454 dpyinfo->bitmaps
455 = (struct w32_bitmap_record *) xrealloc (dpyinfo->bitmaps,
456 dpyinfo->bitmaps_size * sizeof (struct w32_bitmap_record));
457 return ++dpyinfo->bitmaps_last;
460 /* Add one reference to the reference count of the bitmap with id ID. */
462 void
463 x_reference_bitmap (f, id)
464 FRAME_PTR f;
465 int id;
467 ++FRAME_W32_DISPLAY_INFO (f)->bitmaps[id - 1].refcount;
470 /* Create a bitmap for frame F from a HEIGHT x WIDTH array of bits at BITS. */
473 x_create_bitmap_from_data (f, bits, width, height)
474 struct frame *f;
475 char *bits;
476 unsigned int width, height;
478 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
479 Pixmap bitmap;
480 int id;
482 bitmap = CreateBitmap (width, height,
483 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_planes,
484 FRAME_W32_DISPLAY_INFO (XFRAME (frame))->n_cbits,
485 bits);
487 if (! bitmap)
488 return -1;
490 id = x_allocate_bitmap_record (f);
491 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
492 dpyinfo->bitmaps[id - 1].file = NULL;
493 dpyinfo->bitmaps[id - 1].hinst = NULL;
494 dpyinfo->bitmaps[id - 1].refcount = 1;
495 dpyinfo->bitmaps[id - 1].depth = 1;
496 dpyinfo->bitmaps[id - 1].height = height;
497 dpyinfo->bitmaps[id - 1].width = width;
499 return id;
502 /* Create bitmap from file FILE for frame F. */
505 x_create_bitmap_from_file (f, file)
506 struct frame *f;
507 Lisp_Object file;
509 return -1;
510 #if 0 /* NTEMACS_TODO : bitmap support */
511 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
512 unsigned int width, height;
513 HBITMAP bitmap;
514 int xhot, yhot, result, id;
515 Lisp_Object found;
516 int fd;
517 char *filename;
518 HINSTANCE hinst;
520 /* Look for an existing bitmap with the same name. */
521 for (id = 0; id < dpyinfo->bitmaps_last; ++id)
523 if (dpyinfo->bitmaps[id].refcount
524 && dpyinfo->bitmaps[id].file
525 && !strcmp (dpyinfo->bitmaps[id].file, (char *) XSTRING (file)->data))
527 ++dpyinfo->bitmaps[id].refcount;
528 return id + 1;
532 /* Search bitmap-file-path for the file, if appropriate. */
533 fd = openp (Vx_bitmap_file_path, file, "", &found, 0);
534 if (fd < 0)
535 return -1;
536 /* LoadLibraryEx won't handle special files handled by Emacs handler. */
537 if (fd == 0)
538 return -1;
539 emacs_close (fd);
541 filename = (char *) XSTRING (found)->data;
543 hinst = LoadLibraryEx (filename, NULL, LOAD_LIBRARY_AS_DATAFILE);
545 if (hinst == NULL)
546 return -1;
549 result = XReadBitmapFile (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
550 filename, &width, &height, &bitmap, &xhot, &yhot);
551 if (result != BitmapSuccess)
552 return -1;
554 id = x_allocate_bitmap_record (f);
555 dpyinfo->bitmaps[id - 1].pixmap = bitmap;
556 dpyinfo->bitmaps[id - 1].refcount = 1;
557 dpyinfo->bitmaps[id - 1].file = (char *) xmalloc (XSTRING (file)->size + 1);
558 dpyinfo->bitmaps[id - 1].depth = 1;
559 dpyinfo->bitmaps[id - 1].height = height;
560 dpyinfo->bitmaps[id - 1].width = width;
561 strcpy (dpyinfo->bitmaps[id - 1].file, XSTRING (file)->data);
563 return id;
564 #endif /* NTEMACS_TODO */
567 /* Remove reference to bitmap with id number ID. */
569 void
570 x_destroy_bitmap (f, id)
571 FRAME_PTR f;
572 int id;
574 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
576 if (id > 0)
578 --dpyinfo->bitmaps[id - 1].refcount;
579 if (dpyinfo->bitmaps[id - 1].refcount == 0)
581 BLOCK_INPUT;
582 DeleteObject (dpyinfo->bitmaps[id - 1].pixmap);
583 if (dpyinfo->bitmaps[id - 1].file)
585 xfree (dpyinfo->bitmaps[id - 1].file);
586 dpyinfo->bitmaps[id - 1].file = NULL;
588 UNBLOCK_INPUT;
593 /* Free all the bitmaps for the display specified by DPYINFO. */
595 static void
596 x_destroy_all_bitmaps (dpyinfo)
597 struct w32_display_info *dpyinfo;
599 int i;
600 for (i = 0; i < dpyinfo->bitmaps_last; i++)
601 if (dpyinfo->bitmaps[i].refcount > 0)
603 DeleteObject (dpyinfo->bitmaps[i].pixmap);
604 if (dpyinfo->bitmaps[i].file)
605 xfree (dpyinfo->bitmaps[i].file);
607 dpyinfo->bitmaps_last = 0;
610 /* Connect the frame-parameter names for W32 frames
611 to the ways of passing the parameter values to the window system.
613 The name of a parameter, as a Lisp symbol,
614 has an `x-frame-parameter' property which is an integer in Lisp
615 but can be interpreted as an `enum x_frame_parm' in C. */
617 enum x_frame_parm
619 X_PARM_FOREGROUND_COLOR,
620 X_PARM_BACKGROUND_COLOR,
621 X_PARM_MOUSE_COLOR,
622 X_PARM_CURSOR_COLOR,
623 X_PARM_BORDER_COLOR,
624 X_PARM_ICON_TYPE,
625 X_PARM_FONT,
626 X_PARM_BORDER_WIDTH,
627 X_PARM_INTERNAL_BORDER_WIDTH,
628 X_PARM_NAME,
629 X_PARM_AUTORAISE,
630 X_PARM_AUTOLOWER,
631 X_PARM_VERT_SCROLL_BAR,
632 X_PARM_VISIBILITY,
633 X_PARM_MENU_BAR_LINES
637 struct x_frame_parm_table
639 char *name;
640 void (*setter) P_ ((struct frame *, Lisp_Object, Lisp_Object));
643 /* NTEMACS_TODO: Native Input Method support; see x_create_im. */
644 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
645 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
646 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
647 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
648 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
649 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
650 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
651 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
652 void x_set_font P_ ((struct frame *, Lisp_Object, Lisp_Object));
653 void x_set_border_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
654 void x_set_internal_border_width P_ ((struct frame *, Lisp_Object,
655 Lisp_Object));
656 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
657 void x_set_autoraise P_ ((struct frame *, Lisp_Object, Lisp_Object));
658 void x_set_autolower P_ ((struct frame *, Lisp_Object, Lisp_Object));
659 void x_set_vertical_scroll_bars P_ ((struct frame *, Lisp_Object,
660 Lisp_Object));
661 void x_set_visibility P_ ((struct frame *, Lisp_Object, Lisp_Object));
662 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
663 void x_set_scroll_bar_width P_ ((struct frame *, Lisp_Object, Lisp_Object));
664 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
665 void x_set_unsplittable P_ ((struct frame *, Lisp_Object, Lisp_Object));
666 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
667 static void x_set_screen_gamma P_ ((struct frame *, Lisp_Object, Lisp_Object));
669 static struct x_frame_parm_table x_frame_parms[] =
671 "auto-raise", x_set_autoraise,
672 "auto-lower", x_set_autolower,
673 "background-color", x_set_background_color,
674 "border-color", x_set_border_color,
675 "border-width", x_set_border_width,
676 "cursor-color", x_set_cursor_color,
677 "cursor-type", x_set_cursor_type,
678 "font", x_set_font,
679 "foreground-color", x_set_foreground_color,
680 "icon-name", x_set_icon_name,
681 "icon-type", x_set_icon_type,
682 "internal-border-width", x_set_internal_border_width,
683 "menu-bar-lines", x_set_menu_bar_lines,
684 "mouse-color", x_set_mouse_color,
685 "name", x_explicitly_set_name,
686 "scroll-bar-width", x_set_scroll_bar_width,
687 "title", x_set_title,
688 "unsplittable", x_set_unsplittable,
689 "vertical-scroll-bars", x_set_vertical_scroll_bars,
690 "visibility", x_set_visibility,
691 "tool-bar-lines", x_set_tool_bar_lines,
692 "screen-gamma", x_set_screen_gamma
695 /* Attach the `x-frame-parameter' properties to
696 the Lisp symbol names of parameters relevant to W32. */
698 init_x_parm_symbols ()
700 int i;
702 for (i = 0; i < sizeof (x_frame_parms) / sizeof (x_frame_parms[0]); i++)
703 Fput (intern (x_frame_parms[i].name), Qx_frame_parameter,
704 make_number (i));
707 /* Change the parameters of FRAME as specified by ALIST.
708 If a parameter is not specially recognized, do nothing;
709 otherwise call the `x_set_...' function for that parameter. */
711 void
712 x_set_frame_parameters (f, alist)
713 FRAME_PTR f;
714 Lisp_Object alist;
716 Lisp_Object tail;
718 /* If both of these parameters are present, it's more efficient to
719 set them both at once. So we wait until we've looked at the
720 entire list before we set them. */
721 int width, height;
723 /* Same here. */
724 Lisp_Object left, top;
726 /* Same with these. */
727 Lisp_Object icon_left, icon_top;
729 /* Record in these vectors all the parms specified. */
730 Lisp_Object *parms;
731 Lisp_Object *values;
732 int i, p;
733 int left_no_change = 0, top_no_change = 0;
734 int icon_left_no_change = 0, icon_top_no_change = 0;
736 struct gcpro gcpro1, gcpro2;
738 i = 0;
739 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
740 i++;
742 parms = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
743 values = (Lisp_Object *) alloca (i * sizeof (Lisp_Object));
745 /* Extract parm names and values into those vectors. */
747 i = 0;
748 for (tail = alist; CONSP (tail); tail = Fcdr (tail))
750 Lisp_Object elt;
752 elt = Fcar (tail);
753 parms[i] = Fcar (elt);
754 values[i] = Fcdr (elt);
755 i++;
758 /* TAIL and ALIST are not used again below here. */
759 alist = tail = Qnil;
761 GCPRO2 (*parms, *values);
762 gcpro1.nvars = i;
763 gcpro2.nvars = i;
765 /* There is no need to gcpro LEFT, TOP, ICON_LEFT, or ICON_TOP,
766 because their values appear in VALUES and strings are not valid. */
767 top = left = Qunbound;
768 icon_left = icon_top = Qunbound;
770 /* Provide default values for HEIGHT and WIDTH. */
771 width = FRAME_WIDTH (f);
772 height = FRAME_HEIGHT (f);
774 /* Process foreground_color and background_color before anything else.
775 They are independent of other properties, but other properties (e.g.,
776 cursor_color) are dependent upon them. */
777 for (p = 0; p < i; p++)
779 Lisp_Object prop, val;
781 prop = parms[p];
782 val = values[p];
783 if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
785 register Lisp_Object param_index, old_value;
787 param_index = Fget (prop, Qx_frame_parameter);
788 old_value = get_frame_param (f, prop);
789 store_frame_param (f, prop, val);
790 if (NATNUMP (param_index)
791 && (XFASTINT (param_index)
792 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
793 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
797 /* Now process them in reverse of specified order. */
798 for (i--; i >= 0; i--)
800 Lisp_Object prop, val;
802 prop = parms[i];
803 val = values[i];
805 if (EQ (prop, Qwidth) && NUMBERP (val))
806 width = XFASTINT (val);
807 else if (EQ (prop, Qheight) && NUMBERP (val))
808 height = XFASTINT (val);
809 else if (EQ (prop, Qtop))
810 top = val;
811 else if (EQ (prop, Qleft))
812 left = val;
813 else if (EQ (prop, Qicon_top))
814 icon_top = val;
815 else if (EQ (prop, Qicon_left))
816 icon_left = val;
817 else if (EQ (prop, Qforeground_color) || EQ (prop, Qbackground_color))
818 /* Processed above. */
819 continue;
820 else
822 register Lisp_Object param_index, old_value;
824 param_index = Fget (prop, Qx_frame_parameter);
825 old_value = get_frame_param (f, prop);
826 store_frame_param (f, prop, val);
827 if (NATNUMP (param_index)
828 && (XFASTINT (param_index)
829 < sizeof (x_frame_parms)/sizeof (x_frame_parms[0])))
830 (*x_frame_parms[XINT (param_index)].setter)(f, val, old_value);
834 /* Don't die if just one of these was set. */
835 if (EQ (left, Qunbound))
837 left_no_change = 1;
838 if (f->output_data.w32->left_pos < 0)
839 left = Fcons (Qplus, Fcons (make_number (f->output_data.w32->left_pos), Qnil));
840 else
841 XSETINT (left, f->output_data.w32->left_pos);
843 if (EQ (top, Qunbound))
845 top_no_change = 1;
846 if (f->output_data.w32->top_pos < 0)
847 top = Fcons (Qplus, Fcons (make_number (f->output_data.w32->top_pos), Qnil));
848 else
849 XSETINT (top, f->output_data.w32->top_pos);
852 /* If one of the icon positions was not set, preserve or default it. */
853 if (EQ (icon_left, Qunbound) || ! INTEGERP (icon_left))
855 icon_left_no_change = 1;
856 icon_left = Fcdr (Fassq (Qicon_left, f->param_alist));
857 if (NILP (icon_left))
858 XSETINT (icon_left, 0);
860 if (EQ (icon_top, Qunbound) || ! INTEGERP (icon_top))
862 icon_top_no_change = 1;
863 icon_top = Fcdr (Fassq (Qicon_top, f->param_alist));
864 if (NILP (icon_top))
865 XSETINT (icon_top, 0);
868 /* Don't set these parameters unless they've been explicitly
869 specified. The window might be mapped or resized while we're in
870 this function, and we don't want to override that unless the lisp
871 code has asked for it.
873 Don't set these parameters unless they actually differ from the
874 window's current parameters; the window may not actually exist
875 yet. */
877 Lisp_Object frame;
879 check_frame_size (f, &height, &width);
881 XSETFRAME (frame, f);
883 if (XINT (width) != FRAME_WIDTH (f)
884 || XINT (height) != FRAME_HEIGHT (f))
885 Fset_frame_size (frame, make_number (width), make_number (height));
887 if ((!NILP (left) || !NILP (top))
888 && ! (left_no_change && top_no_change)
889 && ! (NUMBERP (left) && XINT (left) == f->output_data.w32->left_pos
890 && NUMBERP (top) && XINT (top) == f->output_data.w32->top_pos))
892 int leftpos = 0;
893 int toppos = 0;
895 /* Record the signs. */
896 f->output_data.w32->size_hint_flags &= ~ (XNegative | YNegative);
897 if (EQ (left, Qminus))
898 f->output_data.w32->size_hint_flags |= XNegative;
899 else if (INTEGERP (left))
901 leftpos = XINT (left);
902 if (leftpos < 0)
903 f->output_data.w32->size_hint_flags |= XNegative;
905 else if (CONSP (left) && EQ (XCAR (left), Qminus)
906 && CONSP (XCDR (left))
907 && INTEGERP (XCAR (XCDR (left))))
909 leftpos = - XINT (XCAR (XCDR (left)));
910 f->output_data.w32->size_hint_flags |= XNegative;
912 else if (CONSP (left) && EQ (XCAR (left), Qplus)
913 && CONSP (XCDR (left))
914 && INTEGERP (XCAR (XCDR (left))))
916 leftpos = XINT (XCAR (XCDR (left)));
919 if (EQ (top, Qminus))
920 f->output_data.w32->size_hint_flags |= YNegative;
921 else if (INTEGERP (top))
923 toppos = XINT (top);
924 if (toppos < 0)
925 f->output_data.w32->size_hint_flags |= YNegative;
927 else if (CONSP (top) && EQ (XCAR (top), Qminus)
928 && CONSP (XCDR (top))
929 && INTEGERP (XCAR (XCDR (top))))
931 toppos = - XINT (XCAR (XCDR (top)));
932 f->output_data.w32->size_hint_flags |= YNegative;
934 else if (CONSP (top) && EQ (XCAR (top), Qplus)
935 && CONSP (XCDR (top))
936 && INTEGERP (XCAR (XCDR (top))))
938 toppos = XINT (XCAR (XCDR (top)));
942 /* Store the numeric value of the position. */
943 f->output_data.w32->top_pos = toppos;
944 f->output_data.w32->left_pos = leftpos;
946 f->output_data.w32->win_gravity = NorthWestGravity;
948 /* Actually set that position, and convert to absolute. */
949 x_set_offset (f, leftpos, toppos, -1);
952 if ((!NILP (icon_left) || !NILP (icon_top))
953 && ! (icon_left_no_change && icon_top_no_change))
954 x_wm_set_icon_position (f, XINT (icon_left), XINT (icon_top));
957 UNGCPRO;
960 /* Store the screen positions of frame F into XPTR and YPTR.
961 These are the positions of the containing window manager window,
962 not Emacs's own window. */
964 void
965 x_real_positions (f, xptr, yptr)
966 FRAME_PTR f;
967 int *xptr, *yptr;
969 POINT pt;
972 RECT rect;
974 GetClientRect(FRAME_W32_WINDOW(f), &rect);
975 AdjustWindowRect(&rect, f->output_data.w32->dwStyle, FRAME_EXTERNAL_MENU_BAR(f));
977 pt.x = rect.left;
978 pt.y = rect.top;
981 ClientToScreen (FRAME_W32_WINDOW(f), &pt);
983 *xptr = pt.x;
984 *yptr = pt.y;
987 /* Insert a description of internally-recorded parameters of frame X
988 into the parameter alist *ALISTPTR that is to be given to the user.
989 Only parameters that are specific to W32
990 and whose values are not correctly recorded in the frame's
991 param_alist need to be considered here. */
993 x_report_frame_params (f, alistptr)
994 struct frame *f;
995 Lisp_Object *alistptr;
997 char buf[16];
998 Lisp_Object tem;
1000 /* Represent negative positions (off the top or left screen edge)
1001 in a way that Fmodify_frame_parameters will understand correctly. */
1002 XSETINT (tem, f->output_data.w32->left_pos);
1003 if (f->output_data.w32->left_pos >= 0)
1004 store_in_alist (alistptr, Qleft, tem);
1005 else
1006 store_in_alist (alistptr, Qleft, Fcons (Qplus, Fcons (tem, Qnil)));
1008 XSETINT (tem, f->output_data.w32->top_pos);
1009 if (f->output_data.w32->top_pos >= 0)
1010 store_in_alist (alistptr, Qtop, tem);
1011 else
1012 store_in_alist (alistptr, Qtop, Fcons (Qplus, Fcons (tem, Qnil)));
1014 store_in_alist (alistptr, Qborder_width,
1015 make_number (f->output_data.w32->border_width));
1016 store_in_alist (alistptr, Qinternal_border_width,
1017 make_number (f->output_data.w32->internal_border_width));
1018 sprintf (buf, "%ld", (long) FRAME_W32_WINDOW (f));
1019 store_in_alist (alistptr, Qwindow_id,
1020 build_string (buf));
1021 store_in_alist (alistptr, Qicon_name, f->icon_name);
1022 FRAME_SAMPLE_VISIBILITY (f);
1023 store_in_alist (alistptr, Qvisibility,
1024 (FRAME_VISIBLE_P (f) ? Qt
1025 : FRAME_ICONIFIED_P (f) ? Qicon : Qnil));
1026 store_in_alist (alistptr, Qdisplay,
1027 XCAR (FRAME_W32_DISPLAY_INFO (f)->name_list_element));
1031 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color, Sw32_define_rgb_color, 4, 4, 0,
1032 "Convert RGB numbers to a windows color reference and associate with NAME (a string).\n\
1033 This adds or updates a named color to w32-color-map, making it available for use.\n\
1034 The original entry's RGB ref is returned, or nil if the entry is new.")
1035 (red, green, blue, name)
1036 Lisp_Object red, green, blue, name;
1038 Lisp_Object rgb;
1039 Lisp_Object oldrgb = Qnil;
1040 Lisp_Object entry;
1042 CHECK_NUMBER (red, 0);
1043 CHECK_NUMBER (green, 0);
1044 CHECK_NUMBER (blue, 0);
1045 CHECK_STRING (name, 0);
1047 XSET (rgb, Lisp_Int, RGB(XUINT (red), XUINT (green), XUINT (blue)));
1049 BLOCK_INPUT;
1051 /* replace existing entry in w32-color-map or add new entry. */
1052 entry = Fassoc (name, Vw32_color_map);
1053 if (NILP (entry))
1055 entry = Fcons (name, rgb);
1056 Vw32_color_map = Fcons (entry, Vw32_color_map);
1058 else
1060 oldrgb = Fcdr (entry);
1061 Fsetcdr (entry, rgb);
1064 UNBLOCK_INPUT;
1066 return (oldrgb);
1069 DEFUN ("w32-load-color-file", Fw32_load_color_file, Sw32_load_color_file, 1, 1, 0,
1070 "Create an alist of color entries from an external file (ie. rgb.txt).\n\
1071 Assign this value to w32-color-map to replace the existing color map.\n\
1073 The file should define one named RGB color per line like so:\
1074 R G B name\n\
1075 where R,G,B are numbers between 0 and 255 and name is an arbitrary string.")
1076 (filename)
1077 Lisp_Object filename;
1079 FILE *fp;
1080 Lisp_Object cmap = Qnil;
1081 Lisp_Object abspath;
1083 CHECK_STRING (filename, 0);
1084 abspath = Fexpand_file_name (filename, Qnil);
1086 fp = fopen (XSTRING (filename)->data, "rt");
1087 if (fp)
1089 char buf[512];
1090 int red, green, blue;
1091 int num;
1093 BLOCK_INPUT;
1095 while (fgets (buf, sizeof (buf), fp) != NULL) {
1096 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
1098 char *name = buf + num;
1099 num = strlen (name) - 1;
1100 if (name[num] == '\n')
1101 name[num] = 0;
1102 cmap = Fcons (Fcons (build_string (name),
1103 make_number (RGB (red, green, blue))),
1104 cmap);
1107 fclose (fp);
1109 UNBLOCK_INPUT;
1112 return cmap;
1115 /* The default colors for the w32 color map */
1116 typedef struct colormap_t
1118 char *name;
1119 COLORREF colorref;
1120 } colormap_t;
1122 colormap_t w32_color_map[] =
1124 {"snow" , PALETTERGB (255,250,250)},
1125 {"ghost white" , PALETTERGB (248,248,255)},
1126 {"GhostWhite" , PALETTERGB (248,248,255)},
1127 {"white smoke" , PALETTERGB (245,245,245)},
1128 {"WhiteSmoke" , PALETTERGB (245,245,245)},
1129 {"gainsboro" , PALETTERGB (220,220,220)},
1130 {"floral white" , PALETTERGB (255,250,240)},
1131 {"FloralWhite" , PALETTERGB (255,250,240)},
1132 {"old lace" , PALETTERGB (253,245,230)},
1133 {"OldLace" , PALETTERGB (253,245,230)},
1134 {"linen" , PALETTERGB (250,240,230)},
1135 {"antique white" , PALETTERGB (250,235,215)},
1136 {"AntiqueWhite" , PALETTERGB (250,235,215)},
1137 {"papaya whip" , PALETTERGB (255,239,213)},
1138 {"PapayaWhip" , PALETTERGB (255,239,213)},
1139 {"blanched almond" , PALETTERGB (255,235,205)},
1140 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
1141 {"bisque" , PALETTERGB (255,228,196)},
1142 {"peach puff" , PALETTERGB (255,218,185)},
1143 {"PeachPuff" , PALETTERGB (255,218,185)},
1144 {"navajo white" , PALETTERGB (255,222,173)},
1145 {"NavajoWhite" , PALETTERGB (255,222,173)},
1146 {"moccasin" , PALETTERGB (255,228,181)},
1147 {"cornsilk" , PALETTERGB (255,248,220)},
1148 {"ivory" , PALETTERGB (255,255,240)},
1149 {"lemon chiffon" , PALETTERGB (255,250,205)},
1150 {"LemonChiffon" , PALETTERGB (255,250,205)},
1151 {"seashell" , PALETTERGB (255,245,238)},
1152 {"honeydew" , PALETTERGB (240,255,240)},
1153 {"mint cream" , PALETTERGB (245,255,250)},
1154 {"MintCream" , PALETTERGB (245,255,250)},
1155 {"azure" , PALETTERGB (240,255,255)},
1156 {"alice blue" , PALETTERGB (240,248,255)},
1157 {"AliceBlue" , PALETTERGB (240,248,255)},
1158 {"lavender" , PALETTERGB (230,230,250)},
1159 {"lavender blush" , PALETTERGB (255,240,245)},
1160 {"LavenderBlush" , PALETTERGB (255,240,245)},
1161 {"misty rose" , PALETTERGB (255,228,225)},
1162 {"MistyRose" , PALETTERGB (255,228,225)},
1163 {"white" , PALETTERGB (255,255,255)},
1164 {"black" , PALETTERGB ( 0, 0, 0)},
1165 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
1166 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
1167 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
1168 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
1169 {"dim gray" , PALETTERGB (105,105,105)},
1170 {"DimGray" , PALETTERGB (105,105,105)},
1171 {"dim grey" , PALETTERGB (105,105,105)},
1172 {"DimGrey" , PALETTERGB (105,105,105)},
1173 {"slate gray" , PALETTERGB (112,128,144)},
1174 {"SlateGray" , PALETTERGB (112,128,144)},
1175 {"slate grey" , PALETTERGB (112,128,144)},
1176 {"SlateGrey" , PALETTERGB (112,128,144)},
1177 {"light slate gray" , PALETTERGB (119,136,153)},
1178 {"LightSlateGray" , PALETTERGB (119,136,153)},
1179 {"light slate grey" , PALETTERGB (119,136,153)},
1180 {"LightSlateGrey" , PALETTERGB (119,136,153)},
1181 {"gray" , PALETTERGB (190,190,190)},
1182 {"grey" , PALETTERGB (190,190,190)},
1183 {"light grey" , PALETTERGB (211,211,211)},
1184 {"LightGrey" , PALETTERGB (211,211,211)},
1185 {"light gray" , PALETTERGB (211,211,211)},
1186 {"LightGray" , PALETTERGB (211,211,211)},
1187 {"midnight blue" , PALETTERGB ( 25, 25,112)},
1188 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
1189 {"navy" , PALETTERGB ( 0, 0,128)},
1190 {"navy blue" , PALETTERGB ( 0, 0,128)},
1191 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
1192 {"cornflower blue" , PALETTERGB (100,149,237)},
1193 {"CornflowerBlue" , PALETTERGB (100,149,237)},
1194 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
1195 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
1196 {"slate blue" , PALETTERGB (106, 90,205)},
1197 {"SlateBlue" , PALETTERGB (106, 90,205)},
1198 {"medium slate blue" , PALETTERGB (123,104,238)},
1199 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
1200 {"light slate blue" , PALETTERGB (132,112,255)},
1201 {"LightSlateBlue" , PALETTERGB (132,112,255)},
1202 {"medium blue" , PALETTERGB ( 0, 0,205)},
1203 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
1204 {"royal blue" , PALETTERGB ( 65,105,225)},
1205 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
1206 {"blue" , PALETTERGB ( 0, 0,255)},
1207 {"dodger blue" , PALETTERGB ( 30,144,255)},
1208 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
1209 {"deep sky blue" , PALETTERGB ( 0,191,255)},
1210 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
1211 {"sky blue" , PALETTERGB (135,206,235)},
1212 {"SkyBlue" , PALETTERGB (135,206,235)},
1213 {"light sky blue" , PALETTERGB (135,206,250)},
1214 {"LightSkyBlue" , PALETTERGB (135,206,250)},
1215 {"steel blue" , PALETTERGB ( 70,130,180)},
1216 {"SteelBlue" , PALETTERGB ( 70,130,180)},
1217 {"light steel blue" , PALETTERGB (176,196,222)},
1218 {"LightSteelBlue" , PALETTERGB (176,196,222)},
1219 {"light blue" , PALETTERGB (173,216,230)},
1220 {"LightBlue" , PALETTERGB (173,216,230)},
1221 {"powder blue" , PALETTERGB (176,224,230)},
1222 {"PowderBlue" , PALETTERGB (176,224,230)},
1223 {"pale turquoise" , PALETTERGB (175,238,238)},
1224 {"PaleTurquoise" , PALETTERGB (175,238,238)},
1225 {"dark turquoise" , PALETTERGB ( 0,206,209)},
1226 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
1227 {"medium turquoise" , PALETTERGB ( 72,209,204)},
1228 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
1229 {"turquoise" , PALETTERGB ( 64,224,208)},
1230 {"cyan" , PALETTERGB ( 0,255,255)},
1231 {"light cyan" , PALETTERGB (224,255,255)},
1232 {"LightCyan" , PALETTERGB (224,255,255)},
1233 {"cadet blue" , PALETTERGB ( 95,158,160)},
1234 {"CadetBlue" , PALETTERGB ( 95,158,160)},
1235 {"medium aquamarine" , PALETTERGB (102,205,170)},
1236 {"MediumAquamarine" , PALETTERGB (102,205,170)},
1237 {"aquamarine" , PALETTERGB (127,255,212)},
1238 {"dark green" , PALETTERGB ( 0,100, 0)},
1239 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
1240 {"dark olive green" , PALETTERGB ( 85,107, 47)},
1241 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
1242 {"dark sea green" , PALETTERGB (143,188,143)},
1243 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
1244 {"sea green" , PALETTERGB ( 46,139, 87)},
1245 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
1246 {"medium sea green" , PALETTERGB ( 60,179,113)},
1247 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
1248 {"light sea green" , PALETTERGB ( 32,178,170)},
1249 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
1250 {"pale green" , PALETTERGB (152,251,152)},
1251 {"PaleGreen" , PALETTERGB (152,251,152)},
1252 {"spring green" , PALETTERGB ( 0,255,127)},
1253 {"SpringGreen" , PALETTERGB ( 0,255,127)},
1254 {"lawn green" , PALETTERGB (124,252, 0)},
1255 {"LawnGreen" , PALETTERGB (124,252, 0)},
1256 {"green" , PALETTERGB ( 0,255, 0)},
1257 {"chartreuse" , PALETTERGB (127,255, 0)},
1258 {"medium spring green" , PALETTERGB ( 0,250,154)},
1259 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
1260 {"green yellow" , PALETTERGB (173,255, 47)},
1261 {"GreenYellow" , PALETTERGB (173,255, 47)},
1262 {"lime green" , PALETTERGB ( 50,205, 50)},
1263 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
1264 {"yellow green" , PALETTERGB (154,205, 50)},
1265 {"YellowGreen" , PALETTERGB (154,205, 50)},
1266 {"forest green" , PALETTERGB ( 34,139, 34)},
1267 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
1268 {"olive drab" , PALETTERGB (107,142, 35)},
1269 {"OliveDrab" , PALETTERGB (107,142, 35)},
1270 {"dark khaki" , PALETTERGB (189,183,107)},
1271 {"DarkKhaki" , PALETTERGB (189,183,107)},
1272 {"khaki" , PALETTERGB (240,230,140)},
1273 {"pale goldenrod" , PALETTERGB (238,232,170)},
1274 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
1275 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
1276 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
1277 {"light yellow" , PALETTERGB (255,255,224)},
1278 {"LightYellow" , PALETTERGB (255,255,224)},
1279 {"yellow" , PALETTERGB (255,255, 0)},
1280 {"gold" , PALETTERGB (255,215, 0)},
1281 {"light goldenrod" , PALETTERGB (238,221,130)},
1282 {"LightGoldenrod" , PALETTERGB (238,221,130)},
1283 {"goldenrod" , PALETTERGB (218,165, 32)},
1284 {"dark goldenrod" , PALETTERGB (184,134, 11)},
1285 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
1286 {"rosy brown" , PALETTERGB (188,143,143)},
1287 {"RosyBrown" , PALETTERGB (188,143,143)},
1288 {"indian red" , PALETTERGB (205, 92, 92)},
1289 {"IndianRed" , PALETTERGB (205, 92, 92)},
1290 {"saddle brown" , PALETTERGB (139, 69, 19)},
1291 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
1292 {"sienna" , PALETTERGB (160, 82, 45)},
1293 {"peru" , PALETTERGB (205,133, 63)},
1294 {"burlywood" , PALETTERGB (222,184,135)},
1295 {"beige" , PALETTERGB (245,245,220)},
1296 {"wheat" , PALETTERGB (245,222,179)},
1297 {"sandy brown" , PALETTERGB (244,164, 96)},
1298 {"SandyBrown" , PALETTERGB (244,164, 96)},
1299 {"tan" , PALETTERGB (210,180,140)},
1300 {"chocolate" , PALETTERGB (210,105, 30)},
1301 {"firebrick" , PALETTERGB (178,34, 34)},
1302 {"brown" , PALETTERGB (165,42, 42)},
1303 {"dark salmon" , PALETTERGB (233,150,122)},
1304 {"DarkSalmon" , PALETTERGB (233,150,122)},
1305 {"salmon" , PALETTERGB (250,128,114)},
1306 {"light salmon" , PALETTERGB (255,160,122)},
1307 {"LightSalmon" , PALETTERGB (255,160,122)},
1308 {"orange" , PALETTERGB (255,165, 0)},
1309 {"dark orange" , PALETTERGB (255,140, 0)},
1310 {"DarkOrange" , PALETTERGB (255,140, 0)},
1311 {"coral" , PALETTERGB (255,127, 80)},
1312 {"light coral" , PALETTERGB (240,128,128)},
1313 {"LightCoral" , PALETTERGB (240,128,128)},
1314 {"tomato" , PALETTERGB (255, 99, 71)},
1315 {"orange red" , PALETTERGB (255, 69, 0)},
1316 {"OrangeRed" , PALETTERGB (255, 69, 0)},
1317 {"red" , PALETTERGB (255, 0, 0)},
1318 {"hot pink" , PALETTERGB (255,105,180)},
1319 {"HotPink" , PALETTERGB (255,105,180)},
1320 {"deep pink" , PALETTERGB (255, 20,147)},
1321 {"DeepPink" , PALETTERGB (255, 20,147)},
1322 {"pink" , PALETTERGB (255,192,203)},
1323 {"light pink" , PALETTERGB (255,182,193)},
1324 {"LightPink" , PALETTERGB (255,182,193)},
1325 {"pale violet red" , PALETTERGB (219,112,147)},
1326 {"PaleVioletRed" , PALETTERGB (219,112,147)},
1327 {"maroon" , PALETTERGB (176, 48, 96)},
1328 {"medium violet red" , PALETTERGB (199, 21,133)},
1329 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
1330 {"violet red" , PALETTERGB (208, 32,144)},
1331 {"VioletRed" , PALETTERGB (208, 32,144)},
1332 {"magenta" , PALETTERGB (255, 0,255)},
1333 {"violet" , PALETTERGB (238,130,238)},
1334 {"plum" , PALETTERGB (221,160,221)},
1335 {"orchid" , PALETTERGB (218,112,214)},
1336 {"medium orchid" , PALETTERGB (186, 85,211)},
1337 {"MediumOrchid" , PALETTERGB (186, 85,211)},
1338 {"dark orchid" , PALETTERGB (153, 50,204)},
1339 {"DarkOrchid" , PALETTERGB (153, 50,204)},
1340 {"dark violet" , PALETTERGB (148, 0,211)},
1341 {"DarkViolet" , PALETTERGB (148, 0,211)},
1342 {"blue violet" , PALETTERGB (138, 43,226)},
1343 {"BlueViolet" , PALETTERGB (138, 43,226)},
1344 {"purple" , PALETTERGB (160, 32,240)},
1345 {"medium purple" , PALETTERGB (147,112,219)},
1346 {"MediumPurple" , PALETTERGB (147,112,219)},
1347 {"thistle" , PALETTERGB (216,191,216)},
1348 {"gray0" , PALETTERGB ( 0, 0, 0)},
1349 {"grey0" , PALETTERGB ( 0, 0, 0)},
1350 {"dark grey" , PALETTERGB (169,169,169)},
1351 {"DarkGrey" , PALETTERGB (169,169,169)},
1352 {"dark gray" , PALETTERGB (169,169,169)},
1353 {"DarkGray" , PALETTERGB (169,169,169)},
1354 {"dark blue" , PALETTERGB ( 0, 0,139)},
1355 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
1356 {"dark cyan" , PALETTERGB ( 0,139,139)},
1357 {"DarkCyan" , PALETTERGB ( 0,139,139)},
1358 {"dark magenta" , PALETTERGB (139, 0,139)},
1359 {"DarkMagenta" , PALETTERGB (139, 0,139)},
1360 {"dark red" , PALETTERGB (139, 0, 0)},
1361 {"DarkRed" , PALETTERGB (139, 0, 0)},
1362 {"light green" , PALETTERGB (144,238,144)},
1363 {"LightGreen" , PALETTERGB (144,238,144)},
1366 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
1367 0, 0, 0, "Return the default color map.")
1370 int i;
1371 colormap_t *pc = w32_color_map;
1372 Lisp_Object cmap;
1374 BLOCK_INPUT;
1376 cmap = Qnil;
1378 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
1379 pc++, i++)
1380 cmap = Fcons (Fcons (build_string (pc->name),
1381 make_number (pc->colorref)),
1382 cmap);
1384 UNBLOCK_INPUT;
1386 return (cmap);
1389 Lisp_Object
1390 w32_to_x_color (rgb)
1391 Lisp_Object rgb;
1393 Lisp_Object color;
1395 CHECK_NUMBER (rgb, 0);
1397 BLOCK_INPUT;
1399 color = Frassq (rgb, Vw32_color_map);
1401 UNBLOCK_INPUT;
1403 if (!NILP (color))
1404 return (Fcar (color));
1405 else
1406 return Qnil;
1409 COLORREF
1410 w32_color_map_lookup (colorname)
1411 char *colorname;
1413 Lisp_Object tail, ret = Qnil;
1415 BLOCK_INPUT;
1417 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
1419 register Lisp_Object elt, tem;
1421 elt = Fcar (tail);
1422 if (!CONSP (elt)) continue;
1424 tem = Fcar (elt);
1426 if (lstrcmpi (XSTRING (tem)->data, colorname) == 0)
1428 ret = XUINT (Fcdr (elt));
1429 break;
1432 QUIT;
1436 UNBLOCK_INPUT;
1438 return ret;
1441 COLORREF
1442 x_to_w32_color (colorname)
1443 char * colorname;
1445 register Lisp_Object tail, ret = Qnil;
1447 BLOCK_INPUT;
1449 if (colorname[0] == '#')
1451 /* Could be an old-style RGB Device specification. */
1452 char *color;
1453 int size;
1454 color = colorname + 1;
1456 size = strlen(color);
1457 if (size == 3 || size == 6 || size == 9 || size == 12)
1459 UINT colorval;
1460 int i, pos;
1461 pos = 0;
1462 size /= 3;
1463 colorval = 0;
1465 for (i = 0; i < 3; i++)
1467 char *end;
1468 char t;
1469 unsigned long value;
1471 /* The check for 'x' in the following conditional takes into
1472 account the fact that strtol allows a "0x" in front of
1473 our numbers, and we don't. */
1474 if (!isxdigit(color[0]) || color[1] == 'x')
1475 break;
1476 t = color[size];
1477 color[size] = '\0';
1478 value = strtoul(color, &end, 16);
1479 color[size] = t;
1480 if (errno == ERANGE || end - color != size)
1481 break;
1482 switch (size)
1484 case 1:
1485 value = value * 0x10;
1486 break;
1487 case 2:
1488 break;
1489 case 3:
1490 value /= 0x10;
1491 break;
1492 case 4:
1493 value /= 0x100;
1494 break;
1496 colorval |= (value << pos);
1497 pos += 0x8;
1498 if (i == 2)
1500 UNBLOCK_INPUT;
1501 return (colorval);
1503 color = end;
1507 else if (strnicmp(colorname, "rgb:", 4) == 0)
1509 char *color;
1510 UINT colorval;
1511 int i, pos;
1512 pos = 0;
1514 colorval = 0;
1515 color = colorname + 4;
1516 for (i = 0; i < 3; i++)
1518 char *end;
1519 unsigned long value;
1521 /* The check for 'x' in the following conditional takes into
1522 account the fact that strtol allows a "0x" in front of
1523 our numbers, and we don't. */
1524 if (!isxdigit(color[0]) || color[1] == 'x')
1525 break;
1526 value = strtoul(color, &end, 16);
1527 if (errno == ERANGE)
1528 break;
1529 switch (end - color)
1531 case 1:
1532 value = value * 0x10 + value;
1533 break;
1534 case 2:
1535 break;
1536 case 3:
1537 value /= 0x10;
1538 break;
1539 case 4:
1540 value /= 0x100;
1541 break;
1542 default:
1543 value = ULONG_MAX;
1545 if (value == ULONG_MAX)
1546 break;
1547 colorval |= (value << pos);
1548 pos += 0x8;
1549 if (i == 2)
1551 if (*end != '\0')
1552 break;
1553 UNBLOCK_INPUT;
1554 return (colorval);
1556 if (*end != '/')
1557 break;
1558 color = end + 1;
1561 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1563 /* This is an RGB Intensity specification. */
1564 char *color;
1565 UINT colorval;
1566 int i, pos;
1567 pos = 0;
1569 colorval = 0;
1570 color = colorname + 5;
1571 for (i = 0; i < 3; i++)
1573 char *end;
1574 double value;
1575 UINT val;
1577 value = strtod(color, &end);
1578 if (errno == ERANGE)
1579 break;
1580 if (value < 0.0 || value > 1.0)
1581 break;
1582 val = (UINT)(0x100 * value);
1583 /* We used 0x100 instead of 0xFF to give an continuous
1584 range between 0.0 and 1.0 inclusive. The next statement
1585 fixes the 1.0 case. */
1586 if (val == 0x100)
1587 val = 0xFF;
1588 colorval |= (val << pos);
1589 pos += 0x8;
1590 if (i == 2)
1592 if (*end != '\0')
1593 break;
1594 UNBLOCK_INPUT;
1595 return (colorval);
1597 if (*end != '/')
1598 break;
1599 color = end + 1;
1602 /* I am not going to attempt to handle any of the CIE color schemes
1603 or TekHVC, since I don't know the algorithms for conversion to
1604 RGB. */
1606 /* If we fail to lookup the color name in w32_color_map, then check the
1607 colorname to see if it can be crudely approximated: If the X color
1608 ends in a number (e.g., "darkseagreen2"), strip the number and
1609 return the result of looking up the base color name. */
1610 ret = w32_color_map_lookup (colorname);
1611 if (NILP (ret))
1613 int len = strlen (colorname);
1615 if (isdigit (colorname[len - 1]))
1617 char *ptr, *approx = alloca (len);
1619 strcpy (approx, colorname);
1620 ptr = &approx[len - 1];
1621 while (ptr > approx && isdigit (*ptr))
1622 *ptr-- = '\0';
1624 ret = w32_color_map_lookup (approx);
1628 UNBLOCK_INPUT;
1629 return ret;
1633 void
1634 w32_regenerate_palette (FRAME_PTR f)
1636 struct w32_palette_entry * list;
1637 LOGPALETTE * log_palette;
1638 HPALETTE new_palette;
1639 int i;
1641 /* don't bother trying to create palette if not supported */
1642 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1643 return;
1645 log_palette = (LOGPALETTE *)
1646 alloca (sizeof (LOGPALETTE) +
1647 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1648 log_palette->palVersion = 0x300;
1649 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1651 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1652 for (i = 0;
1653 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1654 i++, list = list->next)
1655 log_palette->palPalEntry[i] = list->entry;
1657 new_palette = CreatePalette (log_palette);
1659 enter_crit ();
1661 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1662 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1663 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1665 /* Realize display palette and garbage all frames. */
1666 release_frame_dc (f, get_frame_dc (f));
1668 leave_crit ();
1671 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1672 #define SET_W32_COLOR(pe, color) \
1673 do \
1675 pe.peRed = GetRValue (color); \
1676 pe.peGreen = GetGValue (color); \
1677 pe.peBlue = GetBValue (color); \
1678 pe.peFlags = 0; \
1679 } while (0)
1681 #if 0
1682 /* Keep these around in case we ever want to track color usage. */
1683 void
1684 w32_map_color (FRAME_PTR f, COLORREF color)
1686 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1688 if (NILP (Vw32_enable_palette))
1689 return;
1691 /* check if color is already mapped */
1692 while (list)
1694 if (W32_COLOR (list->entry) == color)
1696 ++list->refcount;
1697 return;
1699 list = list->next;
1702 /* not already mapped, so add to list and recreate Windows palette */
1703 list = (struct w32_palette_entry *)
1704 xmalloc (sizeof (struct w32_palette_entry));
1705 SET_W32_COLOR (list->entry, color);
1706 list->refcount = 1;
1707 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1708 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1709 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1711 /* set flag that palette must be regenerated */
1712 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1715 void
1716 w32_unmap_color (FRAME_PTR f, COLORREF color)
1718 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1719 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1721 if (NILP (Vw32_enable_palette))
1722 return;
1724 /* check if color is already mapped */
1725 while (list)
1727 if (W32_COLOR (list->entry) == color)
1729 if (--list->refcount == 0)
1731 *prev = list->next;
1732 xfree (list);
1733 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1734 break;
1736 else
1737 return;
1739 prev = &list->next;
1740 list = list->next;
1743 /* set flag that palette must be regenerated */
1744 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1746 #endif
1749 /* Gamma-correct COLOR on frame F. */
1751 void
1752 gamma_correct (f, color)
1753 struct frame *f;
1754 COLORREF *color;
1756 if (f->gamma)
1758 *color = PALETTERGB (
1759 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1760 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1761 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1766 /* Decide if color named COLOR is valid for the display associated with
1767 the selected frame; if so, return the rgb values in COLOR_DEF.
1768 If ALLOC is nonzero, allocate a new colormap cell. */
1771 w32_defined_color (f, color, color_def, alloc)
1772 FRAME_PTR f;
1773 char *color;
1774 XColor *color_def;
1775 int alloc;
1777 register Lisp_Object tem;
1778 COLORREF w32_color_ref;
1780 tem = x_to_w32_color (color);
1782 if (!NILP (tem))
1784 if (f)
1786 /* Apply gamma correction. */
1787 w32_color_ref = XUINT (tem);
1788 gamma_correct (f, &w32_color_ref);
1789 XSETINT (tem, w32_color_ref);
1792 /* Map this color to the palette if it is enabled. */
1793 if (!NILP (Vw32_enable_palette))
1795 struct w32_palette_entry * entry =
1796 one_w32_display_info.color_list;
1797 struct w32_palette_entry ** prev =
1798 &one_w32_display_info.color_list;
1800 /* check if color is already mapped */
1801 while (entry)
1803 if (W32_COLOR (entry->entry) == XUINT (tem))
1804 break;
1805 prev = &entry->next;
1806 entry = entry->next;
1809 if (entry == NULL && alloc)
1811 /* not already mapped, so add to list */
1812 entry = (struct w32_palette_entry *)
1813 xmalloc (sizeof (struct w32_palette_entry));
1814 SET_W32_COLOR (entry->entry, XUINT (tem));
1815 entry->next = NULL;
1816 *prev = entry;
1817 one_w32_display_info.num_colors++;
1819 /* set flag that palette must be regenerated */
1820 one_w32_display_info.regen_palette = TRUE;
1823 /* Ensure COLORREF value is snapped to nearest color in (default)
1824 palette by simulating the PALETTERGB macro. This works whether
1825 or not the display device has a palette. */
1826 w32_color_ref = XUINT (tem) | 0x2000000;
1828 color_def->pixel = w32_color_ref;
1829 color_def->red = GetRValue (w32_color_ref);
1830 color_def->green = GetGValue (w32_color_ref);
1831 color_def->blue = GetBValue (w32_color_ref);
1833 return 1;
1835 else
1837 return 0;
1841 /* Given a string ARG naming a color, compute a pixel value from it
1842 suitable for screen F.
1843 If F is not a color screen, return DEF (default) regardless of what
1844 ARG says. */
1847 x_decode_color (f, arg, def)
1848 FRAME_PTR f;
1849 Lisp_Object arg;
1850 int def;
1852 XColor cdef;
1854 CHECK_STRING (arg, 0);
1856 if (strcmp (XSTRING (arg)->data, "black") == 0)
1857 return BLACK_PIX_DEFAULT (f);
1858 else if (strcmp (XSTRING (arg)->data, "white") == 0)
1859 return WHITE_PIX_DEFAULT (f);
1861 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1862 return def;
1864 /* w32_defined_color is responsible for coping with failures
1865 by looking for a near-miss. */
1866 if (w32_defined_color (f, XSTRING (arg)->data, &cdef, 1))
1867 return cdef.pixel;
1869 /* defined_color failed; return an ultimate default. */
1870 return def;
1873 /* Change the `screen-gamma' frame parameter of frame F. OLD_VALUE is
1874 the previous value of that parameter, NEW_VALUE is the new value. */
1876 static void
1877 x_set_screen_gamma (f, new_value, old_value)
1878 struct frame *f;
1879 Lisp_Object new_value, old_value;
1881 if (NILP (new_value))
1882 f->gamma = 0;
1883 else if (NUMBERP (new_value) && XFLOATINT (new_value) > 0)
1884 /* The value 0.4545 is the normal viewing gamma. */
1885 f->gamma = 1.0 / (0.4545 * XFLOATINT (new_value));
1886 else
1887 Fsignal (Qerror, Fcons (build_string ("Illegal screen-gamma"),
1888 Fcons (new_value, Qnil)));
1890 clear_face_cache (0);
1894 /* Functions called only from `x_set_frame_param'
1895 to set individual parameters.
1897 If FRAME_W32_WINDOW (f) is 0,
1898 the frame is being created and its window does not exist yet.
1899 In that case, just record the parameter's new value
1900 in the standard place; do not attempt to change the window. */
1902 void
1903 x_set_foreground_color (f, arg, oldval)
1904 struct frame *f;
1905 Lisp_Object arg, oldval;
1907 FRAME_FOREGROUND_PIXEL (f)
1908 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1910 if (FRAME_W32_WINDOW (f) != 0)
1912 update_face_from_frame_parameter (f, Qforeground_color, arg);
1913 if (FRAME_VISIBLE_P (f))
1914 redraw_frame (f);
1918 void
1919 x_set_background_color (f, arg, oldval)
1920 struct frame *f;
1921 Lisp_Object arg, oldval;
1923 FRAME_BACKGROUND_PIXEL (f)
1924 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1926 if (FRAME_W32_WINDOW (f) != 0)
1928 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1929 FRAME_BACKGROUND_PIXEL (f));
1931 update_face_from_frame_parameter (f, Qbackground_color, arg);
1933 if (FRAME_VISIBLE_P (f))
1934 redraw_frame (f);
1938 void
1939 x_set_mouse_color (f, arg, oldval)
1940 struct frame *f;
1941 Lisp_Object arg, oldval;
1944 Cursor cursor, nontext_cursor, mode_cursor, cross_cursor;
1945 int count;
1946 int mask_color;
1948 if (!EQ (Qnil, arg))
1949 f->output_data.w32->mouse_pixel
1950 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1951 mask_color = FRAME_BACKGROUND_PIXEL (f);
1953 /* Don't let pointers be invisible. */
1954 if (mask_color == f->output_data.w32->mouse_pixel
1955 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1956 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1958 #if 0 /* NTEMACS_TODO : cursor changes */
1959 BLOCK_INPUT;
1961 /* It's not okay to crash if the user selects a screwy cursor. */
1962 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1964 if (!EQ (Qnil, Vx_pointer_shape))
1966 CHECK_NUMBER (Vx_pointer_shape, 0);
1967 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1969 else
1970 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1971 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1973 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1975 CHECK_NUMBER (Vx_nontext_pointer_shape, 0);
1976 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1977 XINT (Vx_nontext_pointer_shape));
1979 else
1980 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1981 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1983 if (!EQ (Qnil, Vx_busy_pointer_shape))
1985 CHECK_NUMBER (Vx_busy_pointer_shape, 0);
1986 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1987 XINT (Vx_busy_pointer_shape));
1989 else
1990 busy_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1991 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1993 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1994 if (!EQ (Qnil, Vx_mode_pointer_shape))
1996 CHECK_NUMBER (Vx_mode_pointer_shape, 0);
1997 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1998 XINT (Vx_mode_pointer_shape));
2000 else
2001 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
2002 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
2004 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
2006 CHECK_NUMBER (Vx_sensitive_text_pointer_shape, 0);
2007 cross_cursor
2008 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
2009 XINT (Vx_sensitive_text_pointer_shape));
2011 else
2012 cross_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
2014 /* Check and report errors with the above calls. */
2015 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
2016 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
2019 XColor fore_color, back_color;
2021 fore_color.pixel = f->output_data.w32->mouse_pixel;
2022 back_color.pixel = mask_color;
2023 XQueryColor (FRAME_W32_DISPLAY (f),
2024 DefaultColormap (FRAME_W32_DISPLAY (f),
2025 DefaultScreen (FRAME_W32_DISPLAY (f))),
2026 &fore_color);
2027 XQueryColor (FRAME_W32_DISPLAY (f),
2028 DefaultColormap (FRAME_W32_DISPLAY (f),
2029 DefaultScreen (FRAME_W32_DISPLAY (f))),
2030 &back_color);
2031 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
2032 &fore_color, &back_color);
2033 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
2034 &fore_color, &back_color);
2035 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
2036 &fore_color, &back_color);
2037 XRecolorCursor (FRAME_W32_DISPLAY (f), cross_cursor,
2038 &fore_color, &back_color);
2039 XRecolorCursor (FRAME_W32_DISPLAY (f), busy_cursor,
2040 &fore_color, &back_color);
2043 if (FRAME_W32_WINDOW (f) != 0)
2044 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
2046 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
2047 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
2048 f->output_data.w32->text_cursor = cursor;
2050 if (nontext_cursor != f->output_data.w32->nontext_cursor
2051 && f->output_data.w32->nontext_cursor != 0)
2052 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
2053 f->output_data.w32->nontext_cursor = nontext_cursor;
2055 if (busy_cursor != f->output_data.w32->busy_cursor
2056 && f->output_data.w32->busy_cursor != 0)
2057 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->busy_cursor);
2058 f->output_data.w32->busy_cursor = busy_cursor;
2060 if (mode_cursor != f->output_data.w32->modeline_cursor
2061 && f->output_data.w32->modeline_cursor != 0)
2062 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
2063 f->output_data.w32->modeline_cursor = mode_cursor;
2065 if (cross_cursor != f->output_data.w32->cross_cursor
2066 && f->output_data.w32->cross_cursor != 0)
2067 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->cross_cursor);
2068 f->output_data.w32->cross_cursor = cross_cursor;
2070 XFlush (FRAME_W32_DISPLAY (f));
2071 UNBLOCK_INPUT;
2073 update_face_from_frame_parameter (f, Qmouse_color, arg);
2074 #endif /* NTEMACS_TODO */
2077 void
2078 x_set_cursor_color (f, arg, oldval)
2079 struct frame *f;
2080 Lisp_Object arg, oldval;
2082 unsigned long fore_pixel;
2084 if (!EQ (Vx_cursor_fore_pixel, Qnil))
2085 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
2086 WHITE_PIX_DEFAULT (f));
2087 else
2088 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2089 f->output_data.w32->cursor_pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2091 /* Make sure that the cursor color differs from the background color. */
2092 if (f->output_data.w32->cursor_pixel == FRAME_BACKGROUND_PIXEL (f))
2094 f->output_data.w32->cursor_pixel = f->output_data.w32->mouse_pixel;
2095 if (f->output_data.w32->cursor_pixel == fore_pixel)
2096 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
2098 FRAME_FOREGROUND_PIXEL (f) = fore_pixel;
2100 if (FRAME_W32_WINDOW (f) != 0)
2102 if (FRAME_VISIBLE_P (f))
2104 x_display_cursor (f, 0);
2105 x_display_cursor (f, 1);
2109 update_face_from_frame_parameter (f, Qcursor_color, arg);
2112 /* Set the border-color of frame F to pixel value PIX.
2113 Note that this does not fully take effect if done before
2114 F has an window. */
2115 void
2116 x_set_border_pixel (f, pix)
2117 struct frame *f;
2118 int pix;
2120 f->output_data.w32->border_pixel = pix;
2122 if (FRAME_W32_WINDOW (f) != 0 && f->output_data.w32->border_width > 0)
2124 if (FRAME_VISIBLE_P (f))
2125 redraw_frame (f);
2129 /* Set the border-color of frame F to value described by ARG.
2130 ARG can be a string naming a color.
2131 The border-color is used for the border that is drawn by the server.
2132 Note that this does not fully take effect if done before
2133 F has a window; it must be redone when the window is created. */
2135 void
2136 x_set_border_color (f, arg, oldval)
2137 struct frame *f;
2138 Lisp_Object arg, oldval;
2140 int pix;
2142 CHECK_STRING (arg, 0);
2143 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
2144 x_set_border_pixel (f, pix);
2145 update_face_from_frame_parameter (f, Qborder_color, arg);
2148 void
2149 x_set_cursor_type (f, arg, oldval)
2150 FRAME_PTR f;
2151 Lisp_Object arg, oldval;
2153 if (EQ (arg, Qbar))
2155 FRAME_DESIRED_CURSOR (f) = BAR_CURSOR;
2156 f->output_data.w32->cursor_width = 2;
2158 else if (CONSP (arg) && EQ (XCAR (arg), Qbar)
2159 && INTEGERP (XCDR (arg)))
2161 FRAME_DESIRED_CURSOR (f) = BAR_CURSOR;
2162 f->output_data.w32->cursor_width = XINT (XCDR (arg));
2164 else
2165 /* Treat anything unknown as "box cursor".
2166 It was bad to signal an error; people have trouble fixing
2167 .Xdefaults with Emacs, when it has something bad in it. */
2168 FRAME_DESIRED_CURSOR (f) = FILLED_BOX_CURSOR;
2170 /* Make sure the cursor gets redrawn. This is overkill, but how
2171 often do people change cursor types? */
2172 update_mode_lines++;
2175 void
2176 x_set_icon_type (f, arg, oldval)
2177 struct frame *f;
2178 Lisp_Object arg, oldval;
2180 int result;
2182 if (NILP (arg) && NILP (oldval))
2183 return;
2185 if (STRINGP (arg) && STRINGP (oldval)
2186 && EQ (Fstring_equal (oldval, arg), Qt))
2187 return;
2189 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
2190 return;
2192 BLOCK_INPUT;
2194 result = x_bitmap_icon (f, arg);
2195 if (result)
2197 UNBLOCK_INPUT;
2198 error ("No icon window available");
2201 UNBLOCK_INPUT;
2204 /* Return non-nil if frame F wants a bitmap icon. */
2206 Lisp_Object
2207 x_icon_type (f)
2208 FRAME_PTR f;
2210 Lisp_Object tem;
2212 tem = assq_no_quit (Qicon_type, f->param_alist);
2213 if (CONSP (tem))
2214 return XCDR (tem);
2215 else
2216 return Qnil;
2219 void
2220 x_set_icon_name (f, arg, oldval)
2221 struct frame *f;
2222 Lisp_Object arg, oldval;
2224 int result;
2226 if (STRINGP (arg))
2228 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
2229 return;
2231 else if (!STRINGP (oldval) && EQ (oldval, Qnil) == EQ (arg, Qnil))
2232 return;
2234 f->icon_name = arg;
2236 #if 0
2237 if (f->output_data.w32->icon_bitmap != 0)
2238 return;
2240 BLOCK_INPUT;
2242 result = x_text_icon (f,
2243 (char *) XSTRING ((!NILP (f->icon_name)
2244 ? f->icon_name
2245 : !NILP (f->title)
2246 ? f->title
2247 : f->name))->data);
2249 if (result)
2251 UNBLOCK_INPUT;
2252 error ("No icon window available");
2255 /* If the window was unmapped (and its icon was mapped),
2256 the new icon is not mapped, so map the window in its stead. */
2257 if (FRAME_VISIBLE_P (f))
2259 #ifdef USE_X_TOOLKIT
2260 XtPopup (f->output_data.w32->widget, XtGrabNone);
2261 #endif
2262 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
2265 XFlush (FRAME_W32_DISPLAY (f));
2266 UNBLOCK_INPUT;
2267 #endif
2270 extern Lisp_Object x_new_font ();
2271 extern Lisp_Object x_new_fontset();
2273 void
2274 x_set_font (f, arg, oldval)
2275 struct frame *f;
2276 Lisp_Object arg, oldval;
2278 Lisp_Object result;
2279 Lisp_Object fontset_name;
2280 Lisp_Object frame;
2282 CHECK_STRING (arg, 1);
2284 fontset_name = Fquery_fontset (arg, Qnil);
2286 BLOCK_INPUT;
2287 result = (STRINGP (fontset_name)
2288 ? x_new_fontset (f, XSTRING (fontset_name)->data)
2289 : x_new_font (f, XSTRING (arg)->data));
2290 UNBLOCK_INPUT;
2292 if (EQ (result, Qnil))
2293 error ("Font \"%s\" is not defined", XSTRING (arg)->data);
2294 else if (EQ (result, Qt))
2295 error ("the characters of the given font have varying widths");
2296 else if (STRINGP (result))
2298 store_frame_param (f, Qfont, result);
2299 recompute_basic_faces (f);
2301 else
2302 abort ();
2304 do_pending_window_change (0);
2306 /* Don't call `face-set-after-frame-default' when faces haven't been
2307 initialized yet. This is the case when called from
2308 Fx_create_frame. In that case, the X widget or window doesn't
2309 exist either, and we can end up in x_report_frame_params with a
2310 null widget which gives a segfault. */
2311 if (FRAME_FACE_CACHE (f))
2313 XSETFRAME (frame, f);
2314 call1 (Qface_set_after_frame_default, frame);
2318 void
2319 x_set_border_width (f, arg, oldval)
2320 struct frame *f;
2321 Lisp_Object arg, oldval;
2323 CHECK_NUMBER (arg, 0);
2325 if (XINT (arg) == f->output_data.w32->border_width)
2326 return;
2328 if (FRAME_W32_WINDOW (f) != 0)
2329 error ("Cannot change the border width of a window");
2331 f->output_data.w32->border_width = XINT (arg);
2334 void
2335 x_set_internal_border_width (f, arg, oldval)
2336 struct frame *f;
2337 Lisp_Object arg, oldval;
2339 int old = f->output_data.w32->internal_border_width;
2341 CHECK_NUMBER (arg, 0);
2342 f->output_data.w32->internal_border_width = XINT (arg);
2343 if (f->output_data.w32->internal_border_width < 0)
2344 f->output_data.w32->internal_border_width = 0;
2346 if (f->output_data.w32->internal_border_width == old)
2347 return;
2349 if (FRAME_W32_WINDOW (f) != 0)
2351 x_set_window_size (f, 0, f->width, f->height);
2352 SET_FRAME_GARBAGED (f);
2353 do_pending_window_change (0);
2357 void
2358 x_set_visibility (f, value, oldval)
2359 struct frame *f;
2360 Lisp_Object value, oldval;
2362 Lisp_Object frame;
2363 XSETFRAME (frame, f);
2365 if (NILP (value))
2366 Fmake_frame_invisible (frame, Qt);
2367 else if (EQ (value, Qicon))
2368 Ficonify_frame (frame);
2369 else
2370 Fmake_frame_visible (frame);
2373 void
2374 x_set_menu_bar_lines (f, value, oldval)
2375 struct frame *f;
2376 Lisp_Object value, oldval;
2378 int nlines;
2379 int olines = FRAME_MENU_BAR_LINES (f);
2381 /* Right now, menu bars don't work properly in minibuf-only frames;
2382 most of the commands try to apply themselves to the minibuffer
2383 frame itself, and get an error because you can't switch buffers
2384 in or split the minibuffer window. */
2385 if (FRAME_MINIBUF_ONLY_P (f))
2386 return;
2388 if (INTEGERP (value))
2389 nlines = XINT (value);
2390 else
2391 nlines = 0;
2393 FRAME_MENU_BAR_LINES (f) = 0;
2394 if (nlines)
2395 FRAME_EXTERNAL_MENU_BAR (f) = 1;
2396 else
2398 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
2399 free_frame_menubar (f);
2400 FRAME_EXTERNAL_MENU_BAR (f) = 0;
2402 /* Adjust the frame size so that the client (text) dimensions
2403 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
2404 set correctly. */
2405 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2406 do_pending_window_change (0);
2408 adjust_glyphs (f);
2412 /* Set the number of lines used for the tool bar of frame F to VALUE.
2413 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
2414 is the old number of tool bar lines. This function changes the
2415 height of all windows on frame F to match the new tool bar height.
2416 The frame's height doesn't change. */
2418 void
2419 x_set_tool_bar_lines (f, value, oldval)
2420 struct frame *f;
2421 Lisp_Object value, oldval;
2423 int delta, nlines;
2425 /* Use VALUE only if an integer >= 0. */
2426 if (INTEGERP (value) && XINT (value) >= 0)
2427 nlines = XFASTINT (value);
2428 else
2429 nlines = 0;
2431 /* Make sure we redisplay all windows in this frame. */
2432 ++windows_or_buffers_changed;
2434 delta = nlines - FRAME_TOOL_BAR_LINES (f);
2435 FRAME_TOOL_BAR_LINES (f) = nlines;
2436 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2437 do_pending_window_change (0);
2438 adjust_glyphs (f);
2442 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
2443 w32_id_name.
2445 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2446 name; if NAME is a string, set F's name to NAME and set
2447 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2449 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2450 suggesting a new name, which lisp code should override; if
2451 F->explicit_name is set, ignore the new name; otherwise, set it. */
2453 void
2454 x_set_name (f, name, explicit)
2455 struct frame *f;
2456 Lisp_Object name;
2457 int explicit;
2459 /* Make sure that requests from lisp code override requests from
2460 Emacs redisplay code. */
2461 if (explicit)
2463 /* If we're switching from explicit to implicit, we had better
2464 update the mode lines and thereby update the title. */
2465 if (f->explicit_name && NILP (name))
2466 update_mode_lines = 1;
2468 f->explicit_name = ! NILP (name);
2470 else if (f->explicit_name)
2471 return;
2473 /* If NAME is nil, set the name to the w32_id_name. */
2474 if (NILP (name))
2476 /* Check for no change needed in this very common case
2477 before we do any consing. */
2478 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
2479 XSTRING (f->name)->data))
2480 return;
2481 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
2483 else
2484 CHECK_STRING (name, 0);
2486 /* Don't change the name if it's already NAME. */
2487 if (! NILP (Fstring_equal (name, f->name)))
2488 return;
2490 f->name = name;
2492 /* For setting the frame title, the title parameter should override
2493 the name parameter. */
2494 if (! NILP (f->title))
2495 name = f->title;
2497 if (FRAME_W32_WINDOW (f))
2499 if (STRING_MULTIBYTE (name))
2500 name = string_make_unibyte (name);
2502 BLOCK_INPUT;
2503 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2504 UNBLOCK_INPUT;
2508 /* This function should be called when the user's lisp code has
2509 specified a name for the frame; the name will override any set by the
2510 redisplay code. */
2511 void
2512 x_explicitly_set_name (f, arg, oldval)
2513 FRAME_PTR f;
2514 Lisp_Object arg, oldval;
2516 x_set_name (f, arg, 1);
2519 /* This function should be called by Emacs redisplay code to set the
2520 name; names set this way will never override names set by the user's
2521 lisp code. */
2522 void
2523 x_implicitly_set_name (f, arg, oldval)
2524 FRAME_PTR f;
2525 Lisp_Object arg, oldval;
2527 x_set_name (f, arg, 0);
2530 /* Change the title of frame F to NAME.
2531 If NAME is nil, use the frame name as the title.
2533 If EXPLICIT is non-zero, that indicates that lisp code is setting the
2534 name; if NAME is a string, set F's name to NAME and set
2535 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
2537 If EXPLICIT is zero, that indicates that Emacs redisplay code is
2538 suggesting a new name, which lisp code should override; if
2539 F->explicit_name is set, ignore the new name; otherwise, set it. */
2541 void
2542 x_set_title (f, name, old_name)
2543 struct frame *f;
2544 Lisp_Object name, old_name;
2546 /* Don't change the title if it's already NAME. */
2547 if (EQ (name, f->title))
2548 return;
2550 update_mode_lines = 1;
2552 f->title = name;
2554 if (NILP (name))
2555 name = f->name;
2557 if (FRAME_W32_WINDOW (f))
2559 if (STRING_MULTIBYTE (name))
2560 name = string_make_unibyte (name);
2562 BLOCK_INPUT;
2563 SetWindowText(FRAME_W32_WINDOW (f), XSTRING (name)->data);
2564 UNBLOCK_INPUT;
2568 void
2569 x_set_autoraise (f, arg, oldval)
2570 struct frame *f;
2571 Lisp_Object arg, oldval;
2573 f->auto_raise = !EQ (Qnil, arg);
2576 void
2577 x_set_autolower (f, arg, oldval)
2578 struct frame *f;
2579 Lisp_Object arg, oldval;
2581 f->auto_lower = !EQ (Qnil, arg);
2584 void
2585 x_set_unsplittable (f, arg, oldval)
2586 struct frame *f;
2587 Lisp_Object arg, oldval;
2589 f->no_split = !NILP (arg);
2592 void
2593 x_set_vertical_scroll_bars (f, arg, oldval)
2594 struct frame *f;
2595 Lisp_Object arg, oldval;
2597 if ((EQ (arg, Qleft) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_RIGHT (f))
2598 || (EQ (arg, Qright) && FRAME_HAS_VERTICAL_SCROLL_BARS_ON_LEFT (f))
2599 || (NILP (arg) && FRAME_HAS_VERTICAL_SCROLL_BARS (f))
2600 || (!NILP (arg) && ! FRAME_HAS_VERTICAL_SCROLL_BARS (f)))
2602 FRAME_VERTICAL_SCROLL_BAR_TYPE (f) = NILP (arg) ?
2603 vertical_scroll_bar_none :
2604 /* Put scroll bars on the right by default, as is conventional
2605 on MS-Windows. */
2606 EQ (Qleft, arg)
2607 ? vertical_scroll_bar_left
2608 : vertical_scroll_bar_right;
2610 /* We set this parameter before creating the window for the
2611 frame, so we can get the geometry right from the start.
2612 However, if the window hasn't been created yet, we shouldn't
2613 call x_set_window_size. */
2614 if (FRAME_W32_WINDOW (f))
2615 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2616 do_pending_window_change (0);
2620 void
2621 x_set_scroll_bar_width (f, arg, oldval)
2622 struct frame *f;
2623 Lisp_Object arg, oldval;
2625 int wid = FONT_WIDTH (f->output_data.w32->font);
2627 if (NILP (arg))
2629 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
2630 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f) +
2631 wid - 1) / wid;
2632 if (FRAME_W32_WINDOW (f))
2633 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2634 do_pending_window_change (0);
2636 else if (INTEGERP (arg) && XINT (arg) > 0
2637 && XFASTINT (arg) != FRAME_SCROLL_BAR_PIXEL_WIDTH (f))
2639 FRAME_SCROLL_BAR_PIXEL_WIDTH (f) = XFASTINT (arg);
2640 FRAME_SCROLL_BAR_COLS (f) = (FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
2641 + wid-1) / wid;
2642 if (FRAME_W32_WINDOW (f))
2643 x_set_window_size (f, 0, FRAME_WIDTH (f), FRAME_HEIGHT (f));
2644 do_pending_window_change (0);
2646 change_frame_size (f, 0, FRAME_WIDTH (f), 0, 0, 0);
2647 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.hpos = 0;
2648 XWINDOW (FRAME_SELECTED_WINDOW (f))->cursor.x = 0;
2651 /* Subroutines of creating an frame. */
2653 /* Make sure that Vx_resource_name is set to a reasonable value.
2654 Fix it up, or set it to `emacs' if it is too hopeless. */
2656 static void
2657 validate_x_resource_name ()
2659 int len = 0;
2660 /* Number of valid characters in the resource name. */
2661 int good_count = 0;
2662 /* Number of invalid characters in the resource name. */
2663 int bad_count = 0;
2664 Lisp_Object new;
2665 int i;
2667 if (STRINGP (Vx_resource_name))
2669 unsigned char *p = XSTRING (Vx_resource_name)->data;
2670 int i;
2672 len = XSTRING (Vx_resource_name)->size;
2674 /* Only letters, digits, - and _ are valid in resource names.
2675 Count the valid characters and count the invalid ones. */
2676 for (i = 0; i < len; i++)
2678 int c = p[i];
2679 if (! ((c >= 'a' && c <= 'z')
2680 || (c >= 'A' && c <= 'Z')
2681 || (c >= '0' && c <= '9')
2682 || c == '-' || c == '_'))
2683 bad_count++;
2684 else
2685 good_count++;
2688 else
2689 /* Not a string => completely invalid. */
2690 bad_count = 5, good_count = 0;
2692 /* If name is valid already, return. */
2693 if (bad_count == 0)
2694 return;
2696 /* If name is entirely invalid, or nearly so, use `emacs'. */
2697 if (good_count == 0
2698 || (good_count == 1 && bad_count > 0))
2700 Vx_resource_name = build_string ("emacs");
2701 return;
2704 /* Name is partly valid. Copy it and replace the invalid characters
2705 with underscores. */
2707 Vx_resource_name = new = Fcopy_sequence (Vx_resource_name);
2709 for (i = 0; i < len; i++)
2711 int c = XSTRING (new)->data[i];
2712 if (! ((c >= 'a' && c <= 'z')
2713 || (c >= 'A' && c <= 'Z')
2714 || (c >= '0' && c <= '9')
2715 || c == '-' || c == '_'))
2716 XSTRING (new)->data[i] = '_';
2721 extern char *x_get_string_resource ();
2723 DEFUN ("x-get-resource", Fx_get_resource, Sx_get_resource, 2, 4, 0,
2724 "Return the value of ATTRIBUTE, of class CLASS, from the X defaults database.\n\
2725 This uses `INSTANCE.ATTRIBUTE' as the key and `Emacs.CLASS' as the\n\
2726 class, where INSTANCE is the name under which Emacs was invoked, or\n\
2727 the name specified by the `-name' or `-rn' command-line arguments.\n\
2729 The optional arguments COMPONENT and SUBCLASS add to the key and the\n\
2730 class, respectively. You must specify both of them or neither.\n\
2731 If you specify them, the key is `INSTANCE.COMPONENT.ATTRIBUTE'\n\
2732 and the class is `Emacs.CLASS.SUBCLASS'.")
2733 (attribute, class, component, subclass)
2734 Lisp_Object attribute, class, component, subclass;
2736 register char *value;
2737 char *name_key;
2738 char *class_key;
2740 CHECK_STRING (attribute, 0);
2741 CHECK_STRING (class, 0);
2743 if (!NILP (component))
2744 CHECK_STRING (component, 1);
2745 if (!NILP (subclass))
2746 CHECK_STRING (subclass, 2);
2747 if (NILP (component) != NILP (subclass))
2748 error ("x-get-resource: must specify both COMPONENT and SUBCLASS or neither");
2750 validate_x_resource_name ();
2752 /* Allocate space for the components, the dots which separate them,
2753 and the final '\0'. Make them big enough for the worst case. */
2754 name_key = (char *) alloca (XSTRING (Vx_resource_name)->size
2755 + (STRINGP (component)
2756 ? XSTRING (component)->size : 0)
2757 + XSTRING (attribute)->size
2758 + 3);
2760 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2761 + XSTRING (class)->size
2762 + (STRINGP (subclass)
2763 ? XSTRING (subclass)->size : 0)
2764 + 3);
2766 /* Start with emacs.FRAMENAME for the name (the specific one)
2767 and with `Emacs' for the class key (the general one). */
2768 strcpy (name_key, XSTRING (Vx_resource_name)->data);
2769 strcpy (class_key, EMACS_CLASS);
2771 strcat (class_key, ".");
2772 strcat (class_key, XSTRING (class)->data);
2774 if (!NILP (component))
2776 strcat (class_key, ".");
2777 strcat (class_key, XSTRING (subclass)->data);
2779 strcat (name_key, ".");
2780 strcat (name_key, XSTRING (component)->data);
2783 strcat (name_key, ".");
2784 strcat (name_key, XSTRING (attribute)->data);
2786 value = x_get_string_resource (Qnil,
2787 name_key, class_key);
2789 if (value != (char *) 0)
2790 return build_string (value);
2791 else
2792 return Qnil;
2795 /* Used when C code wants a resource value. */
2797 char *
2798 x_get_resource_string (attribute, class)
2799 char *attribute, *class;
2801 char *name_key;
2802 char *class_key;
2803 struct frame *sf = SELECTED_FRAME ();
2805 /* Allocate space for the components, the dots which separate them,
2806 and the final '\0'. */
2807 name_key = (char *) alloca (XSTRING (Vinvocation_name)->size
2808 + strlen (attribute) + 2);
2809 class_key = (char *) alloca ((sizeof (EMACS_CLASS) - 1)
2810 + strlen (class) + 2);
2812 sprintf (name_key, "%s.%s",
2813 XSTRING (Vinvocation_name)->data,
2814 attribute);
2815 sprintf (class_key, "%s.%s", EMACS_CLASS, class);
2817 return x_get_string_resource (sf, name_key, class_key);
2820 /* Types we might convert a resource string into. */
2821 enum resource_types
2823 RES_TYPE_NUMBER,
2824 RES_TYPE_FLOAT,
2825 RES_TYPE_BOOLEAN,
2826 RES_TYPE_STRING,
2827 RES_TYPE_SYMBOL
2830 /* Return the value of parameter PARAM.
2832 First search ALIST, then Vdefault_frame_alist, then the X defaults
2833 database, using ATTRIBUTE as the attribute name and CLASS as its class.
2835 Convert the resource to the type specified by desired_type.
2837 If no default is specified, return Qunbound. If you call
2838 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
2839 and don't let it get stored in any Lisp-visible variables! */
2841 static Lisp_Object
2842 w32_get_arg (alist, param, attribute, class, type)
2843 Lisp_Object alist, param;
2844 char *attribute;
2845 char *class;
2846 enum resource_types type;
2848 register Lisp_Object tem;
2850 tem = Fassq (param, alist);
2851 if (EQ (tem, Qnil))
2852 tem = Fassq (param, Vdefault_frame_alist);
2853 if (EQ (tem, Qnil))
2856 if (attribute)
2858 tem = Fx_get_resource (build_string (attribute),
2859 build_string (class),
2860 Qnil, Qnil);
2862 if (NILP (tem))
2863 return Qunbound;
2865 switch (type)
2867 case RES_TYPE_NUMBER:
2868 return make_number (atoi (XSTRING (tem)->data));
2870 case RES_TYPE_FLOAT:
2871 return make_float (atof (XSTRING (tem)->data));
2873 case RES_TYPE_BOOLEAN:
2874 tem = Fdowncase (tem);
2875 if (!strcmp (XSTRING (tem)->data, "on")
2876 || !strcmp (XSTRING (tem)->data, "true"))
2877 return Qt;
2878 else
2879 return Qnil;
2881 case RES_TYPE_STRING:
2882 return tem;
2884 case RES_TYPE_SYMBOL:
2885 /* As a special case, we map the values `true' and `on'
2886 to Qt, and `false' and `off' to Qnil. */
2888 Lisp_Object lower;
2889 lower = Fdowncase (tem);
2890 if (!strcmp (XSTRING (lower)->data, "on")
2891 || !strcmp (XSTRING (lower)->data, "true"))
2892 return Qt;
2893 else if (!strcmp (XSTRING (lower)->data, "off")
2894 || !strcmp (XSTRING (lower)->data, "false"))
2895 return Qnil;
2896 else
2897 return Fintern (tem, Qnil);
2900 default:
2901 abort ();
2904 else
2905 return Qunbound;
2907 return Fcdr (tem);
2910 /* Record in frame F the specified or default value according to ALIST
2911 of the parameter named PARAM (a Lisp symbol).
2912 If no value is specified for PARAM, look for an X default for XPROP
2913 on the frame named NAME.
2914 If that is not found either, use the value DEFLT. */
2916 static Lisp_Object
2917 x_default_parameter (f, alist, prop, deflt, xprop, xclass, type)
2918 struct frame *f;
2919 Lisp_Object alist;
2920 Lisp_Object prop;
2921 Lisp_Object deflt;
2922 char *xprop;
2923 char *xclass;
2924 enum resource_types type;
2926 Lisp_Object tem;
2928 tem = w32_get_arg (alist, prop, xprop, xclass, type);
2929 if (EQ (tem, Qunbound))
2930 tem = deflt;
2931 x_set_frame_parameters (f, Fcons (Fcons (prop, tem), Qnil));
2932 return tem;
2935 DEFUN ("x-parse-geometry", Fx_parse_geometry, Sx_parse_geometry, 1, 1, 0,
2936 "Parse an X-style geometry string STRING.\n\
2937 Returns an alist of the form ((top . TOP), (left . LEFT) ... ).\n\
2938 The properties returned may include `top', `left', `height', and `width'.\n\
2939 The value of `left' or `top' may be an integer,\n\
2940 or a list (+ N) meaning N pixels relative to top/left corner,\n\
2941 or a list (- N) meaning -N pixels relative to bottom/right corner.")
2942 (string)
2943 Lisp_Object string;
2945 int geometry, x, y;
2946 unsigned int width, height;
2947 Lisp_Object result;
2949 CHECK_STRING (string, 0);
2951 geometry = XParseGeometry ((char *) XSTRING (string)->data,
2952 &x, &y, &width, &height);
2954 result = Qnil;
2955 if (geometry & XValue)
2957 Lisp_Object element;
2959 if (x >= 0 && (geometry & XNegative))
2960 element = Fcons (Qleft, Fcons (Qminus, Fcons (make_number (-x), Qnil)));
2961 else if (x < 0 && ! (geometry & XNegative))
2962 element = Fcons (Qleft, Fcons (Qplus, Fcons (make_number (x), Qnil)));
2963 else
2964 element = Fcons (Qleft, make_number (x));
2965 result = Fcons (element, result);
2968 if (geometry & YValue)
2970 Lisp_Object element;
2972 if (y >= 0 && (geometry & YNegative))
2973 element = Fcons (Qtop, Fcons (Qminus, Fcons (make_number (-y), Qnil)));
2974 else if (y < 0 && ! (geometry & YNegative))
2975 element = Fcons (Qtop, Fcons (Qplus, Fcons (make_number (y), Qnil)));
2976 else
2977 element = Fcons (Qtop, make_number (y));
2978 result = Fcons (element, result);
2981 if (geometry & WidthValue)
2982 result = Fcons (Fcons (Qwidth, make_number (width)), result);
2983 if (geometry & HeightValue)
2984 result = Fcons (Fcons (Qheight, make_number (height)), result);
2986 return result;
2989 /* Calculate the desired size and position of this window,
2990 and return the flags saying which aspects were specified.
2992 This function does not make the coordinates positive. */
2994 #define DEFAULT_ROWS 40
2995 #define DEFAULT_COLS 80
2997 static int
2998 x_figure_window_size (f, parms)
2999 struct frame *f;
3000 Lisp_Object parms;
3002 register Lisp_Object tem0, tem1, tem2;
3003 long window_prompting = 0;
3005 /* Default values if we fall through.
3006 Actually, if that happens we should get
3007 window manager prompting. */
3008 SET_FRAME_WIDTH (f, DEFAULT_COLS);
3009 f->height = DEFAULT_ROWS;
3010 /* Window managers expect that if program-specified
3011 positions are not (0,0), they're intentional, not defaults. */
3012 f->output_data.w32->top_pos = 0;
3013 f->output_data.w32->left_pos = 0;
3015 tem0 = w32_get_arg (parms, Qheight, 0, 0, RES_TYPE_NUMBER);
3016 tem1 = w32_get_arg (parms, Qwidth, 0, 0, RES_TYPE_NUMBER);
3017 tem2 = w32_get_arg (parms, Quser_size, 0, 0, RES_TYPE_NUMBER);
3018 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3020 if (!EQ (tem0, Qunbound))
3022 CHECK_NUMBER (tem0, 0);
3023 f->height = XINT (tem0);
3025 if (!EQ (tem1, Qunbound))
3027 CHECK_NUMBER (tem1, 0);
3028 SET_FRAME_WIDTH (f, XINT (tem1));
3030 if (!NILP (tem2) && !EQ (tem2, Qunbound))
3031 window_prompting |= USSize;
3032 else
3033 window_prompting |= PSize;
3036 f->output_data.w32->vertical_scroll_bar_extra
3037 = (!FRAME_HAS_VERTICAL_SCROLL_BARS (f)
3039 : FRAME_SCROLL_BAR_PIXEL_WIDTH (f) > 0
3040 ? FRAME_SCROLL_BAR_PIXEL_WIDTH (f)
3041 : (FRAME_SCROLL_BAR_COLS (f) * FONT_WIDTH (f->output_data.w32->font)));
3042 f->output_data.w32->flags_areas_extra
3043 = FRAME_FLAGS_AREA_WIDTH (f);
3044 f->output_data.w32->pixel_width = CHAR_TO_PIXEL_WIDTH (f, f->width);
3045 f->output_data.w32->pixel_height = CHAR_TO_PIXEL_HEIGHT (f, f->height);
3047 tem0 = w32_get_arg (parms, Qtop, 0, 0, RES_TYPE_NUMBER);
3048 tem1 = w32_get_arg (parms, Qleft, 0, 0, RES_TYPE_NUMBER);
3049 tem2 = w32_get_arg (parms, Quser_position, 0, 0, RES_TYPE_NUMBER);
3050 if (! EQ (tem0, Qunbound) || ! EQ (tem1, Qunbound))
3052 if (EQ (tem0, Qminus))
3054 f->output_data.w32->top_pos = 0;
3055 window_prompting |= YNegative;
3057 else if (CONSP (tem0) && EQ (XCAR (tem0), Qminus)
3058 && CONSP (XCDR (tem0))
3059 && INTEGERP (XCAR (XCDR (tem0))))
3061 f->output_data.w32->top_pos = - XINT (XCAR (XCDR (tem0)));
3062 window_prompting |= YNegative;
3064 else if (CONSP (tem0) && EQ (XCAR (tem0), Qplus)
3065 && CONSP (XCDR (tem0))
3066 && INTEGERP (XCAR (XCDR (tem0))))
3068 f->output_data.w32->top_pos = XINT (XCAR (XCDR (tem0)));
3070 else if (EQ (tem0, Qunbound))
3071 f->output_data.w32->top_pos = 0;
3072 else
3074 CHECK_NUMBER (tem0, 0);
3075 f->output_data.w32->top_pos = XINT (tem0);
3076 if (f->output_data.w32->top_pos < 0)
3077 window_prompting |= YNegative;
3080 if (EQ (tem1, Qminus))
3082 f->output_data.w32->left_pos = 0;
3083 window_prompting |= XNegative;
3085 else if (CONSP (tem1) && EQ (XCAR (tem1), Qminus)
3086 && CONSP (XCDR (tem1))
3087 && INTEGERP (XCAR (XCDR (tem1))))
3089 f->output_data.w32->left_pos = - XINT (XCAR (XCDR (tem1)));
3090 window_prompting |= XNegative;
3092 else if (CONSP (tem1) && EQ (XCAR (tem1), Qplus)
3093 && CONSP (XCDR (tem1))
3094 && INTEGERP (XCAR (XCDR (tem1))))
3096 f->output_data.w32->left_pos = XINT (XCAR (XCDR (tem1)));
3098 else if (EQ (tem1, Qunbound))
3099 f->output_data.w32->left_pos = 0;
3100 else
3102 CHECK_NUMBER (tem1, 0);
3103 f->output_data.w32->left_pos = XINT (tem1);
3104 if (f->output_data.w32->left_pos < 0)
3105 window_prompting |= XNegative;
3108 if (!NILP (tem2) && ! EQ (tem2, Qunbound))
3109 window_prompting |= USPosition;
3110 else
3111 window_prompting |= PPosition;
3114 return window_prompting;
3119 extern LRESULT CALLBACK w32_wnd_proc ();
3121 BOOL
3122 w32_init_class (hinst)
3123 HINSTANCE hinst;
3125 WNDCLASS wc;
3127 wc.style = CS_HREDRAW | CS_VREDRAW;
3128 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
3129 wc.cbClsExtra = 0;
3130 wc.cbWndExtra = WND_EXTRA_BYTES;
3131 wc.hInstance = hinst;
3132 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
3133 wc.hCursor = LoadCursor (NULL, IDC_ARROW);
3134 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
3135 wc.lpszMenuName = NULL;
3136 wc.lpszClassName = EMACS_CLASS;
3138 return (RegisterClass (&wc));
3141 HWND
3142 w32_createscrollbar (f, bar)
3143 struct frame *f;
3144 struct scroll_bar * bar;
3146 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
3147 /* Position and size of scroll bar. */
3148 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
3149 XINT(bar->top),
3150 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
3151 XINT(bar->height),
3152 FRAME_W32_WINDOW (f),
3153 NULL,
3154 hinst,
3155 NULL));
3158 void
3159 w32_createwindow (f)
3160 struct frame *f;
3162 HWND hwnd;
3163 RECT rect;
3165 rect.left = rect.top = 0;
3166 rect.right = PIXEL_WIDTH (f);
3167 rect.bottom = PIXEL_HEIGHT (f);
3169 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3170 FRAME_EXTERNAL_MENU_BAR (f));
3172 /* Do first time app init */
3174 if (!hprevinst)
3176 w32_init_class (hinst);
3179 FRAME_W32_WINDOW (f) = hwnd
3180 = CreateWindow (EMACS_CLASS,
3181 f->namebuf,
3182 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
3183 f->output_data.w32->left_pos,
3184 f->output_data.w32->top_pos,
3185 rect.right - rect.left,
3186 rect.bottom - rect.top,
3187 NULL,
3188 NULL,
3189 hinst,
3190 NULL);
3192 if (hwnd)
3194 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FONT_WIDTH (f->output_data.w32->font));
3195 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, f->output_data.w32->line_height);
3196 SetWindowLong (hwnd, WND_BORDER_INDEX, f->output_data.w32->internal_border_width);
3197 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->output_data.w32->vertical_scroll_bar_extra);
3198 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3200 /* Enable drag-n-drop. */
3201 DragAcceptFiles (hwnd, TRUE);
3203 /* Do this to discard the default setting specified by our parent. */
3204 ShowWindow (hwnd, SW_HIDE);
3208 void
3209 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
3210 W32Msg * wmsg;
3211 HWND hwnd;
3212 UINT msg;
3213 WPARAM wParam;
3214 LPARAM lParam;
3216 wmsg->msg.hwnd = hwnd;
3217 wmsg->msg.message = msg;
3218 wmsg->msg.wParam = wParam;
3219 wmsg->msg.lParam = lParam;
3220 wmsg->msg.time = GetMessageTime ();
3222 post_msg (wmsg);
3225 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
3226 between left and right keys as advertised. We test for this
3227 support dynamically, and set a flag when the support is absent. If
3228 absent, we keep track of the left and right control and alt keys
3229 ourselves. This is particularly necessary on keyboards that rely
3230 upon the AltGr key, which is represented as having the left control
3231 and right alt keys pressed. For these keyboards, we need to know
3232 when the left alt key has been pressed in addition to the AltGr key
3233 so that we can properly support M-AltGr-key sequences (such as M-@
3234 on Swedish keyboards). */
3236 #define EMACS_LCONTROL 0
3237 #define EMACS_RCONTROL 1
3238 #define EMACS_LMENU 2
3239 #define EMACS_RMENU 3
3241 static int modifiers[4];
3242 static int modifiers_recorded;
3243 static int modifier_key_support_tested;
3245 static void
3246 test_modifier_support (unsigned int wparam)
3248 unsigned int l, r;
3250 if (wparam != VK_CONTROL && wparam != VK_MENU)
3251 return;
3252 if (wparam == VK_CONTROL)
3254 l = VK_LCONTROL;
3255 r = VK_RCONTROL;
3257 else
3259 l = VK_LMENU;
3260 r = VK_RMENU;
3262 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
3263 modifiers_recorded = 1;
3264 else
3265 modifiers_recorded = 0;
3266 modifier_key_support_tested = 1;
3269 static void
3270 record_keydown (unsigned int wparam, unsigned int lparam)
3272 int i;
3274 if (!modifier_key_support_tested)
3275 test_modifier_support (wparam);
3277 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3278 return;
3280 if (wparam == VK_CONTROL)
3281 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3282 else
3283 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3285 modifiers[i] = 1;
3288 static void
3289 record_keyup (unsigned int wparam, unsigned int lparam)
3291 int i;
3293 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
3294 return;
3296 if (wparam == VK_CONTROL)
3297 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
3298 else
3299 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
3301 modifiers[i] = 0;
3304 /* Emacs can lose focus while a modifier key has been pressed. When
3305 it regains focus, be conservative and clear all modifiers since
3306 we cannot reconstruct the left and right modifier state. */
3307 static void
3308 reset_modifiers ()
3310 SHORT ctrl, alt;
3312 if (GetFocus () == NULL)
3313 /* Emacs doesn't have keyboard focus. Do nothing. */
3314 return;
3316 ctrl = GetAsyncKeyState (VK_CONTROL);
3317 alt = GetAsyncKeyState (VK_MENU);
3319 if (!(ctrl & 0x08000))
3320 /* Clear any recorded control modifier state. */
3321 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3323 if (!(alt & 0x08000))
3324 /* Clear any recorded alt modifier state. */
3325 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3327 /* Update the state of all modifier keys, because modifiers used in
3328 hot-key combinations can get stuck on if Emacs loses focus as a
3329 result of a hot-key being pressed. */
3331 BYTE keystate[256];
3333 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
3335 GetKeyboardState (keystate);
3336 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
3337 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
3338 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
3339 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
3340 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
3341 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
3342 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
3343 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
3344 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
3345 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
3346 SetKeyboardState (keystate);
3350 /* Synchronize modifier state with what is reported with the current
3351 keystroke. Even if we cannot distinguish between left and right
3352 modifier keys, we know that, if no modifiers are set, then neither
3353 the left or right modifier should be set. */
3354 static void
3355 sync_modifiers ()
3357 if (!modifiers_recorded)
3358 return;
3360 if (!(GetKeyState (VK_CONTROL) & 0x8000))
3361 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
3363 if (!(GetKeyState (VK_MENU) & 0x8000))
3364 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
3367 static int
3368 modifier_set (int vkey)
3370 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
3371 return (GetKeyState (vkey) & 0x1);
3372 if (!modifiers_recorded)
3373 return (GetKeyState (vkey) & 0x8000);
3375 switch (vkey)
3377 case VK_LCONTROL:
3378 return modifiers[EMACS_LCONTROL];
3379 case VK_RCONTROL:
3380 return modifiers[EMACS_RCONTROL];
3381 case VK_LMENU:
3382 return modifiers[EMACS_LMENU];
3383 case VK_RMENU:
3384 return modifiers[EMACS_RMENU];
3386 return (GetKeyState (vkey) & 0x8000);
3389 /* Convert between the modifier bits W32 uses and the modifier bits
3390 Emacs uses. */
3392 unsigned int
3393 w32_key_to_modifier (int key)
3395 Lisp_Object key_mapping;
3397 switch (key)
3399 case VK_LWIN:
3400 key_mapping = Vw32_lwindow_modifier;
3401 break;
3402 case VK_RWIN:
3403 key_mapping = Vw32_rwindow_modifier;
3404 break;
3405 case VK_APPS:
3406 key_mapping = Vw32_apps_modifier;
3407 break;
3408 case VK_SCROLL:
3409 key_mapping = Vw32_scroll_lock_modifier;
3410 break;
3411 default:
3412 key_mapping = Qnil;
3415 /* NB. This code runs in the input thread, asychronously to the lisp
3416 thread, so we must be careful to ensure access to lisp data is
3417 thread-safe. The following code is safe because the modifier
3418 variable values are updated atomically from lisp and symbols are
3419 not relocated by GC. Also, we don't have to worry about seeing GC
3420 markbits here. */
3421 if (EQ (key_mapping, Qhyper))
3422 return hyper_modifier;
3423 if (EQ (key_mapping, Qsuper))
3424 return super_modifier;
3425 if (EQ (key_mapping, Qmeta))
3426 return meta_modifier;
3427 if (EQ (key_mapping, Qalt))
3428 return alt_modifier;
3429 if (EQ (key_mapping, Qctrl))
3430 return ctrl_modifier;
3431 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3432 return ctrl_modifier;
3433 if (EQ (key_mapping, Qshift))
3434 return shift_modifier;
3436 /* Don't generate any modifier if not explicitly requested. */
3437 return 0;
3440 unsigned int
3441 w32_get_modifiers ()
3443 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3444 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3445 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3446 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3447 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3448 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3449 (modifier_set (VK_MENU) ?
3450 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3453 /* We map the VK_* modifiers into console modifier constants
3454 so that we can use the same routines to handle both console
3455 and window input. */
3457 static int
3458 construct_console_modifiers ()
3460 int mods;
3462 mods = 0;
3463 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3464 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3465 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3466 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3467 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3468 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3469 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3470 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3471 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3472 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3473 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3475 return mods;
3478 static int
3479 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3481 int mods;
3483 /* Convert to emacs modifiers. */
3484 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3486 return mods;
3489 unsigned int
3490 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3492 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3493 return virt_key;
3495 if (virt_key == VK_RETURN)
3496 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3498 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3499 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3501 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3502 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3504 if (virt_key == VK_CLEAR)
3505 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3507 return virt_key;
3510 /* List of special key combinations which w32 would normally capture,
3511 but emacs should grab instead. Not directly visible to lisp, to
3512 simplify synchronization. Each item is an integer encoding a virtual
3513 key code and modifier combination to capture. */
3514 Lisp_Object w32_grabbed_keys;
3516 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
3517 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3518 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3519 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3521 /* Register hot-keys for reserved key combinations when Emacs has
3522 keyboard focus, since this is the only way Emacs can receive key
3523 combinations like Alt-Tab which are used by the system. */
3525 static void
3526 register_hot_keys (hwnd)
3527 HWND hwnd;
3529 Lisp_Object keylist;
3531 /* Use GC_CONSP, since we are called asynchronously. */
3532 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3534 Lisp_Object key = XCAR (keylist);
3536 /* Deleted entries get set to nil. */
3537 if (!INTEGERP (key))
3538 continue;
3540 RegisterHotKey (hwnd, HOTKEY_ID (key),
3541 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3545 static void
3546 unregister_hot_keys (hwnd)
3547 HWND hwnd;
3549 Lisp_Object keylist;
3551 /* Use GC_CONSP, since we are called asynchronously. */
3552 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
3554 Lisp_Object key = XCAR (keylist);
3556 if (!INTEGERP (key))
3557 continue;
3559 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3563 /* Main message dispatch loop. */
3565 static void
3566 w32_msg_pump (deferred_msg * msg_buf)
3568 MSG msg;
3569 int result;
3570 HWND focus_window;
3572 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3574 while (GetMessage (&msg, NULL, 0, 0))
3576 if (msg.hwnd == NULL)
3578 switch (msg.message)
3580 case WM_NULL:
3581 /* Produced by complete_deferred_msg; just ignore. */
3582 break;
3583 case WM_EMACS_CREATEWINDOW:
3584 w32_createwindow ((struct frame *) msg.wParam);
3585 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3586 abort ();
3587 break;
3588 case WM_EMACS_SETLOCALE:
3589 SetThreadLocale (msg.wParam);
3590 /* Reply is not expected. */
3591 break;
3592 case WM_EMACS_SETKEYBOARDLAYOUT:
3593 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3594 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3595 result, 0))
3596 abort ();
3597 break;
3598 case WM_EMACS_REGISTER_HOT_KEY:
3599 focus_window = GetFocus ();
3600 if (focus_window != NULL)
3601 RegisterHotKey (focus_window,
3602 HOTKEY_ID (msg.wParam),
3603 HOTKEY_MODIFIERS (msg.wParam),
3604 HOTKEY_VK_CODE (msg.wParam));
3605 /* Reply is not expected. */
3606 break;
3607 case WM_EMACS_UNREGISTER_HOT_KEY:
3608 focus_window = GetFocus ();
3609 if (focus_window != NULL)
3610 UnregisterHotKey (focus_window, HOTKEY_ID (msg.wParam));
3611 /* Mark item as erased. NB: this code must be
3612 thread-safe. The next line is okay because the cons
3613 cell is never made into garbage and is not relocated by
3614 GC. */
3615 XCAR ((Lisp_Object) msg.lParam) = Qnil;
3616 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3617 abort ();
3618 break;
3619 case WM_EMACS_TOGGLE_LOCK_KEY:
3621 int vk_code = (int) msg.wParam;
3622 int cur_state = (GetKeyState (vk_code) & 1);
3623 Lisp_Object new_state = (Lisp_Object) msg.lParam;
3625 /* NB: This code must be thread-safe. It is safe to
3626 call NILP because symbols are not relocated by GC,
3627 and pointer here is not touched by GC (so the markbit
3628 can't be set). Numbers are safe because they are
3629 immediate values. */
3630 if (NILP (new_state)
3631 || (NUMBERP (new_state)
3632 && (XUINT (new_state)) & 1 != cur_state))
3634 one_w32_display_info.faked_key = vk_code;
3636 keybd_event ((BYTE) vk_code,
3637 (BYTE) MapVirtualKey (vk_code, 0),
3638 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3639 keybd_event ((BYTE) vk_code,
3640 (BYTE) MapVirtualKey (vk_code, 0),
3641 KEYEVENTF_EXTENDEDKEY | 0, 0);
3642 keybd_event ((BYTE) vk_code,
3643 (BYTE) MapVirtualKey (vk_code, 0),
3644 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3645 cur_state = !cur_state;
3647 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3648 cur_state, 0))
3649 abort ();
3651 break;
3652 default:
3653 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3656 else
3658 DispatchMessage (&msg);
3661 /* Exit nested loop when our deferred message has completed. */
3662 if (msg_buf->completed)
3663 break;
3667 deferred_msg * deferred_msg_head;
3669 static deferred_msg *
3670 find_deferred_msg (HWND hwnd, UINT msg)
3672 deferred_msg * item;
3674 /* Don't actually need synchronization for read access, since
3675 modification of single pointer is always atomic. */
3676 /* enter_crit (); */
3678 for (item = deferred_msg_head; item != NULL; item = item->next)
3679 if (item->w32msg.msg.hwnd == hwnd
3680 && item->w32msg.msg.message == msg)
3681 break;
3683 /* leave_crit (); */
3685 return item;
3688 static LRESULT
3689 send_deferred_msg (deferred_msg * msg_buf,
3690 HWND hwnd,
3691 UINT msg,
3692 WPARAM wParam,
3693 LPARAM lParam)
3695 /* Only input thread can send deferred messages. */
3696 if (GetCurrentThreadId () != dwWindowsThreadId)
3697 abort ();
3699 /* It is an error to send a message that is already deferred. */
3700 if (find_deferred_msg (hwnd, msg) != NULL)
3701 abort ();
3703 /* Enforced synchronization is not needed because this is the only
3704 function that alters deferred_msg_head, and the following critical
3705 section is guaranteed to only be serially reentered (since only the
3706 input thread can call us). */
3708 /* enter_crit (); */
3710 msg_buf->completed = 0;
3711 msg_buf->next = deferred_msg_head;
3712 deferred_msg_head = msg_buf;
3713 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3715 /* leave_crit (); */
3717 /* Start a new nested message loop to process other messages until
3718 this one is completed. */
3719 w32_msg_pump (msg_buf);
3721 deferred_msg_head = msg_buf->next;
3723 return msg_buf->result;
3726 void
3727 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3729 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3731 if (msg_buf == NULL)
3732 /* Message may have been cancelled, so don't abort(). */
3733 return;
3735 msg_buf->result = result;
3736 msg_buf->completed = 1;
3738 /* Ensure input thread is woken so it notices the completion. */
3739 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3742 void
3743 cancel_all_deferred_msgs ()
3745 deferred_msg * item;
3747 /* Don't actually need synchronization for read access, since
3748 modification of single pointer is always atomic. */
3749 /* enter_crit (); */
3751 for (item = deferred_msg_head; item != NULL; item = item->next)
3753 item->result = 0;
3754 item->completed = 1;
3757 /* leave_crit (); */
3759 /* Ensure input thread is woken so it notices the completion. */
3760 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3763 DWORD
3764 w32_msg_worker (dw)
3765 DWORD dw;
3767 MSG msg;
3768 deferred_msg dummy_buf;
3770 /* Ensure our message queue is created */
3772 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3774 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3775 abort ();
3777 memset (&dummy_buf, 0, sizeof (dummy_buf));
3778 dummy_buf.w32msg.msg.hwnd = NULL;
3779 dummy_buf.w32msg.msg.message = WM_NULL;
3781 /* This is the inital message loop which should only exit when the
3782 application quits. */
3783 w32_msg_pump (&dummy_buf);
3785 return 0;
3788 static void
3789 post_character_message (hwnd, msg, wParam, lParam, modifiers)
3790 HWND hwnd;
3791 UINT msg;
3792 WPARAM wParam;
3793 LPARAM lParam;
3794 DWORD modifiers;
3797 W32Msg wmsg;
3799 wmsg.dwModifiers = modifiers;
3801 /* Detect quit_char and set quit-flag directly. Note that we
3802 still need to post a message to ensure the main thread will be
3803 woken up if blocked in sys_select(), but we do NOT want to post
3804 the quit_char message itself (because it will usually be as if
3805 the user had typed quit_char twice). Instead, we post a dummy
3806 message that has no particular effect. */
3808 int c = wParam;
3809 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
3810 c = make_ctrl_char (c) & 0377;
3811 if (c == quit_char
3812 || (wmsg.dwModifiers == 0 &&
3813 XFASTINT (Vw32_quit_key) && wParam == XFASTINT (Vw32_quit_key)))
3815 Vquit_flag = Qt;
3817 /* The choice of message is somewhat arbitrary, as long as
3818 the main thread handler just ignores it. */
3819 msg = WM_NULL;
3821 /* Interrupt any blocking system calls. */
3822 signal_quit ();
3824 /* As a safety precaution, forcibly complete any deferred
3825 messages. This is a kludge, but I don't see any particularly
3826 clean way to handle the situation where a deferred message is
3827 "dropped" in the lisp thread, and will thus never be
3828 completed, eg. by the user trying to activate the menubar
3829 when the lisp thread is busy, and then typing C-g when the
3830 menubar doesn't open promptly (with the result that the
3831 menubar never responds at all because the deferred
3832 WM_INITMENU message is never completed). Another problem
3833 situation is when the lisp thread calls SendMessage (to send
3834 a window manager command) when a message has been deferred;
3835 the lisp thread gets blocked indefinitely waiting for the
3836 deferred message to be completed, which itself is waiting for
3837 the lisp thread to respond.
3839 Note that we don't want to block the input thread waiting for
3840 a reponse from the lisp thread (although that would at least
3841 solve the deadlock problem above), because we want to be able
3842 to receive C-g to interrupt the lisp thread. */
3843 cancel_all_deferred_msgs ();
3847 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3850 /* Main window procedure */
3852 LRESULT CALLBACK
3853 w32_wnd_proc (hwnd, msg, wParam, lParam)
3854 HWND hwnd;
3855 UINT msg;
3856 WPARAM wParam;
3857 LPARAM lParam;
3859 struct frame *f;
3860 struct w32_display_info *dpyinfo = &one_w32_display_info;
3861 W32Msg wmsg;
3862 int windows_translate;
3863 int key;
3865 /* Note that it is okay to call x_window_to_frame, even though we are
3866 not running in the main lisp thread, because frame deletion
3867 requires the lisp thread to synchronize with this thread. Thus, if
3868 a frame struct is returned, it can be used without concern that the
3869 lisp thread might make it disappear while we are using it.
3871 NB. Walking the frame list in this thread is safe (as long as
3872 writes of Lisp_Object slots are atomic, which they are on Windows).
3873 Although delete-frame can destructively modify the frame list while
3874 we are walking it, a garbage collection cannot occur until after
3875 delete-frame has synchronized with this thread.
3877 It is also safe to use functions that make GDI calls, such as
3878 w32_clear_rect, because these functions must obtain a DC handle
3879 from the frame struct using get_frame_dc which is thread-aware. */
3881 switch (msg)
3883 case WM_ERASEBKGND:
3884 f = x_window_to_frame (dpyinfo, hwnd);
3885 if (f)
3887 HDC hdc = get_frame_dc (f);
3888 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
3889 w32_clear_rect (f, hdc, &wmsg.rect);
3890 release_frame_dc (f, hdc);
3892 #if defined (W32_DEBUG_DISPLAY)
3893 DebPrint (("WM_ERASEBKGND: erasing %d,%d-%d,%d\n",
3894 wmsg.rect.left, wmsg.rect.top, wmsg.rect.right,
3895 wmsg.rect.bottom));
3896 #endif /* W32_DEBUG_DISPLAY */
3898 return 1;
3899 case WM_PALETTECHANGED:
3900 /* ignore our own changes */
3901 if ((HWND)wParam != hwnd)
3903 f = x_window_to_frame (dpyinfo, hwnd);
3904 if (f)
3905 /* get_frame_dc will realize our palette and force all
3906 frames to be redrawn if needed. */
3907 release_frame_dc (f, get_frame_dc (f));
3909 return 0;
3910 case WM_PAINT:
3912 PAINTSTRUCT paintStruct;
3913 RECT update_rect;
3915 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
3916 fails. Apparently this can happen under some
3917 circumstances. */
3918 if (!w32_strict_painting || GetUpdateRect (hwnd, &update_rect, FALSE))
3920 enter_crit ();
3921 BeginPaint (hwnd, &paintStruct);
3923 if (w32_strict_painting)
3924 /* The rectangles returned by GetUpdateRect and BeginPaint
3925 do not always match. GetUpdateRect seems to be the
3926 more reliable of the two. */
3927 wmsg.rect = update_rect;
3928 else
3929 wmsg.rect = paintStruct.rcPaint;
3931 #if defined (W32_DEBUG_DISPLAY)
3932 DebPrint (("WM_PAINT: painting %d,%d-%d,%d\n", wmsg.rect.left,
3933 wmsg.rect.top, wmsg.rect.right, wmsg.rect.bottom));
3934 DebPrint (("WM_PAINT: update region is %d,%d-%d,%d\n",
3935 update_rect.left, update_rect.top,
3936 update_rect.right, update_rect.bottom));
3937 #endif
3938 EndPaint (hwnd, &paintStruct);
3939 leave_crit ();
3941 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3943 return 0;
3946 /* If GetUpdateRect returns 0 (meaning there is no update
3947 region), assume the whole window needs to be repainted. */
3948 GetClientRect(hwnd, &wmsg.rect);
3949 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3950 return 0;
3953 case WM_INPUTLANGCHANGE:
3954 /* Inform lisp thread of keyboard layout changes. */
3955 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3957 /* Clear dead keys in the keyboard state; for simplicity only
3958 preserve modifier key states. */
3960 int i;
3961 BYTE keystate[256];
3963 GetKeyboardState (keystate);
3964 for (i = 0; i < 256; i++)
3965 if (1
3966 && i != VK_SHIFT
3967 && i != VK_LSHIFT
3968 && i != VK_RSHIFT
3969 && i != VK_CAPITAL
3970 && i != VK_NUMLOCK
3971 && i != VK_SCROLL
3972 && i != VK_CONTROL
3973 && i != VK_LCONTROL
3974 && i != VK_RCONTROL
3975 && i != VK_MENU
3976 && i != VK_LMENU
3977 && i != VK_RMENU
3978 && i != VK_LWIN
3979 && i != VK_RWIN)
3980 keystate[i] = 0;
3981 SetKeyboardState (keystate);
3983 goto dflt;
3985 case WM_HOTKEY:
3986 /* Synchronize hot keys with normal input. */
3987 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3988 return (0);
3990 case WM_KEYUP:
3991 case WM_SYSKEYUP:
3992 record_keyup (wParam, lParam);
3993 goto dflt;
3995 case WM_KEYDOWN:
3996 case WM_SYSKEYDOWN:
3997 /* Ignore keystrokes we fake ourself; see below. */
3998 if (dpyinfo->faked_key == wParam)
4000 dpyinfo->faked_key = 0;
4001 /* Make sure TranslateMessage sees them though (as long as
4002 they don't produce WM_CHAR messages). This ensures that
4003 indicator lights are toggled promptly on Windows 9x, for
4004 example. */
4005 if (lispy_function_keys[wParam] != 0)
4007 windows_translate = 1;
4008 goto translate;
4010 return 0;
4013 /* Synchronize modifiers with current keystroke. */
4014 sync_modifiers ();
4015 record_keydown (wParam, lParam);
4016 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4018 windows_translate = 0;
4020 switch (wParam)
4022 case VK_LWIN:
4023 if (NILP (Vw32_pass_lwindow_to_system))
4025 /* Prevent system from acting on keyup (which opens the
4026 Start menu if no other key was pressed) by simulating a
4027 press of Space which we will ignore. */
4028 if (GetAsyncKeyState (wParam) & 1)
4030 if (NUMBERP (Vw32_phantom_key_code))
4031 key = XUINT (Vw32_phantom_key_code) & 255;
4032 else
4033 key = VK_SPACE;
4034 dpyinfo->faked_key = key;
4035 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4038 if (!NILP (Vw32_lwindow_modifier))
4039 return 0;
4040 break;
4041 case VK_RWIN:
4042 if (NILP (Vw32_pass_rwindow_to_system))
4044 if (GetAsyncKeyState (wParam) & 1)
4046 if (NUMBERP (Vw32_phantom_key_code))
4047 key = XUINT (Vw32_phantom_key_code) & 255;
4048 else
4049 key = VK_SPACE;
4050 dpyinfo->faked_key = key;
4051 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4054 if (!NILP (Vw32_rwindow_modifier))
4055 return 0;
4056 break;
4057 case VK_APPS:
4058 if (!NILP (Vw32_apps_modifier))
4059 return 0;
4060 break;
4061 case VK_MENU:
4062 if (NILP (Vw32_pass_alt_to_system))
4063 /* Prevent DefWindowProc from activating the menu bar if an
4064 Alt key is pressed and released by itself. */
4065 return 0;
4066 windows_translate = 1;
4067 break;
4068 case VK_CAPITAL:
4069 /* Decide whether to treat as modifier or function key. */
4070 if (NILP (Vw32_enable_caps_lock))
4071 goto disable_lock_key;
4072 windows_translate = 1;
4073 break;
4074 case VK_NUMLOCK:
4075 /* Decide whether to treat as modifier or function key. */
4076 if (NILP (Vw32_enable_num_lock))
4077 goto disable_lock_key;
4078 windows_translate = 1;
4079 break;
4080 case VK_SCROLL:
4081 /* Decide whether to treat as modifier or function key. */
4082 if (NILP (Vw32_scroll_lock_modifier))
4083 goto disable_lock_key;
4084 windows_translate = 1;
4085 break;
4086 disable_lock_key:
4087 /* Ensure the appropriate lock key state (and indicator light)
4088 remains in the same state. We do this by faking another
4089 press of the relevant key. Apparently, this really is the
4090 only way to toggle the state of the indicator lights. */
4091 dpyinfo->faked_key = wParam;
4092 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4093 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4094 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4095 KEYEVENTF_EXTENDEDKEY | 0, 0);
4096 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4097 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4098 /* Ensure indicator lights are updated promptly on Windows 9x
4099 (TranslateMessage apparently does this), after forwarding
4100 input event. */
4101 post_character_message (hwnd, msg, wParam, lParam,
4102 w32_get_key_modifiers (wParam, lParam));
4103 windows_translate = 1;
4104 break;
4105 case VK_CONTROL:
4106 case VK_SHIFT:
4107 case VK_PROCESSKEY: /* Generated by IME. */
4108 windows_translate = 1;
4109 break;
4110 case VK_CANCEL:
4111 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4112 which is confusing for purposes of key binding; convert
4113 VK_CANCEL events into VK_PAUSE events. */
4114 wParam = VK_PAUSE;
4115 break;
4116 case VK_PAUSE:
4117 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4118 for purposes of key binding; convert these back into
4119 VK_NUMLOCK events, at least when we want to see NumLock key
4120 presses. (Note that there is never any possibility that
4121 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4122 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4123 wParam = VK_NUMLOCK;
4124 break;
4125 default:
4126 /* If not defined as a function key, change it to a WM_CHAR message. */
4127 if (lispy_function_keys[wParam] == 0)
4129 DWORD modifiers = construct_console_modifiers ();
4131 if (!NILP (Vw32_recognize_altgr)
4132 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4134 /* Always let TranslateMessage handle AltGr key chords;
4135 for some reason, ToAscii doesn't always process AltGr
4136 chords correctly. */
4137 windows_translate = 1;
4139 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4141 /* Handle key chords including any modifiers other
4142 than shift directly, in order to preserve as much
4143 modifier information as possible. */
4144 if ('A' <= wParam && wParam <= 'Z')
4146 /* Don't translate modified alphabetic keystrokes,
4147 so the user doesn't need to constantly switch
4148 layout to type control or meta keystrokes when
4149 the normal layout translates alphabetic
4150 characters to non-ascii characters. */
4151 if (!modifier_set (VK_SHIFT))
4152 wParam += ('a' - 'A');
4153 msg = WM_CHAR;
4155 else
4157 /* Try to handle other keystrokes by determining the
4158 base character (ie. translating the base key plus
4159 shift modifier). */
4160 int add;
4161 int isdead = 0;
4162 KEY_EVENT_RECORD key;
4164 key.bKeyDown = TRUE;
4165 key.wRepeatCount = 1;
4166 key.wVirtualKeyCode = wParam;
4167 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4168 key.uChar.AsciiChar = 0;
4169 key.dwControlKeyState = modifiers;
4171 add = w32_kbd_patch_key (&key);
4172 /* 0 means an unrecognised keycode, negative means
4173 dead key. Ignore both. */
4174 while (--add >= 0)
4176 /* Forward asciified character sequence. */
4177 post_character_message
4178 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
4179 w32_get_key_modifiers (wParam, lParam));
4180 w32_kbd_patch_key (&key);
4182 return 0;
4185 else
4187 /* Let TranslateMessage handle everything else. */
4188 windows_translate = 1;
4193 translate:
4194 if (windows_translate)
4196 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4198 windows_msg.time = GetMessageTime ();
4199 TranslateMessage (&windows_msg);
4200 goto dflt;
4203 /* Fall through */
4205 case WM_SYSCHAR:
4206 case WM_CHAR:
4207 post_character_message (hwnd, msg, wParam, lParam,
4208 w32_get_key_modifiers (wParam, lParam));
4209 break;
4211 /* Simulate middle mouse button events when left and right buttons
4212 are used together, but only if user has two button mouse. */
4213 case WM_LBUTTONDOWN:
4214 case WM_RBUTTONDOWN:
4215 if (XINT (Vw32_num_mouse_buttons) == 3)
4216 goto handle_plain_button;
4219 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4220 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4222 if (button_state & this)
4223 return 0;
4225 if (button_state == 0)
4226 SetCapture (hwnd);
4228 button_state |= this;
4230 if (button_state & other)
4232 if (mouse_button_timer)
4234 KillTimer (hwnd, mouse_button_timer);
4235 mouse_button_timer = 0;
4237 /* Generate middle mouse event instead. */
4238 msg = WM_MBUTTONDOWN;
4239 button_state |= MMOUSE;
4241 else if (button_state & MMOUSE)
4243 /* Ignore button event if we've already generated a
4244 middle mouse down event. This happens if the
4245 user releases and press one of the two buttons
4246 after we've faked a middle mouse event. */
4247 return 0;
4249 else
4251 /* Flush out saved message. */
4252 post_msg (&saved_mouse_button_msg);
4254 wmsg.dwModifiers = w32_get_modifiers ();
4255 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4257 /* Clear message buffer. */
4258 saved_mouse_button_msg.msg.hwnd = 0;
4260 else
4262 /* Hold onto message for now. */
4263 mouse_button_timer =
4264 SetTimer (hwnd, MOUSE_BUTTON_ID,
4265 XINT (Vw32_mouse_button_tolerance), NULL);
4266 saved_mouse_button_msg.msg.hwnd = hwnd;
4267 saved_mouse_button_msg.msg.message = msg;
4268 saved_mouse_button_msg.msg.wParam = wParam;
4269 saved_mouse_button_msg.msg.lParam = lParam;
4270 saved_mouse_button_msg.msg.time = GetMessageTime ();
4271 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4274 return 0;
4276 case WM_LBUTTONUP:
4277 case WM_RBUTTONUP:
4278 if (XINT (Vw32_num_mouse_buttons) == 3)
4279 goto handle_plain_button;
4282 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4283 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4285 if ((button_state & this) == 0)
4286 return 0;
4288 button_state &= ~this;
4290 if (button_state & MMOUSE)
4292 /* Only generate event when second button is released. */
4293 if ((button_state & other) == 0)
4295 msg = WM_MBUTTONUP;
4296 button_state &= ~MMOUSE;
4298 if (button_state) abort ();
4300 else
4301 return 0;
4303 else
4305 /* Flush out saved message if necessary. */
4306 if (saved_mouse_button_msg.msg.hwnd)
4308 post_msg (&saved_mouse_button_msg);
4311 wmsg.dwModifiers = w32_get_modifiers ();
4312 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4314 /* Always clear message buffer and cancel timer. */
4315 saved_mouse_button_msg.msg.hwnd = 0;
4316 KillTimer (hwnd, mouse_button_timer);
4317 mouse_button_timer = 0;
4319 if (button_state == 0)
4320 ReleaseCapture ();
4322 return 0;
4324 case WM_MBUTTONDOWN:
4325 case WM_MBUTTONUP:
4326 handle_plain_button:
4328 BOOL up;
4329 int button;
4331 if (parse_button (msg, &button, &up))
4333 if (up) ReleaseCapture ();
4334 else SetCapture (hwnd);
4335 button = (button == 0) ? LMOUSE :
4336 ((button == 1) ? MMOUSE : RMOUSE);
4337 if (up)
4338 button_state &= ~button;
4339 else
4340 button_state |= button;
4344 wmsg.dwModifiers = w32_get_modifiers ();
4345 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4346 return 0;
4348 case WM_VSCROLL:
4349 case WM_MOUSEMOVE:
4350 if (XINT (Vw32_mouse_move_interval) <= 0
4351 || (msg == WM_MOUSEMOVE && button_state == 0))
4353 wmsg.dwModifiers = w32_get_modifiers ();
4354 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4355 return 0;
4358 /* Hang onto mouse move and scroll messages for a bit, to avoid
4359 sending such events to Emacs faster than it can process them.
4360 If we get more events before the timer from the first message
4361 expires, we just replace the first message. */
4363 if (saved_mouse_move_msg.msg.hwnd == 0)
4364 mouse_move_timer =
4365 SetTimer (hwnd, MOUSE_MOVE_ID,
4366 XINT (Vw32_mouse_move_interval), NULL);
4368 /* Hold onto message for now. */
4369 saved_mouse_move_msg.msg.hwnd = hwnd;
4370 saved_mouse_move_msg.msg.message = msg;
4371 saved_mouse_move_msg.msg.wParam = wParam;
4372 saved_mouse_move_msg.msg.lParam = lParam;
4373 saved_mouse_move_msg.msg.time = GetMessageTime ();
4374 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4376 return 0;
4378 case WM_MOUSEWHEEL:
4379 wmsg.dwModifiers = w32_get_modifiers ();
4380 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4381 return 0;
4383 case WM_DROPFILES:
4384 wmsg.dwModifiers = w32_get_modifiers ();
4385 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4386 return 0;
4388 case WM_TIMER:
4389 /* Flush out saved messages if necessary. */
4390 if (wParam == mouse_button_timer)
4392 if (saved_mouse_button_msg.msg.hwnd)
4394 post_msg (&saved_mouse_button_msg);
4395 saved_mouse_button_msg.msg.hwnd = 0;
4397 KillTimer (hwnd, mouse_button_timer);
4398 mouse_button_timer = 0;
4400 else if (wParam == mouse_move_timer)
4402 if (saved_mouse_move_msg.msg.hwnd)
4404 post_msg (&saved_mouse_move_msg);
4405 saved_mouse_move_msg.msg.hwnd = 0;
4407 KillTimer (hwnd, mouse_move_timer);
4408 mouse_move_timer = 0;
4410 return 0;
4412 case WM_NCACTIVATE:
4413 /* Windows doesn't send us focus messages when putting up and
4414 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4415 The only indication we get that something happened is receiving
4416 this message afterwards. So this is a good time to reset our
4417 keyboard modifiers' state. */
4418 reset_modifiers ();
4419 goto dflt;
4421 case WM_INITMENU:
4422 button_state = 0;
4423 ReleaseCapture ();
4424 /* We must ensure menu bar is fully constructed and up to date
4425 before allowing user interaction with it. To achieve this
4426 we send this message to the lisp thread and wait for a
4427 reply (whose value is not actually needed) to indicate that
4428 the menu bar is now ready for use, so we can now return.
4430 To remain responsive in the meantime, we enter a nested message
4431 loop that can process all other messages.
4433 However, we skip all this if the message results from calling
4434 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4435 thread a message because it is blocked on us at this point. We
4436 set menubar_active before calling TrackPopupMenu to indicate
4437 this (there is no possibility of confusion with real menubar
4438 being active). */
4440 f = x_window_to_frame (dpyinfo, hwnd);
4441 if (f
4442 && (f->output_data.w32->menubar_active
4443 /* We can receive this message even in the absence of a
4444 menubar (ie. when the system menu is activated) - in this
4445 case we do NOT want to forward the message, otherwise it
4446 will cause the menubar to suddenly appear when the user
4447 had requested it to be turned off! */
4448 || f->output_data.w32->menubar_widget == NULL))
4449 return 0;
4452 deferred_msg msg_buf;
4454 /* Detect if message has already been deferred; in this case
4455 we cannot return any sensible value to ignore this. */
4456 if (find_deferred_msg (hwnd, msg) != NULL)
4457 abort ();
4459 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4462 case WM_EXITMENULOOP:
4463 f = x_window_to_frame (dpyinfo, hwnd);
4465 /* Indicate that menubar can be modified again. */
4466 if (f)
4467 f->output_data.w32->menubar_active = 0;
4468 goto dflt;
4470 case WM_MEASUREITEM:
4471 f = x_window_to_frame (dpyinfo, hwnd);
4472 if (f)
4474 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4476 if (pMis->CtlType == ODT_MENU)
4478 /* Work out dimensions for popup menu titles. */
4479 char * title = (char *) pMis->itemData;
4480 HDC hdc = GetDC (hwnd);
4481 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4482 LOGFONT menu_logfont;
4483 HFONT old_font;
4484 SIZE size;
4486 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4487 menu_logfont.lfWeight = FW_BOLD;
4488 menu_font = CreateFontIndirect (&menu_logfont);
4489 old_font = SelectObject (hdc, menu_font);
4491 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4492 pMis->itemWidth = size.cx;
4493 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4494 if (pMis->itemHeight < size.cy)
4495 pMis->itemHeight = size.cy;
4497 SelectObject (hdc, old_font);
4498 DeleteObject (menu_font);
4499 ReleaseDC (hwnd, hdc);
4500 return TRUE;
4503 return 0;
4505 case WM_DRAWITEM:
4506 f = x_window_to_frame (dpyinfo, hwnd);
4507 if (f)
4509 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4511 if (pDis->CtlType == ODT_MENU)
4513 /* Draw popup menu title. */
4514 char * title = (char *) pDis->itemData;
4515 HDC hdc = pDis->hDC;
4516 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4517 LOGFONT menu_logfont;
4518 HFONT old_font;
4520 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4521 menu_logfont.lfWeight = FW_BOLD;
4522 menu_font = CreateFontIndirect (&menu_logfont);
4523 old_font = SelectObject (hdc, menu_font);
4525 /* Always draw title as if not selected. */
4526 ExtTextOut (hdc,
4527 pDis->rcItem.left + GetSystemMetrics (SM_CXMENUCHECK),
4528 pDis->rcItem.top,
4529 ETO_OPAQUE, &pDis->rcItem,
4530 title, strlen (title), NULL);
4532 SelectObject (hdc, old_font);
4533 DeleteObject (menu_font);
4534 return TRUE;
4537 return 0;
4539 #if 0
4540 /* Still not right - can't distinguish between clicks in the
4541 client area of the frame from clicks forwarded from the scroll
4542 bars - may have to hook WM_NCHITTEST to remember the mouse
4543 position and then check if it is in the client area ourselves. */
4544 case WM_MOUSEACTIVATE:
4545 /* Discard the mouse click that activates a frame, allowing the
4546 user to click anywhere without changing point (or worse!).
4547 Don't eat mouse clicks on scrollbars though!! */
4548 if (LOWORD (lParam) == HTCLIENT )
4549 return MA_ACTIVATEANDEAT;
4550 goto dflt;
4551 #endif
4553 case WM_ACTIVATEAPP:
4554 case WM_ACTIVATE:
4555 case WM_WINDOWPOSCHANGED:
4556 case WM_SHOWWINDOW:
4557 /* Inform lisp thread that a frame might have just been obscured
4558 or exposed, so should recheck visibility of all frames. */
4559 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4560 goto dflt;
4562 case WM_SETFOCUS:
4563 dpyinfo->faked_key = 0;
4564 reset_modifiers ();
4565 register_hot_keys (hwnd);
4566 goto command;
4567 case WM_KILLFOCUS:
4568 unregister_hot_keys (hwnd);
4569 button_state = 0;
4570 ReleaseCapture ();
4571 case WM_MOVE:
4572 case WM_SIZE:
4573 case WM_COMMAND:
4574 command:
4575 wmsg.dwModifiers = w32_get_modifiers ();
4576 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4577 goto dflt;
4579 case WM_CLOSE:
4580 wmsg.dwModifiers = w32_get_modifiers ();
4581 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4582 return 0;
4584 case WM_WINDOWPOSCHANGING:
4586 WINDOWPLACEMENT wp;
4587 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4589 wp.length = sizeof (WINDOWPLACEMENT);
4590 GetWindowPlacement (hwnd, &wp);
4592 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
4594 RECT rect;
4595 int wdiff;
4596 int hdiff;
4597 DWORD font_width;
4598 DWORD line_height;
4599 DWORD internal_border;
4600 DWORD scrollbar_extra;
4601 RECT wr;
4603 wp.length = sizeof(wp);
4604 GetWindowRect (hwnd, &wr);
4606 enter_crit ();
4608 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4609 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4610 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4611 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
4613 leave_crit ();
4615 memset (&rect, 0, sizeof (rect));
4616 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4617 GetMenu (hwnd) != NULL);
4619 /* Force width and height of client area to be exact
4620 multiples of the character cell dimensions. */
4621 wdiff = (lppos->cx - (rect.right - rect.left)
4622 - 2 * internal_border - scrollbar_extra)
4623 % font_width;
4624 hdiff = (lppos->cy - (rect.bottom - rect.top)
4625 - 2 * internal_border)
4626 % line_height;
4628 if (wdiff || hdiff)
4630 /* For right/bottom sizing we can just fix the sizes.
4631 However for top/left sizing we will need to fix the X
4632 and Y positions as well. */
4634 lppos->cx -= wdiff;
4635 lppos->cy -= hdiff;
4637 if (wp.showCmd != SW_SHOWMAXIMIZED
4638 && (lppos->flags & SWP_NOMOVE) == 0)
4640 if (lppos->x != wr.left || lppos->y != wr.top)
4642 lppos->x += wdiff;
4643 lppos->y += hdiff;
4645 else
4647 lppos->flags |= SWP_NOMOVE;
4651 return 0;
4656 goto dflt;
4658 case WM_GETMINMAXINFO:
4659 /* Hack to correct bug that allows Emacs frames to be resized
4660 below the Minimum Tracking Size. */
4661 ((LPMINMAXINFO) lParam)->ptMinTrackSize.y++;
4662 return 0;
4664 case WM_EMACS_CREATESCROLLBAR:
4665 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
4666 (struct scroll_bar *) lParam);
4668 case WM_EMACS_SHOWWINDOW:
4669 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4671 case WM_EMACS_SETFOREGROUND:
4673 HWND foreground_window;
4674 DWORD foreground_thread, retval;
4676 /* On NT 5.0, and apparently Windows 98, it is necessary to
4677 attach to the thread that currently has focus in order to
4678 pull the focus away from it. */
4679 foreground_window = GetForegroundWindow ();
4680 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4681 if (!foreground_window
4682 || foreground_thread == GetCurrentThreadId ()
4683 || !AttachThreadInput (GetCurrentThreadId (),
4684 foreground_thread, TRUE))
4685 foreground_thread = 0;
4687 retval = SetForegroundWindow ((HWND) wParam);
4689 /* Detach from the previous foreground thread. */
4690 if (foreground_thread)
4691 AttachThreadInput (GetCurrentThreadId (),
4692 foreground_thread, FALSE);
4694 return retval;
4697 case WM_EMACS_SETWINDOWPOS:
4699 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4700 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4701 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4704 case WM_EMACS_DESTROYWINDOW:
4705 DragAcceptFiles ((HWND) wParam, FALSE);
4706 return DestroyWindow ((HWND) wParam);
4708 case WM_EMACS_TRACKPOPUPMENU:
4710 UINT flags;
4711 POINT *pos;
4712 int retval;
4713 pos = (POINT *)lParam;
4714 flags = TPM_CENTERALIGN;
4715 if (button_state & LMOUSE)
4716 flags |= TPM_LEFTBUTTON;
4717 else if (button_state & RMOUSE)
4718 flags |= TPM_RIGHTBUTTON;
4720 /* Remember we did a SetCapture on the initial mouse down event,
4721 so for safety, we make sure the capture is cancelled now. */
4722 ReleaseCapture ();
4723 button_state = 0;
4725 /* Use menubar_active to indicate that WM_INITMENU is from
4726 TrackPopupMenu below, and should be ignored. */
4727 f = x_window_to_frame (dpyinfo, hwnd);
4728 if (f)
4729 f->output_data.w32->menubar_active = 1;
4731 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4732 0, hwnd, NULL))
4734 MSG amsg;
4735 /* Eat any mouse messages during popupmenu */
4736 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4737 PM_REMOVE));
4738 /* Get the menu selection, if any */
4739 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4741 retval = LOWORD (amsg.wParam);
4743 else
4745 retval = 0;
4748 else
4750 retval = -1;
4753 return retval;
4756 default:
4757 /* Check for messages registered at runtime. */
4758 if (msg == msh_mousewheel)
4760 wmsg.dwModifiers = w32_get_modifiers ();
4761 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4762 return 0;
4765 dflt:
4766 return DefWindowProc (hwnd, msg, wParam, lParam);
4770 /* The most common default return code for handled messages is 0. */
4771 return 0;
4774 void
4775 my_create_window (f)
4776 struct frame * f;
4778 MSG msg;
4780 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4781 abort ();
4782 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4785 /* Create and set up the w32 window for frame F. */
4787 static void
4788 w32_window (f, window_prompting, minibuffer_only)
4789 struct frame *f;
4790 long window_prompting;
4791 int minibuffer_only;
4793 BLOCK_INPUT;
4795 /* Use the resource name as the top-level window name
4796 for looking up resources. Make a non-Lisp copy
4797 for the window manager, so GC relocation won't bother it.
4799 Elsewhere we specify the window name for the window manager. */
4802 char *str = (char *) XSTRING (Vx_resource_name)->data;
4803 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4804 strcpy (f->namebuf, str);
4807 my_create_window (f);
4809 validate_x_resource_name ();
4811 /* x_set_name normally ignores requests to set the name if the
4812 requested name is the same as the current name. This is the one
4813 place where that assumption isn't correct; f->name is set, but
4814 the server hasn't been told. */
4816 Lisp_Object name;
4817 int explicit = f->explicit_name;
4819 f->explicit_name = 0;
4820 name = f->name;
4821 f->name = Qnil;
4822 x_set_name (f, name, explicit);
4825 UNBLOCK_INPUT;
4827 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4828 initialize_frame_menubar (f);
4830 if (FRAME_W32_WINDOW (f) == 0)
4831 error ("Unable to create window");
4834 /* Handle the icon stuff for this window. Perhaps later we might
4835 want an x_set_icon_position which can be called interactively as
4836 well. */
4838 static void
4839 x_icon (f, parms)
4840 struct frame *f;
4841 Lisp_Object parms;
4843 Lisp_Object icon_x, icon_y;
4845 /* Set the position of the icon. Note that Windows 95 groups all
4846 icons in the tray. */
4847 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4848 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4849 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4851 CHECK_NUMBER (icon_x, 0);
4852 CHECK_NUMBER (icon_y, 0);
4854 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4855 error ("Both left and top icon corners of icon must be specified");
4857 BLOCK_INPUT;
4859 if (! EQ (icon_x, Qunbound))
4860 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4862 #if 0 /* TODO */
4863 /* Start up iconic or window? */
4864 x_wm_set_window_state
4865 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4866 ? IconicState
4867 : NormalState));
4869 x_text_icon (f, (char *) XSTRING ((!NILP (f->icon_name)
4870 ? f->icon_name
4871 : f->name))->data);
4872 #endif
4874 UNBLOCK_INPUT;
4878 static void
4879 x_make_gc (f)
4880 struct frame *f;
4882 XGCValues gc_values;
4884 BLOCK_INPUT;
4886 /* Create the GC's of this frame.
4887 Note that many default values are used. */
4889 /* Normal video */
4890 gc_values.font = f->output_data.w32->font;
4892 /* Cursor has cursor-color background, background-color foreground. */
4893 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4894 gc_values.background = f->output_data.w32->cursor_pixel;
4895 f->output_data.w32->cursor_gc
4896 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4897 (GCFont | GCForeground | GCBackground),
4898 &gc_values);
4900 /* Reliefs. */
4901 f->output_data.w32->white_relief.gc = 0;
4902 f->output_data.w32->black_relief.gc = 0;
4904 UNBLOCK_INPUT;
4908 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4909 1, 1, 0,
4910 "Make a new window, which is called a \"frame\" in Emacs terms.\n\
4911 Returns an Emacs frame object.\n\
4912 ALIST is an alist of frame parameters.\n\
4913 If the parameters specify that the frame should not have a minibuffer,\n\
4914 and do not specify a specific minibuffer window to use,\n\
4915 then `default-minibuffer-frame' must be a frame whose minibuffer can\n\
4916 be shared by the new frame.\n\
4918 This function is an internal primitive--use `make-frame' instead.")
4919 (parms)
4920 Lisp_Object parms;
4922 struct frame *f;
4923 Lisp_Object frame, tem;
4924 Lisp_Object name;
4925 int minibuffer_only = 0;
4926 long window_prompting = 0;
4927 int width, height;
4928 int count = specpdl_ptr - specpdl;
4929 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4930 Lisp_Object display;
4931 struct w32_display_info *dpyinfo = NULL;
4932 Lisp_Object parent;
4933 struct kboard *kb;
4935 check_w32 ();
4937 /* Use this general default value to start with
4938 until we know if this frame has a specified name. */
4939 Vx_resource_name = Vinvocation_name;
4941 display = w32_get_arg (parms, Qdisplay, 0, 0, RES_TYPE_STRING);
4942 if (EQ (display, Qunbound))
4943 display = Qnil;
4944 dpyinfo = check_x_display_info (display);
4945 #ifdef MULTI_KBOARD
4946 kb = dpyinfo->kboard;
4947 #else
4948 kb = &the_only_kboard;
4949 #endif
4951 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
4952 if (!STRINGP (name)
4953 && ! EQ (name, Qunbound)
4954 && ! NILP (name))
4955 error ("Invalid frame name--not a string or nil");
4957 if (STRINGP (name))
4958 Vx_resource_name = name;
4960 /* See if parent window is specified. */
4961 parent = w32_get_arg (parms, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4962 if (EQ (parent, Qunbound))
4963 parent = Qnil;
4964 if (! NILP (parent))
4965 CHECK_NUMBER (parent, 0);
4967 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4968 /* No need to protect DISPLAY because that's not used after passing
4969 it to make_frame_without_minibuffer. */
4970 frame = Qnil;
4971 GCPRO4 (parms, parent, name, frame);
4972 tem = w32_get_arg (parms, Qminibuffer, 0, 0, RES_TYPE_SYMBOL);
4973 if (EQ (tem, Qnone) || NILP (tem))
4974 f = make_frame_without_minibuffer (Qnil, kb, display);
4975 else if (EQ (tem, Qonly))
4977 f = make_minibuffer_frame ();
4978 minibuffer_only = 1;
4980 else if (WINDOWP (tem))
4981 f = make_frame_without_minibuffer (tem, kb, display);
4982 else
4983 f = make_frame (1);
4985 XSETFRAME (frame, f);
4987 /* Note that Windows does support scroll bars. */
4988 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
4989 /* By default, make scrollbars the system standard width. */
4990 f->scroll_bar_pixel_width = GetSystemMetrics (SM_CXVSCROLL);
4992 f->output_method = output_w32;
4993 f->output_data.w32 =
4994 (struct w32_output *) xmalloc (sizeof (struct w32_output));
4995 bzero (f->output_data.w32, sizeof (struct w32_output));
4997 FRAME_FONTSET (f) = -1;
4999 f->icon_name
5000 = w32_get_arg (parms, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
5001 if (! STRINGP (f->icon_name))
5002 f->icon_name = Qnil;
5004 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
5005 #ifdef MULTI_KBOARD
5006 FRAME_KBOARD (f) = kb;
5007 #endif
5009 /* Specify the parent under which to make this window. */
5011 if (!NILP (parent))
5013 f->output_data.w32->parent_desc = (Window) parent;
5014 f->output_data.w32->explicit_parent = 1;
5016 else
5018 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5019 f->output_data.w32->explicit_parent = 0;
5022 /* Set the name; the functions to which we pass f expect the name to
5023 be set. */
5024 if (EQ (name, Qunbound) || NILP (name))
5026 f->name = build_string (dpyinfo->w32_id_name);
5027 f->explicit_name = 0;
5029 else
5031 f->name = name;
5032 f->explicit_name = 1;
5033 /* use the frame's title when getting resources for this frame. */
5034 specbind (Qx_resource_name, name);
5037 /* Create fontsets from `global_fontset_alist' before handling fonts. */
5038 for (tem = Vglobal_fontset_alist; CONSP (tem); tem = XCDR (tem))
5039 fs_register_fontset (f, XCAR (tem));
5041 /* Extract the window parameters from the supplied values
5042 that are needed to determine window geometry. */
5044 Lisp_Object font;
5046 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
5048 BLOCK_INPUT;
5049 /* First, try whatever font the caller has specified. */
5050 if (STRINGP (font))
5052 tem = Fquery_fontset (font, Qnil);
5053 if (STRINGP (tem))
5054 font = x_new_fontset (f, XSTRING (tem)->data);
5055 else
5056 font = x_new_font (f, XSTRING (font)->data);
5058 /* Try out a font which we hope has bold and italic variations. */
5059 if (!STRINGP (font))
5060 font = x_new_font (f, "-*-Courier New-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5061 if (! STRINGP (font))
5062 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
5063 /* If those didn't work, look for something which will at least work. */
5064 if (! STRINGP (font))
5065 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
5066 UNBLOCK_INPUT;
5067 if (! STRINGP (font))
5068 font = build_string ("Fixedsys");
5070 x_default_parameter (f, parms, Qfont, font,
5071 "font", "Font", RES_TYPE_STRING);
5074 x_default_parameter (f, parms, Qborder_width, make_number (2),
5075 "borderwidth", "BorderWidth", RES_TYPE_NUMBER);
5076 /* This defaults to 2 in order to match xterm. We recognize either
5077 internalBorderWidth or internalBorder (which is what xterm calls
5078 it). */
5079 if (NILP (Fassq (Qinternal_border_width, parms)))
5081 Lisp_Object value;
5083 value = w32_get_arg (parms, Qinternal_border_width,
5084 "internalBorder", "BorderWidth", RES_TYPE_NUMBER);
5085 if (! EQ (value, Qunbound))
5086 parms = Fcons (Fcons (Qinternal_border_width, value),
5087 parms);
5089 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5090 x_default_parameter (f, parms, Qinternal_border_width, make_number (0),
5091 "internalBorderWidth", "BorderWidth", RES_TYPE_NUMBER);
5092 x_default_parameter (f, parms, Qvertical_scroll_bars, Qt,
5093 "verticalScrollBars", "ScrollBars", RES_TYPE_BOOLEAN);
5095 /* Also do the stuff which must be set before the window exists. */
5096 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5097 "foreground", "Foreground", RES_TYPE_STRING);
5098 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5099 "background", "Background", RES_TYPE_STRING);
5100 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5101 "pointerColor", "Foreground", RES_TYPE_STRING);
5102 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5103 "cursorColor", "Foreground", RES_TYPE_STRING);
5104 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5105 "borderColor", "BorderColor", RES_TYPE_STRING);
5106 x_default_parameter (f, parms, Qscreen_gamma, Qnil,
5107 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5110 /* Init faces before x_default_parameter is called for scroll-bar
5111 parameters because that function calls x_set_scroll_bar_width,
5112 which calls change_frame_size, which calls Fset_window_buffer,
5113 which runs hooks, which call Fvertical_motion. At the end, we
5114 end up in init_iterator with a null face cache, which should not
5115 happen. */
5116 init_frame_faces (f);
5118 x_default_parameter (f, parms, Qmenu_bar_lines, make_number (1),
5119 "menuBar", "MenuBar", RES_TYPE_NUMBER);
5120 x_default_parameter (f, parms, Qtool_bar_lines, make_number (0),
5121 "toolBar", "ToolBar", RES_TYPE_NUMBER);
5122 x_default_parameter (f, parms, Qbuffer_predicate, Qnil,
5123 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5124 x_default_parameter (f, parms, Qtitle, Qnil,
5125 "title", "Title", RES_TYPE_STRING);
5127 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5128 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
5129 window_prompting = x_figure_window_size (f, parms);
5131 if (window_prompting & XNegative)
5133 if (window_prompting & YNegative)
5134 f->output_data.w32->win_gravity = SouthEastGravity;
5135 else
5136 f->output_data.w32->win_gravity = NorthEastGravity;
5138 else
5140 if (window_prompting & YNegative)
5141 f->output_data.w32->win_gravity = SouthWestGravity;
5142 else
5143 f->output_data.w32->win_gravity = NorthWestGravity;
5146 f->output_data.w32->size_hint_flags = window_prompting;
5148 tem = w32_get_arg (parms, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5149 f->no_split = minibuffer_only || EQ (tem, Qt);
5151 /* Create the window. Add the tool-bar height to the initial frame
5152 height so that the user gets a text display area of the size he
5153 specified with -g or via the registry. Later changes of the
5154 tool-bar height don't change the frame size. This is done so that
5155 users can create tall Emacs frames without having to guess how
5156 tall the tool-bar will get. */
5157 f->height += FRAME_TOOL_BAR_LINES (f);
5158 w32_window (f, window_prompting, minibuffer_only);
5159 x_icon (f, parms);
5161 x_make_gc (f);
5163 /* Now consider the frame official. */
5164 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
5165 Vframe_list = Fcons (frame, Vframe_list);
5167 /* We need to do this after creating the window, so that the
5168 icon-creation functions can say whose icon they're describing. */
5169 x_default_parameter (f, parms, Qicon_type, Qnil,
5170 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5172 x_default_parameter (f, parms, Qauto_raise, Qnil,
5173 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5174 x_default_parameter (f, parms, Qauto_lower, Qnil,
5175 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5176 x_default_parameter (f, parms, Qcursor_type, Qbox,
5177 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5178 x_default_parameter (f, parms, Qscroll_bar_width, Qnil,
5179 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5181 /* Dimensions, especially f->height, must be done via change_frame_size.
5182 Change will not be effected unless different from the current
5183 f->height. */
5184 width = f->width;
5185 height = f->height;
5186 f->height = 0;
5187 SET_FRAME_WIDTH (f, 0);
5188 change_frame_size (f, height, width, 1, 0, 0);
5190 /* Set up faces after all frame parameters are known. */
5191 call1 (Qface_set_after_frame_default, frame);
5193 /* Tell the server what size and position, etc, we want, and how
5194 badly we want them. This should be done after we have the menu
5195 bar so that its size can be taken into account. */
5196 BLOCK_INPUT;
5197 x_wm_set_size_hint (f, window_prompting, 0);
5198 UNBLOCK_INPUT;
5200 /* Make the window appear on the frame and enable display, unless
5201 the caller says not to. However, with explicit parent, Emacs
5202 cannot control visibility, so don't try. */
5203 if (! f->output_data.w32->explicit_parent)
5205 Lisp_Object visibility;
5207 visibility = w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5208 if (EQ (visibility, Qunbound))
5209 visibility = Qt;
5211 if (EQ (visibility, Qicon))
5212 x_iconify_frame (f);
5213 else if (! NILP (visibility))
5214 x_make_frame_visible (f);
5215 else
5216 /* Must have been Qnil. */
5219 UNGCPRO;
5220 return unbind_to (count, frame);
5223 /* FRAME is used only to get a handle on the X display. We don't pass the
5224 display info directly because we're called from frame.c, which doesn't
5225 know about that structure. */
5226 Lisp_Object
5227 x_get_focus_frame (frame)
5228 struct frame *frame;
5230 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
5231 Lisp_Object xfocus;
5232 if (! dpyinfo->w32_focus_frame)
5233 return Qnil;
5235 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5236 return xfocus;
5239 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
5240 "Give FRAME input focus, raising to foreground if necessary.")
5241 (frame)
5242 Lisp_Object frame;
5244 x_focus_on_frame (check_x_frame (frame));
5245 return Qnil;
5249 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
5250 int size, char* filename);
5252 struct font_info *
5253 w32_load_system_font (f,fontname,size)
5254 struct frame *f;
5255 char * fontname;
5256 int size;
5258 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
5259 Lisp_Object font_names;
5261 /* Get a list of all the fonts that match this name. Once we
5262 have a list of matching fonts, we compare them against the fonts
5263 we already have loaded by comparing names. */
5264 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
5266 if (!NILP (font_names))
5268 Lisp_Object tail;
5269 int i;
5271 /* First check if any are already loaded, as that is cheaper
5272 than loading another one. */
5273 for (i = 0; i < dpyinfo->n_fonts; i++)
5274 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
5275 if (dpyinfo->font_table[i].name
5276 && (!strcmp (dpyinfo->font_table[i].name,
5277 XSTRING (XCAR (tail))->data)
5278 || !strcmp (dpyinfo->font_table[i].full_name,
5279 XSTRING (XCAR (tail))->data)))
5280 return (dpyinfo->font_table + i);
5282 fontname = (char *) XSTRING (XCAR (font_names))->data;
5284 else if (w32_strict_fontnames)
5286 /* If EnumFontFamiliesEx was available, we got a full list of
5287 fonts back so stop now to avoid the possibility of loading a
5288 random font. If we had to fall back to EnumFontFamilies, the
5289 list is incomplete, so continue whether the font we want was
5290 listed or not. */
5291 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5292 FARPROC enum_font_families_ex
5293 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
5294 if (enum_font_families_ex)
5295 return NULL;
5298 /* Load the font and add it to the table. */
5300 char *full_name, *encoding;
5301 XFontStruct *font;
5302 struct font_info *fontp;
5303 LOGFONT lf;
5304 BOOL ok;
5305 int i;
5307 if (!fontname || !x_to_w32_font (fontname, &lf))
5308 return (NULL);
5310 if (!*lf.lfFaceName)
5311 /* If no name was specified for the font, we get a random font
5312 from CreateFontIndirect - this is not particularly
5313 desirable, especially since CreateFontIndirect does not
5314 fill out the missing name in lf, so we never know what we
5315 ended up with. */
5316 return NULL;
5318 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
5320 /* Set bdf to NULL to indicate that this is a Windows font. */
5321 font->bdf = NULL;
5323 BLOCK_INPUT;
5325 font->hfont = CreateFontIndirect (&lf);
5327 if (font->hfont == NULL)
5329 ok = FALSE;
5331 else
5333 HDC hdc;
5334 HANDLE oldobj;
5336 hdc = GetDC (dpyinfo->root_window);
5337 oldobj = SelectObject (hdc, font->hfont);
5338 ok = GetTextMetrics (hdc, &font->tm);
5339 SelectObject (hdc, oldobj);
5340 ReleaseDC (dpyinfo->root_window, hdc);
5341 /* Fill out details in lf according to the font that was
5342 actually loaded. */
5343 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
5344 lf.lfWidth = font->tm.tmAveCharWidth;
5345 lf.lfWeight = font->tm.tmWeight;
5346 lf.lfItalic = font->tm.tmItalic;
5347 lf.lfCharSet = font->tm.tmCharSet;
5348 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
5349 ? VARIABLE_PITCH : FIXED_PITCH);
5350 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
5351 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
5354 UNBLOCK_INPUT;
5356 if (!ok)
5358 w32_unload_font (dpyinfo, font);
5359 return (NULL);
5362 /* Find a free slot in the font table. */
5363 for (i = 0; i < dpyinfo->n_fonts; ++i)
5364 if (dpyinfo->font_table[i].name == NULL)
5365 break;
5367 /* If no free slot found, maybe enlarge the font table. */
5368 if (i == dpyinfo->n_fonts
5369 && dpyinfo->n_fonts == dpyinfo->font_table_size)
5371 int sz;
5372 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
5373 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
5374 dpyinfo->font_table
5375 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
5378 fontp = dpyinfo->font_table + i;
5379 if (i == dpyinfo->n_fonts)
5380 ++dpyinfo->n_fonts;
5382 /* Now fill in the slots of *FONTP. */
5383 BLOCK_INPUT;
5384 fontp->font = font;
5385 fontp->font_idx = i;
5386 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
5387 bcopy (fontname, fontp->name, strlen (fontname) + 1);
5389 /* Work out the font's full name. */
5390 full_name = (char *)xmalloc (100);
5391 if (full_name && w32_to_x_font (&lf, full_name, 100))
5392 fontp->full_name = full_name;
5393 else
5395 /* If all else fails - just use the name we used to load it. */
5396 xfree (full_name);
5397 fontp->full_name = fontp->name;
5400 fontp->size = FONT_WIDTH (font);
5401 fontp->height = FONT_HEIGHT (font);
5403 /* The slot `encoding' specifies how to map a character
5404 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
5405 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF, 0:0x2020..0x7F7F,
5406 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF,
5407 0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF, or
5408 2:0xA020..0xFF7F). For the moment, we don't know which charset
5409 uses this font. So, we set information in fontp->encoding[1]
5410 which is never used by any charset. If mapping can't be
5411 decided, set FONT_ENCODING_NOT_DECIDED. */
5413 /* SJIS fonts need to be set to type 4, all others seem to work as
5414 type FONT_ENCODING_NOT_DECIDED. */
5415 encoding = strrchr (fontp->name, '-');
5416 if (encoding && stricmp (encoding+1, "sjis") == 0)
5417 fontp->encoding[1] = 4;
5418 else
5419 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
5421 /* The following three values are set to 0 under W32, which is
5422 what they get set to if XGetFontProperty fails under X. */
5423 fontp->baseline_offset = 0;
5424 fontp->relative_compose = 0;
5425 fontp->default_ascent = 0;
5427 /* Set global flag fonts_changed_p to non-zero if the font loaded
5428 has a character with a smaller width than any other character
5429 before, or if the font loaded has a smalle>r height than any
5430 other font loaded before. If this happens, it will make a
5431 glyph matrix reallocation necessary. */
5432 fonts_changed_p = x_compute_min_glyph_bounds (f);
5433 UNBLOCK_INPUT;
5434 return fontp;
5438 /* Load font named FONTNAME of size SIZE for frame F, and return a
5439 pointer to the structure font_info while allocating it dynamically.
5440 If loading fails, return NULL. */
5441 struct font_info *
5442 w32_load_font (f,fontname,size)
5443 struct frame *f;
5444 char * fontname;
5445 int size;
5447 Lisp_Object bdf_fonts;
5448 struct font_info *retval = NULL;
5450 bdf_fonts = w32_list_bdf_fonts (build_string (fontname));
5452 while (!retval && CONSP (bdf_fonts))
5454 char *bdf_name, *bdf_file;
5455 Lisp_Object bdf_pair;
5457 bdf_name = XSTRING (XCAR (bdf_fonts))->data;
5458 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
5459 bdf_file = XSTRING (XCDR (bdf_pair))->data;
5461 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
5463 bdf_fonts = XCDR (bdf_fonts);
5466 if (retval)
5467 return retval;
5469 return w32_load_system_font(f, fontname, size);
5473 void
5474 w32_unload_font (dpyinfo, font)
5475 struct w32_display_info *dpyinfo;
5476 XFontStruct * font;
5478 if (font)
5480 if (font->bdf) w32_free_bdf_font (font->bdf);
5482 if (font->hfont) DeleteObject(font->hfont);
5483 xfree (font);
5487 /* The font conversion stuff between x and w32 */
5489 /* X font string is as follows (from faces.el)
5490 * (let ((- "[-?]")
5491 * (foundry "[^-]+")
5492 * (family "[^-]+")
5493 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
5494 * (weight\? "\\([^-]*\\)") ; 1
5495 * (slant "\\([ior]\\)") ; 2
5496 * (slant\? "\\([^-]?\\)") ; 2
5497 * (swidth "\\([^-]*\\)") ; 3
5498 * (adstyle "[^-]*") ; 4
5499 * (pixelsize "[0-9]+")
5500 * (pointsize "[0-9][0-9]+")
5501 * (resx "[0-9][0-9]+")
5502 * (resy "[0-9][0-9]+")
5503 * (spacing "[cmp?*]")
5504 * (avgwidth "[0-9]+")
5505 * (registry "[^-]+")
5506 * (encoding "[^-]+")
5508 * (setq x-font-regexp
5509 * (concat "\\`\\*?[-?*]"
5510 * foundry - family - weight\? - slant\? - swidth - adstyle -
5511 * pixelsize - pointsize - resx - resy - spacing - registry -
5512 * encoding "[-?*]\\*?\\'"
5513 * ))
5514 * (setq x-font-regexp-head
5515 * (concat "\\`[-?*]" foundry - family - weight\? - slant\?
5516 * "\\([-*?]\\|\\'\\)"))
5517 * (setq x-font-regexp-slant (concat - slant -))
5518 * (setq x-font-regexp-weight (concat - weight -))
5519 * nil)
5522 #define FONT_START "[-?]"
5523 #define FONT_FOUNDRY "[^-]+"
5524 #define FONT_FAMILY "\\([^-]+\\)" /* 1 */
5525 #define FONT_WEIGHT "\\(bold\\|demibold\\|medium\\)" /* 2 */
5526 #define FONT_WEIGHT_Q "\\([^-]*\\)" /* 2 */
5527 #define FONT_SLANT "\\([ior]\\)" /* 3 */
5528 #define FONT_SLANT_Q "\\([^-]?\\)" /* 3 */
5529 #define FONT_SWIDTH "\\([^-]*\\)" /* 4 */
5530 #define FONT_ADSTYLE "[^-]*"
5531 #define FONT_PIXELSIZE "[^-]*"
5532 #define FONT_POINTSIZE "\\([0-9][0-9]+\\|\\*\\)" /* 5 */
5533 #define FONT_RESX "[0-9][0-9]+"
5534 #define FONT_RESY "[0-9][0-9]+"
5535 #define FONT_SPACING "[cmp?*]"
5536 #define FONT_AVGWIDTH "[0-9]+"
5537 #define FONT_REGISTRY "[^-]+"
5538 #define FONT_ENCODING "[^-]+"
5540 #define FONT_REGEXP ("\\`\\*?[-?*]" \
5541 FONT_FOUNDRY "-" \
5542 FONT_FAMILY "-" \
5543 FONT_WEIGHT_Q "-" \
5544 FONT_SLANT_Q "-" \
5545 FONT_SWIDTH "-" \
5546 FONT_ADSTYLE "-" \
5547 FONT_PIXELSIZE "-" \
5548 FONT_POINTSIZE "-" \
5549 "[-?*]\\|\\'")
5551 #define FONT_REGEXP_HEAD ("\\`[-?*]" \
5552 FONT_FOUNDRY "-" \
5553 FONT_FAMILY "-" \
5554 FONT_WEIGHT_Q "-" \
5555 FONT_SLANT_Q \
5556 "\\([-*?]\\|\\'\\)")
5558 #define FONT_REGEXP_SLANT "-" FONT_SLANT "-"
5559 #define FONT_REGEXP_WEIGHT "-" FONT_WEIGHT "-"
5561 LONG
5562 x_to_w32_weight (lpw)
5563 char * lpw;
5565 if (!lpw) return (FW_DONTCARE);
5567 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
5568 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
5569 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
5570 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
5571 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
5572 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
5573 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
5574 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
5575 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
5576 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
5577 else
5578 return FW_DONTCARE;
5582 char *
5583 w32_to_x_weight (fnweight)
5584 int fnweight;
5586 if (fnweight >= FW_HEAVY) return "heavy";
5587 if (fnweight >= FW_EXTRABOLD) return "extrabold";
5588 if (fnweight >= FW_BOLD) return "bold";
5589 if (fnweight >= FW_SEMIBOLD) return "demibold";
5590 if (fnweight >= FW_MEDIUM) return "medium";
5591 if (fnweight >= FW_NORMAL) return "normal";
5592 if (fnweight >= FW_LIGHT) return "light";
5593 if (fnweight >= FW_EXTRALIGHT) return "extralight";
5594 if (fnweight >= FW_THIN) return "thin";
5595 else
5596 return "*";
5599 LONG
5600 x_to_w32_charset (lpcs)
5601 char * lpcs;
5603 if (!lpcs) return (0);
5605 if (stricmp (lpcs,"ansi") == 0) return ANSI_CHARSET;
5606 else if (stricmp (lpcs,"iso8859-1") == 0) return ANSI_CHARSET;
5607 else if (stricmp (lpcs, "ms-symbol") == 0) return SYMBOL_CHARSET;
5608 /* Map all Japanese charsets to the Windows Shift-JIS charset. */
5609 else if (strnicmp (lpcs, "jis", 3) == 0) return SHIFTJIS_CHARSET;
5610 /* Map all GB charsets to the Windows GB2312 charset. */
5611 else if (strnicmp (lpcs, "gb2312", 6) == 0) return GB2312_CHARSET;
5612 /* Map all Big5 charsets to the Windows Big5 charset. */
5613 else if (strnicmp (lpcs, "big5", 4) == 0) return CHINESEBIG5_CHARSET;
5614 else if (stricmp (lpcs, "ksc5601.1987") == 0) return HANGEUL_CHARSET;
5615 else if (stricmp (lpcs, "ms-oem") == 0) return OEM_CHARSET;
5617 #ifdef EASTEUROPE_CHARSET
5618 else if (stricmp (lpcs, "iso8859-2") == 0) return EASTEUROPE_CHARSET;
5619 else if (stricmp (lpcs, "iso8859-3") == 0) return TURKISH_CHARSET;
5620 else if (stricmp (lpcs, "iso8859-4") == 0) return BALTIC_CHARSET;
5621 else if (stricmp (lpcs, "iso8859-5") == 0) return RUSSIAN_CHARSET;
5622 else if (stricmp (lpcs, "koi8") == 0) return RUSSIAN_CHARSET;
5623 else if (stricmp (lpcs, "iso8859-6") == 0) return ARABIC_CHARSET;
5624 else if (stricmp (lpcs, "iso8859-7") == 0) return GREEK_CHARSET;
5625 else if (stricmp (lpcs, "iso8859-8") == 0) return HEBREW_CHARSET;
5626 else if (stricmp (lpcs, "iso8859-9") == 0) return TURKISH_CHARSET;
5627 #ifndef VIETNAMESE_CHARSET
5628 #define VIETNAMESE_CHARSET 163
5629 #endif
5630 /* Map all Viscii charsets to the Windows Vietnamese charset. */
5631 else if (strnicmp (lpcs, "viscii", 6) == 0) return VIETNAMESE_CHARSET;
5632 else if (strnicmp (lpcs, "vscii", 5) == 0) return VIETNAMESE_CHARSET;
5633 /* Map all TIS charsets to the Windows Thai charset. */
5634 else if (strnicmp (lpcs, "tis620", 6) == 0) return THAI_CHARSET;
5635 else if (stricmp (lpcs, "mac") == 0) return MAC_CHARSET;
5636 else if (stricmp (lpcs, "ksc5601.1992") == 0) return JOHAB_CHARSET;
5637 /* For backwards compatibility with previous 20.4 pretests, map
5638 non-specific KSC charsets to the Windows Hangeul charset. */
5639 else if (strnicmp (lpcs, "ksc5601", 7) == 0) return HANGEUL_CHARSET;
5640 else if (stricmp (lpcs, "johab") == 0) return JOHAB_CHARSET;
5641 #endif
5643 #ifdef UNICODE_CHARSET
5644 else if (stricmp (lpcs,"iso10646") == 0) return UNICODE_CHARSET;
5645 else if (stricmp (lpcs, "unicode") == 0) return UNICODE_CHARSET;
5646 #endif
5647 else if (lpcs[0] == '#') return atoi (lpcs + 1);
5648 else
5649 return DEFAULT_CHARSET;
5652 char *
5653 w32_to_x_charset (fncharset)
5654 int fncharset;
5656 static char buf[16];
5658 switch (fncharset)
5660 /* ansi is considered iso8859-1, as most modern ansi fonts are. */
5661 case ANSI_CHARSET: return "iso8859-1";
5662 case DEFAULT_CHARSET: return "ascii-*";
5663 case SYMBOL_CHARSET: return "ms-symbol";
5664 case SHIFTJIS_CHARSET: return "jisx0208-sjis";
5665 case HANGEUL_CHARSET: return "ksc5601.1987-*";
5666 case GB2312_CHARSET: return "gb2312-*";
5667 case CHINESEBIG5_CHARSET: return "big5-*";
5668 case OEM_CHARSET: return "ms-oem";
5670 /* More recent versions of Windows (95 and NT4.0) define more
5671 character sets. */
5672 #ifdef EASTEUROPE_CHARSET
5673 case EASTEUROPE_CHARSET: return "iso8859-2";
5674 case TURKISH_CHARSET: return "iso8859-9";
5675 case BALTIC_CHARSET: return "iso8859-4";
5677 /* W95 with international support but not IE4 often has the
5678 KOI8-R codepage but not ISO8859-5. */
5679 case RUSSIAN_CHARSET:
5680 if (!IsValidCodePage(28595) && IsValidCodePage(20886))
5681 return "koi8-r";
5682 else
5683 return "iso8859-5";
5684 case ARABIC_CHARSET: return "iso8859-6";
5685 case GREEK_CHARSET: return "iso8859-7";
5686 case HEBREW_CHARSET: return "iso8859-8";
5687 case VIETNAMESE_CHARSET: return "viscii1.1-*";
5688 case THAI_CHARSET: return "tis620-*";
5689 case MAC_CHARSET: return "mac-*";
5690 case JOHAB_CHARSET: return "ksc5601.1992-*";
5692 #endif
5694 #ifdef UNICODE_CHARSET
5695 case UNICODE_CHARSET: return "iso10646-unicode";
5696 #endif
5698 /* Encode numerical value of unknown charset. */
5699 sprintf (buf, "*-#%u", fncharset);
5700 return buf;
5703 BOOL
5704 w32_to_x_font (lplogfont, lpxstr, len)
5705 LOGFONT * lplogfont;
5706 char * lpxstr;
5707 int len;
5709 char* fonttype;
5710 char *fontname;
5711 char height_pixels[8];
5712 char height_dpi[8];
5713 char width_pixels[8];
5714 char *fontname_dash;
5715 int display_resy = one_w32_display_info.resy;
5716 int display_resx = one_w32_display_info.resx;
5717 int bufsz;
5718 struct coding_system coding;
5720 if (!lpxstr) abort ();
5722 if (!lplogfont)
5723 return FALSE;
5725 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5726 fonttype = "raster";
5727 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5728 fonttype = "outline";
5729 else
5730 fonttype = "unknown";
5732 setup_coding_system (Fcheck_coding_system (Vw32_system_coding_system),
5733 &coding);
5734 coding.mode |= CODING_MODE_LAST_BLOCK;
5735 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
5737 fontname = alloca(sizeof(*fontname) * bufsz);
5738 decode_coding (&coding, lplogfont->lfFaceName, fontname,
5739 strlen(lplogfont->lfFaceName), bufsz - 1);
5740 *(fontname + coding.produced) = '\0';
5742 /* Replace dashes with underscores so the dashes are not
5743 misinterpreted. */
5744 fontname_dash = fontname;
5745 while (fontname_dash = strchr (fontname_dash, '-'))
5746 *fontname_dash = '_';
5748 if (lplogfont->lfHeight)
5750 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
5751 sprintf (height_dpi, "%u",
5752 abs (lplogfont->lfHeight) * 720 / display_resy);
5754 else
5756 strcpy (height_pixels, "*");
5757 strcpy (height_dpi, "*");
5759 if (lplogfont->lfWidth)
5760 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5761 else
5762 strcpy (width_pixels, "*");
5764 _snprintf (lpxstr, len - 1,
5765 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5766 fonttype, /* foundry */
5767 fontname, /* family */
5768 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5769 lplogfont->lfItalic?'i':'r', /* slant */
5770 /* setwidth name */
5771 /* add style name */
5772 height_pixels, /* pixel size */
5773 height_dpi, /* point size */
5774 display_resx, /* resx */
5775 display_resy, /* resy */
5776 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5777 ? 'p' : 'c', /* spacing */
5778 width_pixels, /* avg width */
5779 w32_to_x_charset (lplogfont->lfCharSet) /* charset registry
5780 and encoding*/
5783 lpxstr[len - 1] = 0; /* just to be sure */
5784 return (TRUE);
5787 BOOL
5788 x_to_w32_font (lpxstr, lplogfont)
5789 char * lpxstr;
5790 LOGFONT * lplogfont;
5792 struct coding_system coding;
5794 if (!lplogfont) return (FALSE);
5796 memset (lplogfont, 0, sizeof (*lplogfont));
5798 /* Set default value for each field. */
5799 #if 1
5800 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5801 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5802 lplogfont->lfQuality = DEFAULT_QUALITY;
5803 #else
5804 /* go for maximum quality */
5805 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5806 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5807 lplogfont->lfQuality = PROOF_QUALITY;
5808 #endif
5810 lplogfont->lfCharSet = DEFAULT_CHARSET;
5811 lplogfont->lfWeight = FW_DONTCARE;
5812 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5814 if (!lpxstr)
5815 return FALSE;
5817 /* Provide a simple escape mechanism for specifying Windows font names
5818 * directly -- if font spec does not beginning with '-', assume this
5819 * format:
5820 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5823 if (*lpxstr == '-')
5825 int fields, tem;
5826 char name[50], weight[20], slant, pitch, pixels[10], height[10],
5827 width[10], resy[10], remainder[20];
5828 char * encoding;
5829 int dpi = one_w32_display_info.height_in;
5831 fields = sscanf (lpxstr,
5832 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%19s",
5833 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
5834 if (fields == EOF) return (FALSE);
5836 /* If wildcards cover more than one field, we don't know which
5837 field is which, so don't fill any in. */
5839 if (fields < 9)
5840 fields = 0;
5842 if (fields > 0 && name[0] != '*')
5844 int bufsize;
5845 unsigned char *buf;
5847 setup_coding_system
5848 (Fcheck_coding_system (Vw32_system_coding_system), &coding);
5849 bufsize = encoding_buffer_size (&coding, strlen (name));
5850 buf = (unsigned char *) alloca (bufsize);
5851 coding.mode |= CODING_MODE_LAST_BLOCK;
5852 encode_coding (&coding, name, buf, strlen (name), bufsize);
5853 if (coding.produced >= LF_FACESIZE)
5854 coding.produced = LF_FACESIZE - 1;
5855 buf[coding.produced] = 0;
5856 strcpy (lplogfont->lfFaceName, buf);
5858 else
5860 lplogfont->lfFaceName[0] = '\0';
5863 fields--;
5865 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5867 fields--;
5869 if (!NILP (Vw32_enable_synthesized_fonts))
5870 lplogfont->lfItalic = (fields > 0 && slant == 'i');
5872 fields--;
5874 if (fields > 0 && pixels[0] != '*')
5875 lplogfont->lfHeight = atoi (pixels);
5877 fields--;
5878 fields--;
5879 if (fields > 0 && resy[0] != '*')
5881 tem = atoi (resy);
5882 if (tem > 0) dpi = tem;
5885 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
5886 lplogfont->lfHeight = atoi (height) * dpi / 720;
5888 if (fields > 0)
5889 lplogfont->lfPitchAndFamily =
5890 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
5892 fields--;
5894 if (fields > 0 && width[0] != '*')
5895 lplogfont->lfWidth = atoi (width) / 10;
5897 fields--;
5899 /* Strip the trailing '-' if present. (it shouldn't be, as it
5900 fails the test against xlfd-tight-regexp in fontset.el). */
5902 int len = strlen (remainder);
5903 if (len > 0 && remainder[len-1] == '-')
5904 remainder[len-1] = 0;
5906 encoding = remainder;
5907 if (strncmp (encoding, "*-", 2) == 0)
5908 encoding += 2;
5909 lplogfont->lfCharSet = x_to_w32_charset (fields > 0 ? encoding : "");
5911 else
5913 int fields;
5914 char name[100], height[10], width[10], weight[20];
5916 fields = sscanf (lpxstr,
5917 "%99[^:]:%9[^:]:%9[^:]:%19s",
5918 name, height, width, weight);
5920 if (fields == EOF) return (FALSE);
5922 if (fields > 0)
5924 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
5925 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
5927 else
5929 lplogfont->lfFaceName[0] = 0;
5932 fields--;
5934 if (fields > 0)
5935 lplogfont->lfHeight = atoi (height);
5937 fields--;
5939 if (fields > 0)
5940 lplogfont->lfWidth = atoi (width);
5942 fields--;
5944 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5947 /* This makes TrueType fonts work better. */
5948 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
5950 return (TRUE);
5953 /* Strip the pixel height and point height from the given xlfd, and
5954 return the pixel height. If no pixel height is specified, calculate
5955 one from the point height, or if that isn't defined either, return
5956 0 (which usually signifies a scalable font).
5958 int xlfd_strip_height (char *fontname)
5960 int pixel_height, point_height, dpi, field_number;
5961 char *read_from, *write_to;
5963 xassert (fontname);
5965 pixel_height = field_number = 0;
5966 write_to = NULL;
5968 /* Look for height fields. */
5969 for (read_from = fontname; *read_from; read_from++)
5971 if (*read_from == '-')
5973 field_number++;
5974 if (field_number == 7) /* Pixel height. */
5976 read_from++;
5977 write_to = read_from;
5979 /* Find end of field. */
5980 for (;*read_from && *read_from != '-'; read_from++)
5983 /* Split the fontname at end of field. */
5984 if (*read_from)
5986 *read_from = '\0';
5987 read_from++;
5989 pixel_height = atoi (write_to);
5990 /* Blank out field. */
5991 if (read_from > write_to)
5993 *write_to = '-';
5994 write_to++;
5996 /* If the pixel height field is at the end (partial xfld),
5997 return now. */
5998 else
5999 return pixel_height;
6001 /* If we got a pixel height, the point height can be
6002 ignored. Just blank it out and break now. */
6003 if (pixel_height)
6005 /* Find end of point size field. */
6006 for (; *read_from && *read_from != '-'; read_from++)
6009 if (*read_from)
6010 read_from++;
6012 /* Blank out the point size field. */
6013 if (read_from > write_to)
6015 *write_to = '-';
6016 write_to++;
6018 else
6019 return pixel_height;
6021 break;
6023 /* If the point height is already blank, break now. */
6024 if (*read_from == '-')
6026 read_from++;
6027 break;
6030 else if (field_number == 8)
6032 /* If we didn't get a pixel height, try to get the point
6033 height and convert that. */
6034 int point_size;
6035 char *point_size_start = read_from++;
6037 /* Find end of field. */
6038 for (; *read_from && *read_from != '-'; read_from++)
6041 if (*read_from)
6043 *read_from = '\0';
6044 read_from++;
6047 point_size = atoi (point_size_start);
6049 /* Convert to pixel height. */
6050 pixel_height = point_size
6051 * one_w32_display_info.height_in / 720;
6053 /* Blank out this field and break. */
6054 *write_to = '-';
6055 write_to++;
6056 break;
6061 /* Shift the rest of the font spec into place. */
6062 if (write_to && read_from > write_to)
6064 for (; *read_from; read_from++, write_to++)
6065 *write_to = *read_from;
6066 *write_to = '\0';
6069 return pixel_height;
6072 /* Assume parameter 1 is fully qualified, no wildcards. */
6073 BOOL
6074 w32_font_match (fontname, pattern)
6075 char * fontname;
6076 char * pattern;
6078 char *regex = alloca (strlen (pattern) * 2);
6079 char *font_name_copy = alloca (strlen (fontname) + 1);
6080 char *ptr;
6082 /* Copy fontname so we can modify it during comparison. */
6083 strcpy (font_name_copy, fontname);
6085 ptr = regex;
6086 *ptr++ = '^';
6088 /* Turn pattern into a regexp and do a regexp match. */
6089 for (; *pattern; pattern++)
6091 if (*pattern == '?')
6092 *ptr++ = '.';
6093 else if (*pattern == '*')
6095 *ptr++ = '.';
6096 *ptr++ = '*';
6098 else
6099 *ptr++ = *pattern;
6101 *ptr = '$';
6102 *(ptr + 1) = '\0';
6104 /* Strip out font heights and compare them seperately, since
6105 rounding error can cause mismatches. This also allows a
6106 comparison between a font that declares only a pixel height and a
6107 pattern that declares the point height.
6110 int font_height, pattern_height;
6112 font_height = xlfd_strip_height (font_name_copy);
6113 pattern_height = xlfd_strip_height (regex);
6115 /* Compare now, and don't bother doing expensive regexp matching
6116 if the heights differ. */
6117 if (font_height && pattern_height && (font_height != pattern_height))
6118 return FALSE;
6121 return (fast_c_string_match_ignore_case (build_string (regex),
6122 font_name_copy) >= 0);
6125 /* Callback functions, and a structure holding info they need, for
6126 listing system fonts on W32. We need one set of functions to do the
6127 job properly, but these don't work on NT 3.51 and earlier, so we
6128 have a second set which don't handle character sets properly to
6129 fall back on.
6131 In both cases, there are two passes made. The first pass gets one
6132 font from each family, the second pass lists all the fonts from
6133 each family. */
6135 typedef struct enumfont_t
6137 HDC hdc;
6138 int numFonts;
6139 LOGFONT logfont;
6140 XFontStruct *size_ref;
6141 Lisp_Object *pattern;
6142 Lisp_Object *tail;
6143 } enumfont_t;
6145 int CALLBACK
6146 enum_font_cb2 (lplf, lptm, FontType, lpef)
6147 ENUMLOGFONT * lplf;
6148 NEWTEXTMETRIC * lptm;
6149 int FontType;
6150 enumfont_t * lpef;
6152 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
6153 return (1);
6155 /* Check that the character set matches if it was specified */
6156 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
6157 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
6158 return (1);
6161 char buf[100];
6162 Lisp_Object width = Qnil;
6164 /* Truetype fonts do not report their true metrics until loaded */
6165 if (FontType != RASTER_FONTTYPE)
6167 if (!NILP (*(lpef->pattern)))
6169 /* Scalable fonts are as big as you want them to be. */
6170 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
6171 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
6172 width = make_number (lpef->logfont.lfWidth);
6174 else
6176 lplf->elfLogFont.lfHeight = 0;
6177 lplf->elfLogFont.lfWidth = 0;
6181 /* Make sure the height used here is the same as everywhere
6182 else (ie character height, not cell height). */
6183 if (lplf->elfLogFont.lfHeight > 0)
6185 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
6186 if (FontType == RASTER_FONTTYPE)
6187 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
6188 else
6189 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
6192 if (!w32_to_x_font (&(lplf->elfLogFont), buf, 100))
6193 return (0);
6195 if (NILP (*(lpef->pattern))
6196 || w32_font_match (buf, XSTRING (*(lpef->pattern))->data))
6198 *lpef->tail = Fcons (Fcons (build_string (buf), width), Qnil);
6199 lpef->tail = &(XCDR (*lpef->tail));
6200 lpef->numFonts++;
6204 return (1);
6207 int CALLBACK
6208 enum_font_cb1 (lplf, lptm, FontType, lpef)
6209 ENUMLOGFONT * lplf;
6210 NEWTEXTMETRIC * lptm;
6211 int FontType;
6212 enumfont_t * lpef;
6214 return EnumFontFamilies (lpef->hdc,
6215 lplf->elfLogFont.lfFaceName,
6216 (FONTENUMPROC) enum_font_cb2,
6217 (LPARAM) lpef);
6221 int CALLBACK
6222 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
6223 ENUMLOGFONTEX * lplf;
6224 NEWTEXTMETRICEX * lptm;
6225 int font_type;
6226 enumfont_t * lpef;
6228 /* We are not interested in the extra info we get back from the 'Ex
6229 version - only the fact that we get character set variations
6230 enumerated seperately. */
6231 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
6232 font_type, lpef);
6235 int CALLBACK
6236 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
6237 ENUMLOGFONTEX * lplf;
6238 NEWTEXTMETRICEX * lptm;
6239 int font_type;
6240 enumfont_t * lpef;
6242 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6243 FARPROC enum_font_families_ex
6244 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6245 /* We don't really expect EnumFontFamiliesEx to disappear once we
6246 get here, so don't bother handling it gracefully. */
6247 if (enum_font_families_ex == NULL)
6248 error ("gdi32.dll has disappeared!");
6249 return enum_font_families_ex (lpef->hdc,
6250 &lplf->elfLogFont,
6251 (FONTENUMPROC) enum_fontex_cb2,
6252 (LPARAM) lpef, 0);
6255 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6256 and xterm.c in Emacs 20.3) */
6258 Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6260 char *fontname, *ptnstr;
6261 Lisp_Object list, tem, newlist = Qnil;
6262 int n_fonts = 0;
6264 list = Vw32_bdf_filename_alist;
6265 ptnstr = XSTRING (pattern)->data;
6267 for ( ; CONSP (list); list = XCDR (list))
6269 tem = XCAR (list);
6270 if (CONSP (tem))
6271 fontname = XSTRING (XCAR (tem))->data;
6272 else if (STRINGP (tem))
6273 fontname = XSTRING (tem)->data;
6274 else
6275 continue;
6277 if (w32_font_match (fontname, ptnstr))
6279 newlist = Fcons (XCAR (tem), newlist);
6280 n_fonts++;
6281 if (n_fonts >= max_names)
6282 break;
6286 return newlist;
6289 Lisp_Object w32_list_synthesized_fonts (FRAME_PTR f, Lisp_Object pattern,
6290 int size, int max_names);
6292 /* Return a list of names of available fonts matching PATTERN on frame
6293 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6294 to be listed. Frame F NULL means we have not yet created any
6295 frame, which means we can't get proper size info, as we don't have
6296 a device context to use for GetTextMetrics.
6297 MAXNAMES sets a limit on how many fonts to match. */
6299 Lisp_Object
6300 w32_list_fonts (FRAME_PTR f, Lisp_Object pattern, int size, int maxnames )
6302 Lisp_Object patterns, key = Qnil, tem, tpat;
6303 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6304 struct w32_display_info *dpyinfo = &one_w32_display_info;
6305 int n_fonts = 0;
6307 patterns = Fassoc (pattern, Valternate_fontname_alist);
6308 if (NILP (patterns))
6309 patterns = Fcons (pattern, Qnil);
6311 for (; CONSP (patterns); patterns = XCDR (patterns))
6313 enumfont_t ef;
6315 tpat = XCAR (patterns);
6317 /* See if we cached the result for this particular query.
6318 The cache is an alist of the form:
6319 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6321 if (tem = XCDR (dpyinfo->name_list_element),
6322 !NILP (list = Fassoc (tpat, tem)))
6324 list = Fcdr_safe (list);
6325 /* We have a cached list. Don't have to get the list again. */
6326 goto label_cached;
6329 BLOCK_INPUT;
6330 /* At first, put PATTERN in the cache. */
6331 list = Qnil;
6332 ef.pattern = &tpat;
6333 ef.tail = &list;
6334 ef.numFonts = 0;
6336 /* Use EnumFontFamiliesEx where it is available, as it knows
6337 about character sets. Fall back to EnumFontFamilies for
6338 older versions of NT that don't support the 'Ex function. */
6339 x_to_w32_font (STRINGP (tpat) ? XSTRING (tpat)->data :
6340 NULL, &ef.logfont);
6342 LOGFONT font_match_pattern;
6343 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6344 FARPROC enum_font_families_ex
6345 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6347 /* We do our own pattern matching so we can handle wildcards. */
6348 font_match_pattern.lfFaceName[0] = 0;
6349 font_match_pattern.lfPitchAndFamily = 0;
6350 /* We can use the charset, because if it is a wildcard it will
6351 be DEFAULT_CHARSET anyway. */
6352 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6354 ef.hdc = GetDC (dpyinfo->root_window);
6356 if (enum_font_families_ex)
6357 enum_font_families_ex (ef.hdc,
6358 &font_match_pattern,
6359 (FONTENUMPROC) enum_fontex_cb1,
6360 (LPARAM) &ef, 0);
6361 else
6362 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6363 (LPARAM)&ef);
6365 ReleaseDC (dpyinfo->root_window, ef.hdc);
6368 UNBLOCK_INPUT;
6370 /* Make a list of the fonts we got back.
6371 Store that in the font cache for the display. */
6372 XCDR (dpyinfo->name_list_element)
6373 = Fcons (Fcons (tpat, list),
6374 XCDR (dpyinfo->name_list_element));
6376 label_cached:
6377 if (NILP (list)) continue; /* Try the remaining alternatives. */
6379 newlist = second_best = Qnil;
6381 /* Make a list of the fonts that have the right width. */
6382 for (; CONSP (list); list = XCDR (list))
6384 int found_size;
6385 tem = XCAR (list);
6387 if (!CONSP (tem))
6388 continue;
6389 if (NILP (XCAR (tem)))
6390 continue;
6391 if (!size)
6393 newlist = Fcons (XCAR (tem), newlist);
6394 n_fonts++;
6395 if (n_fonts >= maxnames)
6396 break;
6397 else
6398 continue;
6400 if (!INTEGERP (XCDR (tem)))
6402 /* Since we don't yet know the size of the font, we must
6403 load it and try GetTextMetrics. */
6404 W32FontStruct thisinfo;
6405 LOGFONT lf;
6406 HDC hdc;
6407 HANDLE oldobj;
6409 if (!x_to_w32_font (XSTRING (XCAR (tem))->data, &lf))
6410 continue;
6412 BLOCK_INPUT;
6413 thisinfo.bdf = NULL;
6414 thisinfo.hfont = CreateFontIndirect (&lf);
6415 if (thisinfo.hfont == NULL)
6416 continue;
6418 hdc = GetDC (dpyinfo->root_window);
6419 oldobj = SelectObject (hdc, thisinfo.hfont);
6420 if (GetTextMetrics (hdc, &thisinfo.tm))
6421 XCDR (tem) = make_number (FONT_WIDTH (&thisinfo));
6422 else
6423 XCDR (tem) = make_number (0);
6424 SelectObject (hdc, oldobj);
6425 ReleaseDC (dpyinfo->root_window, hdc);
6426 DeleteObject(thisinfo.hfont);
6427 UNBLOCK_INPUT;
6429 found_size = XINT (XCDR (tem));
6430 if (found_size == size)
6432 newlist = Fcons (XCAR (tem), newlist);
6433 n_fonts++;
6434 if (n_fonts >= maxnames)
6435 break;
6437 /* keep track of the closest matching size in case
6438 no exact match is found. */
6439 else if (found_size > 0)
6441 if (NILP (second_best))
6442 second_best = tem;
6444 else if (found_size < size)
6446 if (XINT (XCDR (second_best)) > size
6447 || XINT (XCDR (second_best)) < found_size)
6448 second_best = tem;
6450 else
6452 if (XINT (XCDR (second_best)) > size
6453 && XINT (XCDR (second_best)) >
6454 found_size)
6455 second_best = tem;
6460 if (!NILP (newlist))
6461 break;
6462 else if (!NILP (second_best))
6464 newlist = Fcons (XCAR (second_best), Qnil);
6465 break;
6469 /* Include any bdf fonts. */
6470 if (n_fonts < maxnames)
6472 Lisp_Object combined[2];
6473 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6474 combined[1] = newlist;
6475 newlist = Fnconc(2, combined);
6478 /* If we can't find a font that matches, check if Windows would be
6479 able to synthesize it from a different style. */
6480 if (NILP (newlist) && !NILP (Vw32_enable_synthesized_fonts))
6481 newlist = w32_list_synthesized_fonts (f, pattern, size, maxnames);
6483 return newlist;
6486 Lisp_Object
6487 w32_list_synthesized_fonts (f, pattern, size, max_names)
6488 FRAME_PTR f;
6489 Lisp_Object pattern;
6490 int size;
6491 int max_names;
6493 int fields;
6494 char *full_pattn, *new_pattn, foundary[50], family[50], *pattn_part2;
6495 char style[20], slant;
6496 Lisp_Object matches, match, tem, synthed_matches = Qnil;
6498 full_pattn = XSTRING (pattern)->data;
6500 pattn_part2 = alloca (XSTRING (pattern)->size);
6501 /* Allow some space for wildcard expansion. */
6502 new_pattn = alloca (XSTRING (pattern)->size + 100);
6504 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%19[^-]-%c-%s",
6505 foundary, family, style, &slant, pattn_part2);
6506 if (fields == EOF || fields < 5)
6507 return Qnil;
6509 /* If the style and slant are wildcards already there is no point
6510 checking again (and we don't want to keep recursing). */
6511 if (*style == '*' && slant == '*')
6512 return Qnil;
6514 sprintf (new_pattn, "-%s-%s-*-*-%s", foundary, family, pattn_part2);
6516 matches = w32_list_fonts (f, build_string (new_pattn), size, max_names);
6518 for ( ; CONSP (matches); matches = XCDR (matches))
6520 tem = XCAR (matches);
6521 if (!STRINGP (tem))
6522 continue;
6524 full_pattn = XSTRING (tem)->data;
6525 fields = sscanf (full_pattn, "-%49[^-]-%49[^-]-%*[^-]-%*c-%s",
6526 foundary, family, pattn_part2);
6527 if (fields == EOF || fields < 3)
6528 continue;
6530 sprintf (new_pattn, "-%s-%s-%s-%c-%s", foundary, family, style,
6531 slant, pattn_part2);
6533 synthed_matches = Fcons (build_string (new_pattn),
6534 synthed_matches);
6537 return synthed_matches;
6541 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6542 struct font_info *
6543 w32_get_font_info (f, font_idx)
6544 FRAME_PTR f;
6545 int font_idx;
6547 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6551 struct font_info*
6552 w32_query_font (struct frame *f, char *fontname)
6554 int i;
6555 struct font_info *pfi;
6557 pfi = FRAME_W32_FONT_TABLE (f);
6559 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6561 if (strcmp(pfi->name, fontname) == 0) return pfi;
6564 return NULL;
6567 /* Find a CCL program for a font specified by FONTP, and set the member
6568 `encoder' of the structure. */
6570 void
6571 w32_find_ccl_program (fontp)
6572 struct font_info *fontp;
6574 Lisp_Object list, elt;
6576 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6578 elt = XCAR (list);
6579 if (CONSP (elt)
6580 && STRINGP (XCAR (elt))
6581 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6582 >= 0))
6583 break;
6585 if (! NILP (list))
6587 struct ccl_program *ccl
6588 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6590 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6591 xfree (ccl);
6592 else
6593 fontp->font_encoder = ccl;
6598 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6599 1, 1, 0,
6600 "Return a list of BDF fonts in DIR, suitable for appending to\n\
6601 w32-bdf-filename-alist. Fonts which do not contain an xfld description\n\
6602 will not be included in the list. DIR may be a list of directories.")
6603 (directory)
6604 Lisp_Object directory;
6606 Lisp_Object list = Qnil;
6607 struct gcpro gcpro1, gcpro2;
6609 if (!CONSP (directory))
6610 return w32_find_bdf_fonts_in_dir (directory);
6612 for ( ; CONSP (directory); directory = XCDR (directory))
6614 Lisp_Object pair[2];
6615 pair[0] = list;
6616 pair[1] = Qnil;
6617 GCPRO2 (directory, list);
6618 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
6619 list = Fnconc( 2, pair );
6620 UNGCPRO;
6622 return list;
6625 /* Find BDF files in a specified directory. (use GCPRO when calling,
6626 as this calls lisp to get a directory listing). */
6627 Lisp_Object w32_find_bdf_fonts_in_dir( Lisp_Object directory )
6629 Lisp_Object filelist, list = Qnil;
6630 char fontname[100];
6632 if (!STRINGP(directory))
6633 return Qnil;
6635 filelist = Fdirectory_files (directory, Qt,
6636 build_string (".*\\.[bB][dD][fF]"), Qt);
6638 for ( ; CONSP(filelist); filelist = XCDR (filelist))
6640 Lisp_Object filename = XCAR (filelist);
6641 if (w32_BDF_to_x_font (XSTRING (filename)->data, fontname, 100))
6642 store_in_alist (&list, build_string (fontname), filename);
6644 return list;
6648 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6649 "Return non-nil if color COLOR is supported on frame FRAME.\n\
6650 If FRAME is omitted or nil, use the selected frame.")
6651 (color, frame)
6652 Lisp_Object color, frame;
6654 XColor foo;
6655 FRAME_PTR f = check_x_frame (frame);
6657 CHECK_STRING (color, 1);
6659 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
6660 return Qt;
6661 else
6662 return Qnil;
6665 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6666 "Return a description of the color named COLOR on frame FRAME.\n\
6667 The value is a list of integer RGB values--(RED GREEN BLUE).\n\
6668 These values appear to range from 0 to 65280 or 65535, depending\n\
6669 on the system; white is (65280 65280 65280) or (65535 65535 65535).\n\
6670 If FRAME is omitted or nil, use the selected frame.")
6671 (color, frame)
6672 Lisp_Object color, frame;
6674 XColor foo;
6675 FRAME_PTR f = check_x_frame (frame);
6677 CHECK_STRING (color, 1);
6679 if (w32_defined_color (f, XSTRING (color)->data, &foo, 0))
6681 Lisp_Object rgb[3];
6683 rgb[0] = make_number ((GetRValue (foo.pixel) << 8)
6684 | GetRValue (foo.pixel));
6685 rgb[1] = make_number ((GetGValue (foo.pixel) << 8)
6686 | GetGValue (foo.pixel));
6687 rgb[2] = make_number ((GetBValue (foo.pixel) << 8)
6688 | GetBValue (foo.pixel));
6689 return Flist (3, rgb);
6691 else
6692 return Qnil;
6695 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6696 "Return t if the X display supports color.\n\
6697 The optional argument DISPLAY specifies which display to ask about.\n\
6698 DISPLAY should be either a frame or a display name (a string).\n\
6699 If omitted or nil, that stands for the selected frame's display.")
6700 (display)
6701 Lisp_Object display;
6703 struct w32_display_info *dpyinfo = check_x_display_info (display);
6705 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6706 return Qnil;
6708 return Qt;
6711 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p, Sx_display_grayscale_p,
6712 0, 1, 0,
6713 "Return t if the X display supports shades of gray.\n\
6714 Note that color displays do support shades of gray.\n\
6715 The optional argument DISPLAY specifies which display to ask about.\n\
6716 DISPLAY should be either a frame or a display name (a string).\n\
6717 If omitted or nil, that stands for the selected frame's display.")
6718 (display)
6719 Lisp_Object display;
6721 struct w32_display_info *dpyinfo = check_x_display_info (display);
6723 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6724 return Qnil;
6726 return Qt;
6729 DEFUN ("x-display-pixel-width", Fx_display_pixel_width, Sx_display_pixel_width,
6730 0, 1, 0,
6731 "Returns the width in pixels of the X display DISPLAY.\n\
6732 The optional argument DISPLAY specifies which display to ask about.\n\
6733 DISPLAY should be either a frame or a display name (a string).\n\
6734 If omitted or nil, that stands for the selected frame's display.")
6735 (display)
6736 Lisp_Object display;
6738 struct w32_display_info *dpyinfo = check_x_display_info (display);
6740 return make_number (dpyinfo->width);
6743 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6744 Sx_display_pixel_height, 0, 1, 0,
6745 "Returns the height in pixels of the X display DISPLAY.\n\
6746 The optional argument DISPLAY specifies which display to ask about.\n\
6747 DISPLAY should be either a frame or a display name (a string).\n\
6748 If omitted or nil, that stands for the selected frame's display.")
6749 (display)
6750 Lisp_Object display;
6752 struct w32_display_info *dpyinfo = check_x_display_info (display);
6754 return make_number (dpyinfo->height);
6757 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6758 0, 1, 0,
6759 "Returns the number of bitplanes of the display DISPLAY.\n\
6760 The optional argument DISPLAY specifies which display to ask about.\n\
6761 DISPLAY should be either a frame or a display name (a string).\n\
6762 If omitted or nil, that stands for the selected frame's display.")
6763 (display)
6764 Lisp_Object display;
6766 struct w32_display_info *dpyinfo = check_x_display_info (display);
6768 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6771 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6772 0, 1, 0,
6773 "Returns the number of color cells of the display DISPLAY.\n\
6774 The optional argument DISPLAY specifies which display to ask about.\n\
6775 DISPLAY should be either a frame or a display name (a string).\n\
6776 If omitted or nil, that stands for the selected frame's display.")
6777 (display)
6778 Lisp_Object display;
6780 struct w32_display_info *dpyinfo = check_x_display_info (display);
6781 HDC hdc;
6782 int cap;
6784 hdc = GetDC (dpyinfo->root_window);
6785 if (dpyinfo->has_palette)
6786 cap = GetDeviceCaps (hdc,SIZEPALETTE);
6787 else
6788 cap = GetDeviceCaps (hdc,NUMCOLORS);
6790 ReleaseDC (dpyinfo->root_window, hdc);
6792 return make_number (cap);
6795 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6796 Sx_server_max_request_size,
6797 0, 1, 0,
6798 "Returns the maximum request size of the server of display DISPLAY.\n\
6799 The optional argument DISPLAY specifies which display to ask about.\n\
6800 DISPLAY should be either a frame or a display name (a string).\n\
6801 If omitted or nil, that stands for the selected frame's display.")
6802 (display)
6803 Lisp_Object display;
6805 struct w32_display_info *dpyinfo = check_x_display_info (display);
6807 return make_number (1);
6810 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6811 "Returns the vendor ID string of the W32 system (Microsoft).\n\
6812 The optional argument DISPLAY specifies which display to ask about.\n\
6813 DISPLAY should be either a frame or a display name (a string).\n\
6814 If omitted or nil, that stands for the selected frame's display.")
6815 (display)
6816 Lisp_Object display;
6818 struct w32_display_info *dpyinfo = check_x_display_info (display);
6819 char *vendor = "Microsoft Corp.";
6821 if (! vendor) vendor = "";
6822 return build_string (vendor);
6825 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6826 "Returns the version numbers of the server of display DISPLAY.\n\
6827 The value is a list of three integers: the major and minor\n\
6828 version numbers, and the vendor-specific release\n\
6829 number. See also the function `x-server-vendor'.\n\n\
6830 The optional argument DISPLAY specifies which display to ask about.\n\
6831 DISPLAY should be either a frame or a display name (a string).\n\
6832 If omitted or nil, that stands for the selected frame's display.")
6833 (display)
6834 Lisp_Object display;
6836 struct w32_display_info *dpyinfo = check_x_display_info (display);
6838 return Fcons (make_number (w32_major_version),
6839 Fcons (make_number (w32_minor_version), Qnil));
6842 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6843 "Returns the number of screens on the server of display DISPLAY.\n\
6844 The optional argument DISPLAY specifies which display to ask about.\n\
6845 DISPLAY should be either a frame or a display name (a string).\n\
6846 If omitted or nil, that stands for the selected frame's display.")
6847 (display)
6848 Lisp_Object display;
6850 struct w32_display_info *dpyinfo = check_x_display_info (display);
6852 return make_number (1);
6855 DEFUN ("x-display-mm-height", Fx_display_mm_height, Sx_display_mm_height, 0, 1, 0,
6856 "Returns the height in millimeters of the X display DISPLAY.\n\
6857 The optional argument DISPLAY specifies which display to ask about.\n\
6858 DISPLAY should be either a frame or a display name (a string).\n\
6859 If omitted or nil, that stands for the selected frame's display.")
6860 (display)
6861 Lisp_Object display;
6863 struct w32_display_info *dpyinfo = check_x_display_info (display);
6864 HDC hdc;
6865 int cap;
6867 hdc = GetDC (dpyinfo->root_window);
6869 cap = GetDeviceCaps (hdc, VERTSIZE);
6871 ReleaseDC (dpyinfo->root_window, hdc);
6873 return make_number (cap);
6876 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6877 "Returns the width in millimeters of the X display DISPLAY.\n\
6878 The optional argument DISPLAY specifies which display to ask about.\n\
6879 DISPLAY should be either a frame or a display name (a string).\n\
6880 If omitted or nil, that stands for the selected frame's display.")
6881 (display)
6882 Lisp_Object display;
6884 struct w32_display_info *dpyinfo = check_x_display_info (display);
6886 HDC hdc;
6887 int cap;
6889 hdc = GetDC (dpyinfo->root_window);
6891 cap = GetDeviceCaps (hdc, HORZSIZE);
6893 ReleaseDC (dpyinfo->root_window, hdc);
6895 return make_number (cap);
6898 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6899 Sx_display_backing_store, 0, 1, 0,
6900 "Returns an indication of whether display DISPLAY does backing store.\n\
6901 The value may be `always', `when-mapped', or `not-useful'.\n\
6902 The optional argument DISPLAY specifies which display to ask about.\n\
6903 DISPLAY should be either a frame or a display name (a string).\n\
6904 If omitted or nil, that stands for the selected frame's display.")
6905 (display)
6906 Lisp_Object display;
6908 return intern ("not-useful");
6911 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6912 Sx_display_visual_class, 0, 1, 0,
6913 "Returns the visual class of the display DISPLAY.\n\
6914 The value is one of the symbols `static-gray', `gray-scale',\n\
6915 `static-color', `pseudo-color', `true-color', or `direct-color'.\n\n\
6916 The optional argument DISPLAY specifies which display to ask about.\n\
6917 DISPLAY should be either a frame or a display name (a string).\n\
6918 If omitted or nil, that stands for the selected frame's display.")
6919 (display)
6920 Lisp_Object display;
6922 struct w32_display_info *dpyinfo = check_x_display_info (display);
6924 #if 0
6925 switch (dpyinfo->visual->class)
6927 case StaticGray: return (intern ("static-gray"));
6928 case GrayScale: return (intern ("gray-scale"));
6929 case StaticColor: return (intern ("static-color"));
6930 case PseudoColor: return (intern ("pseudo-color"));
6931 case TrueColor: return (intern ("true-color"));
6932 case DirectColor: return (intern ("direct-color"));
6933 default:
6934 error ("Display has an unknown visual class");
6936 #endif
6938 error ("Display has an unknown visual class");
6941 DEFUN ("x-display-save-under", Fx_display_save_under,
6942 Sx_display_save_under, 0, 1, 0,
6943 "Returns t if the display DISPLAY supports the save-under feature.\n\
6944 The optional argument DISPLAY specifies which display to ask about.\n\
6945 DISPLAY should be either a frame or a display name (a string).\n\
6946 If omitted or nil, that stands for the selected frame's display.")
6947 (display)
6948 Lisp_Object display;
6950 struct w32_display_info *dpyinfo = check_x_display_info (display);
6952 return Qnil;
6956 x_pixel_width (f)
6957 register struct frame *f;
6959 return PIXEL_WIDTH (f);
6963 x_pixel_height (f)
6964 register struct frame *f;
6966 return PIXEL_HEIGHT (f);
6970 x_char_width (f)
6971 register struct frame *f;
6973 return FONT_WIDTH (f->output_data.w32->font);
6977 x_char_height (f)
6978 register struct frame *f;
6980 return f->output_data.w32->line_height;
6984 x_screen_planes (f)
6985 register struct frame *f;
6987 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
6990 /* Return the display structure for the display named NAME.
6991 Open a new connection if necessary. */
6993 struct w32_display_info *
6994 x_display_info_for_name (name)
6995 Lisp_Object name;
6997 Lisp_Object names;
6998 struct w32_display_info *dpyinfo;
7000 CHECK_STRING (name, 0);
7002 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
7003 dpyinfo;
7004 dpyinfo = dpyinfo->next, names = XCDR (names))
7006 Lisp_Object tem;
7007 tem = Fstring_equal (XCAR (XCAR (names)), name);
7008 if (!NILP (tem))
7009 return dpyinfo;
7012 /* Use this general default value to start with. */
7013 Vx_resource_name = Vinvocation_name;
7015 validate_x_resource_name ();
7017 dpyinfo = w32_term_init (name, (unsigned char *)0,
7018 (char *) XSTRING (Vx_resource_name)->data);
7020 if (dpyinfo == 0)
7021 error ("Cannot connect to server %s", XSTRING (name)->data);
7023 w32_in_use = 1;
7024 XSETFASTINT (Vwindow_system_version, 3);
7026 return dpyinfo;
7029 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
7030 1, 3, 0, "Open a connection to a server.\n\
7031 DISPLAY is the name of the display to connect to.\n\
7032 Optional second arg XRM-STRING is a string of resources in xrdb format.\n\
7033 If the optional third arg MUST-SUCCEED is non-nil,\n\
7034 terminate Emacs if we can't open the connection.")
7035 (display, xrm_string, must_succeed)
7036 Lisp_Object display, xrm_string, must_succeed;
7038 unsigned char *xrm_option;
7039 struct w32_display_info *dpyinfo;
7041 CHECK_STRING (display, 0);
7042 if (! NILP (xrm_string))
7043 CHECK_STRING (xrm_string, 1);
7045 if (! EQ (Vwindow_system, intern ("w32")))
7046 error ("Not using Microsoft Windows");
7048 /* Allow color mapping to be defined externally; first look in user's
7049 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
7051 Lisp_Object color_file;
7052 struct gcpro gcpro1;
7054 color_file = build_string("~/rgb.txt");
7056 GCPRO1 (color_file);
7058 if (NILP (Ffile_readable_p (color_file)))
7059 color_file =
7060 Fexpand_file_name (build_string ("rgb.txt"),
7061 Fsymbol_value (intern ("data-directory")));
7063 Vw32_color_map = Fw32_load_color_file (color_file);
7065 UNGCPRO;
7067 if (NILP (Vw32_color_map))
7068 Vw32_color_map = Fw32_default_color_map ();
7070 if (! NILP (xrm_string))
7071 xrm_option = (unsigned char *) XSTRING (xrm_string)->data;
7072 else
7073 xrm_option = (unsigned char *) 0;
7075 /* Use this general default value to start with. */
7076 /* First remove .exe suffix from invocation-name - it looks ugly. */
7078 char basename[ MAX_PATH ], *str;
7080 strcpy (basename, XSTRING (Vinvocation_name)->data);
7081 str = strrchr (basename, '.');
7082 if (str) *str = 0;
7083 Vinvocation_name = build_string (basename);
7085 Vx_resource_name = Vinvocation_name;
7087 validate_x_resource_name ();
7089 /* This is what opens the connection and sets x_current_display.
7090 This also initializes many symbols, such as those used for input. */
7091 dpyinfo = w32_term_init (display, xrm_option,
7092 (char *) XSTRING (Vx_resource_name)->data);
7094 if (dpyinfo == 0)
7096 if (!NILP (must_succeed))
7097 fatal ("Cannot connect to server %s.\n",
7098 XSTRING (display)->data);
7099 else
7100 error ("Cannot connect to server %s", XSTRING (display)->data);
7103 w32_in_use = 1;
7105 XSETFASTINT (Vwindow_system_version, 3);
7106 return Qnil;
7109 DEFUN ("x-close-connection", Fx_close_connection,
7110 Sx_close_connection, 1, 1, 0,
7111 "Close the connection to DISPLAY's server.\n\
7112 For DISPLAY, specify either a frame or a display name (a string).\n\
7113 If DISPLAY is nil, that stands for the selected frame's display.")
7114 (display)
7115 Lisp_Object display;
7117 struct w32_display_info *dpyinfo = check_x_display_info (display);
7118 int i;
7120 if (dpyinfo->reference_count > 0)
7121 error ("Display still has frames on it");
7123 BLOCK_INPUT;
7124 /* Free the fonts in the font table. */
7125 for (i = 0; i < dpyinfo->n_fonts; i++)
7126 if (dpyinfo->font_table[i].name)
7128 xfree (dpyinfo->font_table[i].name);
7129 /* Don't free the full_name string;
7130 it is always shared with something else. */
7131 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
7133 x_destroy_all_bitmaps (dpyinfo);
7135 x_delete_display (dpyinfo);
7136 UNBLOCK_INPUT;
7138 return Qnil;
7141 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
7142 "Return the list of display names that Emacs has connections to.")
7145 Lisp_Object tail, result;
7147 result = Qnil;
7148 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
7149 result = Fcons (XCAR (XCAR (tail)), result);
7151 return result;
7154 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
7155 "If ON is non-nil, report errors as soon as the erring request is made.\n\
7156 If ON is nil, allow buffering of requests.\n\
7157 This is a noop on W32 systems.\n\
7158 The optional second argument DISPLAY specifies which display to act on.\n\
7159 DISPLAY should be either a frame or a display name (a string).\n\
7160 If DISPLAY is omitted or nil, that stands for the selected frame's display.")
7161 (on, display)
7162 Lisp_Object display, on;
7164 struct w32_display_info *dpyinfo = check_x_display_info (display);
7166 return Qnil;
7171 /***********************************************************************
7172 Image types
7173 ***********************************************************************/
7175 /* Value is the number of elements of vector VECTOR. */
7177 #define DIM(VECTOR) (sizeof (VECTOR) / sizeof *(VECTOR))
7179 /* List of supported image types. Use define_image_type to add new
7180 types. Use lookup_image_type to find a type for a given symbol. */
7182 static struct image_type *image_types;
7184 /* A list of symbols, one for each supported image type. */
7186 Lisp_Object Vimage_types;
7188 /* The symbol `image' which is the car of the lists used to represent
7189 images in Lisp. */
7191 extern Lisp_Object Qimage;
7193 /* The symbol `xbm' which is used as the type symbol for XBM images. */
7195 Lisp_Object Qxbm;
7197 /* Keywords. */
7199 Lisp_Object QCtype, QCdata, QCascent, QCmargin, QCrelief;
7200 extern Lisp_Object QCwidth, QCheight, QCforeground, QCbackground, QCfile;
7201 Lisp_Object QCalgorithm, QCcolor_symbols, QCheuristic_mask;
7202 extern Lisp_Object QCindex;
7204 /* Other symbols. */
7206 Lisp_Object Qlaplace;
7208 /* Time in seconds after which images should be removed from the cache
7209 if not displayed. */
7211 Lisp_Object Vimage_cache_eviction_delay;
7213 /* Function prototypes. */
7215 static void define_image_type P_ ((struct image_type *type));
7216 static struct image_type *lookup_image_type P_ ((Lisp_Object symbol));
7217 static void image_error P_ ((char *format, Lisp_Object, Lisp_Object));
7218 static void x_laplace P_ ((struct frame *, struct image *));
7219 static int x_build_heuristic_mask P_ ((struct frame *, struct image *,
7220 Lisp_Object));
7222 /* Define a new image type from TYPE. This adds a copy of TYPE to
7223 image_types and adds the symbol *TYPE->type to Vimage_types. */
7225 static void
7226 define_image_type (type)
7227 struct image_type *type;
7229 /* Make a copy of TYPE to avoid a bus error in a dumped Emacs.
7230 The initialized data segment is read-only. */
7231 struct image_type *p = (struct image_type *) xmalloc (sizeof *p);
7232 bcopy (type, p, sizeof *p);
7233 p->next = image_types;
7234 image_types = p;
7235 Vimage_types = Fcons (*p->type, Vimage_types);
7239 /* Look up image type SYMBOL, and return a pointer to its image_type
7240 structure. Value is null if SYMBOL is not a known image type. */
7242 static INLINE struct image_type *
7243 lookup_image_type (symbol)
7244 Lisp_Object symbol;
7246 struct image_type *type;
7248 for (type = image_types; type; type = type->next)
7249 if (EQ (symbol, *type->type))
7250 break;
7252 return type;
7256 /* Value is non-zero if OBJECT is a valid Lisp image specification. A
7257 valid image specification is a list whose car is the symbol
7258 `image', and whose rest is a property list. The property list must
7259 contain a value for key `:type'. That value must be the name of a
7260 supported image type. The rest of the property list depends on the
7261 image type. */
7264 valid_image_p (object)
7265 Lisp_Object object;
7267 int valid_p = 0;
7269 if (CONSP (object) && EQ (XCAR (object), Qimage))
7271 Lisp_Object symbol = Fplist_get (XCDR (object), QCtype);
7272 struct image_type *type = lookup_image_type (symbol);
7274 if (type)
7275 valid_p = type->valid_p (object);
7278 return valid_p;
7282 /* Log error message with format string FORMAT and argument ARG.
7283 Signaling an error, e.g. when an image cannot be loaded, is not a
7284 good idea because this would interrupt redisplay, and the error
7285 message display would lead to another redisplay. This function
7286 therefore simply displays a message. */
7288 static void
7289 image_error (format, arg1, arg2)
7290 char *format;
7291 Lisp_Object arg1, arg2;
7293 add_to_log (format, arg1, arg2);
7298 /***********************************************************************
7299 Image specifications
7300 ***********************************************************************/
7302 enum image_value_type
7304 IMAGE_DONT_CHECK_VALUE_TYPE,
7305 IMAGE_STRING_VALUE,
7306 IMAGE_SYMBOL_VALUE,
7307 IMAGE_POSITIVE_INTEGER_VALUE,
7308 IMAGE_NON_NEGATIVE_INTEGER_VALUE,
7309 IMAGE_INTEGER_VALUE,
7310 IMAGE_FUNCTION_VALUE,
7311 IMAGE_NUMBER_VALUE,
7312 IMAGE_BOOL_VALUE
7315 /* Structure used when parsing image specifications. */
7317 struct image_keyword
7319 /* Name of keyword. */
7320 char *name;
7322 /* The type of value allowed. */
7323 enum image_value_type type;
7325 /* Non-zero means key must be present. */
7326 int mandatory_p;
7328 /* Used to recognize duplicate keywords in a property list. */
7329 int count;
7331 /* The value that was found. */
7332 Lisp_Object value;
7336 static int parse_image_spec P_ ((Lisp_Object, struct image_keyword *,
7337 int, Lisp_Object));
7338 static Lisp_Object image_spec_value P_ ((Lisp_Object, Lisp_Object, int *));
7341 /* Parse image spec SPEC according to KEYWORDS. A valid image spec
7342 has the format (image KEYWORD VALUE ...). One of the keyword/
7343 value pairs must be `:type TYPE'. KEYWORDS is a vector of
7344 image_keywords structures of size NKEYWORDS describing other
7345 allowed keyword/value pairs. Value is non-zero if SPEC is valid. */
7347 static int
7348 parse_image_spec (spec, keywords, nkeywords, type)
7349 Lisp_Object spec;
7350 struct image_keyword *keywords;
7351 int nkeywords;
7352 Lisp_Object type;
7354 int i;
7355 Lisp_Object plist;
7357 if (!CONSP (spec) || !EQ (XCAR (spec), Qimage))
7358 return 0;
7360 plist = XCDR (spec);
7361 while (CONSP (plist))
7363 Lisp_Object key, value;
7365 /* First element of a pair must be a symbol. */
7366 key = XCAR (plist);
7367 plist = XCDR (plist);
7368 if (!SYMBOLP (key))
7369 return 0;
7371 /* There must follow a value. */
7372 if (!CONSP (plist))
7373 return 0;
7374 value = XCAR (plist);
7375 plist = XCDR (plist);
7377 /* Find key in KEYWORDS. Error if not found. */
7378 for (i = 0; i < nkeywords; ++i)
7379 if (strcmp (keywords[i].name, XSYMBOL (key)->name->data) == 0)
7380 break;
7382 if (i == nkeywords)
7383 continue;
7385 /* Record that we recognized the keyword. If a keywords
7386 was found more than once, it's an error. */
7387 keywords[i].value = value;
7388 ++keywords[i].count;
7390 if (keywords[i].count > 1)
7391 return 0;
7393 /* Check type of value against allowed type. */
7394 switch (keywords[i].type)
7396 case IMAGE_STRING_VALUE:
7397 if (!STRINGP (value))
7398 return 0;
7399 break;
7401 case IMAGE_SYMBOL_VALUE:
7402 if (!SYMBOLP (value))
7403 return 0;
7404 break;
7406 case IMAGE_POSITIVE_INTEGER_VALUE:
7407 if (!INTEGERP (value) || XINT (value) <= 0)
7408 return 0;
7409 break;
7411 case IMAGE_NON_NEGATIVE_INTEGER_VALUE:
7412 if (!INTEGERP (value) || XINT (value) < 0)
7413 return 0;
7414 break;
7416 case IMAGE_DONT_CHECK_VALUE_TYPE:
7417 break;
7419 case IMAGE_FUNCTION_VALUE:
7420 value = indirect_function (value);
7421 if (SUBRP (value)
7422 || COMPILEDP (value)
7423 || (CONSP (value) && EQ (XCAR (value), Qlambda)))
7424 break;
7425 return 0;
7427 case IMAGE_NUMBER_VALUE:
7428 if (!INTEGERP (value) && !FLOATP (value))
7429 return 0;
7430 break;
7432 case IMAGE_INTEGER_VALUE:
7433 if (!INTEGERP (value))
7434 return 0;
7435 break;
7437 case IMAGE_BOOL_VALUE:
7438 if (!NILP (value) && !EQ (value, Qt))
7439 return 0;
7440 break;
7442 default:
7443 abort ();
7444 break;
7447 if (EQ (key, QCtype) && !EQ (type, value))
7448 return 0;
7451 /* Check that all mandatory fields are present. */
7452 for (i = 0; i < nkeywords; ++i)
7453 if (keywords[i].mandatory_p && keywords[i].count == 0)
7454 return 0;
7456 return NILP (plist);
7460 /* Return the value of KEY in image specification SPEC. Value is nil
7461 if KEY is not present in SPEC. if FOUND is not null, set *FOUND
7462 to 1 if KEY was found in SPEC, set it to 0 otherwise. */
7464 static Lisp_Object
7465 image_spec_value (spec, key, found)
7466 Lisp_Object spec, key;
7467 int *found;
7469 Lisp_Object tail;
7471 xassert (valid_image_p (spec));
7473 for (tail = XCDR (spec);
7474 CONSP (tail) && CONSP (XCDR (tail));
7475 tail = XCDR (XCDR (tail)))
7477 if (EQ (XCAR (tail), key))
7479 if (found)
7480 *found = 1;
7481 return XCAR (XCDR (tail));
7485 if (found)
7486 *found = 0;
7487 return Qnil;
7493 /***********************************************************************
7494 Image type independent image structures
7495 ***********************************************************************/
7497 static struct image *make_image P_ ((Lisp_Object spec, unsigned hash));
7498 static void free_image P_ ((struct frame *f, struct image *img));
7501 /* Allocate and return a new image structure for image specification
7502 SPEC. SPEC has a hash value of HASH. */
7504 static struct image *
7505 make_image (spec, hash)
7506 Lisp_Object spec;
7507 unsigned hash;
7509 struct image *img = (struct image *) xmalloc (sizeof *img);
7511 xassert (valid_image_p (spec));
7512 bzero (img, sizeof *img);
7513 img->type = lookup_image_type (image_spec_value (spec, QCtype, NULL));
7514 xassert (img->type != NULL);
7515 img->spec = spec;
7516 img->data.lisp_val = Qnil;
7517 img->ascent = DEFAULT_IMAGE_ASCENT;
7518 img->hash = hash;
7519 return img;
7523 /* Free image IMG which was used on frame F, including its resources. */
7525 static void
7526 free_image (f, img)
7527 struct frame *f;
7528 struct image *img;
7530 if (img)
7532 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7534 /* Remove IMG from the hash table of its cache. */
7535 if (img->prev)
7536 img->prev->next = img->next;
7537 else
7538 c->buckets[img->hash % IMAGE_CACHE_BUCKETS_SIZE] = img->next;
7540 if (img->next)
7541 img->next->prev = img->prev;
7543 c->images[img->id] = NULL;
7545 /* Free resources, then free IMG. */
7546 img->type->free (f, img);
7547 xfree (img);
7552 /* Prepare image IMG for display on frame F. Must be called before
7553 drawing an image. */
7555 void
7556 prepare_image_for_display (f, img)
7557 struct frame *f;
7558 struct image *img;
7560 EMACS_TIME t;
7562 /* We're about to display IMG, so set its timestamp to `now'. */
7563 EMACS_GET_TIME (t);
7564 img->timestamp = EMACS_SECS (t);
7566 /* If IMG doesn't have a pixmap yet, load it now, using the image
7567 type dependent loader function. */
7568 if (img->pixmap == 0 && !img->load_failed_p)
7569 img->load_failed_p = img->type->load (f, img) == 0;
7574 /***********************************************************************
7575 Helper functions for X image types
7576 ***********************************************************************/
7578 static void x_clear_image P_ ((struct frame *f, struct image *img));
7579 static unsigned long x_alloc_image_color P_ ((struct frame *f,
7580 struct image *img,
7581 Lisp_Object color_name,
7582 unsigned long dflt));
7584 /* Free X resources of image IMG which is used on frame F. */
7586 static void
7587 x_clear_image (f, img)
7588 struct frame *f;
7589 struct image *img;
7591 #if 0 /* NTEMACS_TODO: W32 image support */
7593 if (img->pixmap)
7595 BLOCK_INPUT;
7596 XFreePixmap (NULL, img->pixmap);
7597 img->pixmap = 0;
7598 UNBLOCK_INPUT;
7601 if (img->ncolors)
7603 int class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
7605 /* If display has an immutable color map, freeing colors is not
7606 necessary and some servers don't allow it. So don't do it. */
7607 if (class != StaticColor
7608 && class != StaticGray
7609 && class != TrueColor)
7611 Colormap cmap;
7612 BLOCK_INPUT;
7613 cmap = DefaultColormapOfScreen (FRAME_W32_DISPLAY_INFO (f)->screen);
7614 XFreeColors (FRAME_W32_DISPLAY (f), cmap, img->colors,
7615 img->ncolors, 0);
7616 UNBLOCK_INPUT;
7619 xfree (img->colors);
7620 img->colors = NULL;
7621 img->ncolors = 0;
7623 #endif
7627 /* Allocate color COLOR_NAME for image IMG on frame F. If color
7628 cannot be allocated, use DFLT. Add a newly allocated color to
7629 IMG->colors, so that it can be freed again. Value is the pixel
7630 color. */
7632 static unsigned long
7633 x_alloc_image_color (f, img, color_name, dflt)
7634 struct frame *f;
7635 struct image *img;
7636 Lisp_Object color_name;
7637 unsigned long dflt;
7639 #if 0 /* NTEMACS_TODO: allocing colors. */
7640 XColor color;
7641 unsigned long result;
7643 xassert (STRINGP (color_name));
7645 if (w32_defined_color (f, XSTRING (color_name)->data, &color, 1))
7647 /* This isn't called frequently so we get away with simply
7648 reallocating the color vector to the needed size, here. */
7649 ++img->ncolors;
7650 img->colors =
7651 (unsigned long *) xrealloc (img->colors,
7652 img->ncolors * sizeof *img->colors);
7653 img->colors[img->ncolors - 1] = color.pixel;
7654 result = color.pixel;
7656 else
7657 result = dflt;
7658 return result;
7659 #endif
7660 return 0;
7665 /***********************************************************************
7666 Image Cache
7667 ***********************************************************************/
7669 static void cache_image P_ ((struct frame *f, struct image *img));
7672 /* Return a new, initialized image cache that is allocated from the
7673 heap. Call free_image_cache to free an image cache. */
7675 struct image_cache *
7676 make_image_cache ()
7678 struct image_cache *c = (struct image_cache *) xmalloc (sizeof *c);
7679 int size;
7681 bzero (c, sizeof *c);
7682 c->size = 50;
7683 c->images = (struct image **) xmalloc (c->size * sizeof *c->images);
7684 size = IMAGE_CACHE_BUCKETS_SIZE * sizeof *c->buckets;
7685 c->buckets = (struct image **) xmalloc (size);
7686 bzero (c->buckets, size);
7687 return c;
7691 /* Free image cache of frame F. Be aware that X frames share images
7692 caches. */
7694 void
7695 free_image_cache (f)
7696 struct frame *f;
7698 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7699 if (c)
7701 int i;
7703 /* Cache should not be referenced by any frame when freed. */
7704 xassert (c->refcount == 0);
7706 for (i = 0; i < c->used; ++i)
7707 free_image (f, c->images[i]);
7708 xfree (c->images);
7709 xfree (c);
7710 xfree (c->buckets);
7711 FRAME_X_IMAGE_CACHE (f) = NULL;
7716 /* Clear image cache of frame F. FORCE_P non-zero means free all
7717 images. FORCE_P zero means clear only images that haven't been
7718 displayed for some time. Should be called from time to time to
7719 reduce the number of loaded images. If image-cache-eveiction-delay
7720 is non-nil, this frees images in the cache which weren't displayed for
7721 at least that many seconds. */
7723 void
7724 clear_image_cache (f, force_p)
7725 struct frame *f;
7726 int force_p;
7728 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7730 if (c && INTEGERP (Vimage_cache_eviction_delay))
7732 EMACS_TIME t;
7733 unsigned long old;
7734 int i, any_freed_p = 0;
7736 EMACS_GET_TIME (t);
7737 old = EMACS_SECS (t) - XFASTINT (Vimage_cache_eviction_delay);
7739 for (i = 0; i < c->used; ++i)
7741 struct image *img = c->images[i];
7742 if (img != NULL
7743 && (force_p
7744 || (img->timestamp > old)))
7746 free_image (f, img);
7747 any_freed_p = 1;
7751 /* We may be clearing the image cache because, for example,
7752 Emacs was iconified for a longer period of time. In that
7753 case, current matrices may still contain references to
7754 images freed above. So, clear these matrices. */
7755 if (any_freed_p)
7757 clear_current_matrices (f);
7758 ++windows_or_buffers_changed;
7764 DEFUN ("clear-image-cache", Fclear_image_cache, Sclear_image_cache,
7765 0, 1, 0,
7766 "Clear the image cache of FRAME.\n\
7767 FRAME nil or omitted means use the selected frame.\n\
7768 FRAME t means clear the image caches of all frames.")
7769 (frame)
7770 Lisp_Object frame;
7772 if (EQ (frame, Qt))
7774 Lisp_Object tail;
7776 FOR_EACH_FRAME (tail, frame)
7777 if (FRAME_W32_P (XFRAME (frame)))
7778 clear_image_cache (XFRAME (frame), 1);
7780 else
7781 clear_image_cache (check_x_frame (frame), 1);
7783 return Qnil;
7787 /* Return the id of image with Lisp specification SPEC on frame F.
7788 SPEC must be a valid Lisp image specification (see valid_image_p). */
7791 lookup_image (f, spec)
7792 struct frame *f;
7793 Lisp_Object spec;
7795 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7796 struct image *img;
7797 int i;
7798 unsigned hash;
7799 struct gcpro gcpro1;
7800 EMACS_TIME now;
7802 /* F must be a window-system frame, and SPEC must be a valid image
7803 specification. */
7804 xassert (FRAME_WINDOW_P (f));
7805 xassert (valid_image_p (spec));
7807 GCPRO1 (spec);
7809 /* Look up SPEC in the hash table of the image cache. */
7810 hash = sxhash (spec, 0);
7811 i = hash % IMAGE_CACHE_BUCKETS_SIZE;
7813 for (img = c->buckets[i]; img; img = img->next)
7814 if (img->hash == hash && !NILP (Fequal (img->spec, spec)))
7815 break;
7817 /* If not found, create a new image and cache it. */
7818 if (img == NULL)
7820 img = make_image (spec, hash);
7821 cache_image (f, img);
7822 img->load_failed_p = img->type->load (f, img) == 0;
7823 xassert (!interrupt_input_blocked);
7825 /* If we can't load the image, and we don't have a width and
7826 height, use some arbitrary width and height so that we can
7827 draw a rectangle for it. */
7828 if (img->load_failed_p)
7830 Lisp_Object value;
7832 value = image_spec_value (spec, QCwidth, NULL);
7833 img->width = (INTEGERP (value)
7834 ? XFASTINT (value) : DEFAULT_IMAGE_WIDTH);
7835 value = image_spec_value (spec, QCheight, NULL);
7836 img->height = (INTEGERP (value)
7837 ? XFASTINT (value) : DEFAULT_IMAGE_HEIGHT);
7839 else
7841 /* Handle image type independent image attributes
7842 `:ascent PERCENT', `:margin MARGIN', `:relief RELIEF'. */
7843 Lisp_Object ascent, margin, relief, algorithm, heuristic_mask;
7844 Lisp_Object file;
7846 ascent = image_spec_value (spec, QCascent, NULL);
7847 if (INTEGERP (ascent))
7848 img->ascent = XFASTINT (ascent);
7850 margin = image_spec_value (spec, QCmargin, NULL);
7851 if (INTEGERP (margin) && XINT (margin) >= 0)
7852 img->margin = XFASTINT (margin);
7854 relief = image_spec_value (spec, QCrelief, NULL);
7855 if (INTEGERP (relief))
7857 img->relief = XINT (relief);
7858 img->margin += abs (img->relief);
7861 /* Should we apply a Laplace edge-detection algorithm? */
7862 algorithm = image_spec_value (spec, QCalgorithm, NULL);
7863 if (img->pixmap && EQ (algorithm, Qlaplace))
7864 x_laplace (f, img);
7866 /* Should we built a mask heuristically? */
7867 heuristic_mask = image_spec_value (spec, QCheuristic_mask, NULL);
7868 if (img->pixmap && !img->mask && !NILP (heuristic_mask))
7869 x_build_heuristic_mask (f, img, heuristic_mask);
7873 /* We're using IMG, so set its timestamp to `now'. */
7874 EMACS_GET_TIME (now);
7875 img->timestamp = EMACS_SECS (now);
7877 UNGCPRO;
7879 /* Value is the image id. */
7880 return img->id;
7884 /* Cache image IMG in the image cache of frame F. */
7886 static void
7887 cache_image (f, img)
7888 struct frame *f;
7889 struct image *img;
7891 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7892 int i;
7894 /* Find a free slot in c->images. */
7895 for (i = 0; i < c->used; ++i)
7896 if (c->images[i] == NULL)
7897 break;
7899 /* If no free slot found, maybe enlarge c->images. */
7900 if (i == c->used && c->used == c->size)
7902 c->size *= 2;
7903 c->images = (struct image **) xrealloc (c->images,
7904 c->size * sizeof *c->images);
7907 /* Add IMG to c->images, and assign IMG an id. */
7908 c->images[i] = img;
7909 img->id = i;
7910 if (i == c->used)
7911 ++c->used;
7913 /* Add IMG to the cache's hash table. */
7914 i = img->hash % IMAGE_CACHE_BUCKETS_SIZE;
7915 img->next = c->buckets[i];
7916 if (img->next)
7917 img->next->prev = img;
7918 img->prev = NULL;
7919 c->buckets[i] = img;
7923 /* Call FN on every image in the image cache of frame F. Used to mark
7924 Lisp Objects in the image cache. */
7926 void
7927 forall_images_in_image_cache (f, fn)
7928 struct frame *f;
7929 void (*fn) P_ ((struct image *img));
7931 if (FRAME_LIVE_P (f) && FRAME_W32_P (f))
7933 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
7934 if (c)
7936 int i;
7937 for (i = 0; i < c->used; ++i)
7938 if (c->images[i])
7939 fn (c->images[i]);
7946 /***********************************************************************
7947 W32 support code
7948 ***********************************************************************/
7950 #if 0 /* NTEMACS_TODO: W32 specific image code. */
7952 static int x_create_x_image_and_pixmap P_ ((struct frame *, int, int, int,
7953 XImage **, Pixmap *));
7954 static void x_destroy_x_image P_ ((XImage *));
7955 static void x_put_x_image P_ ((struct frame *, XImage *, Pixmap, int, int));
7958 /* Create an XImage and a pixmap of size WIDTH x HEIGHT for use on
7959 frame F. Set *XIMG and *PIXMAP to the XImage and Pixmap created.
7960 Set (*XIMG)->data to a raster of WIDTH x HEIGHT pixels allocated
7961 via xmalloc. Print error messages via image_error if an error
7962 occurs. Value is non-zero if successful. */
7964 static int
7965 x_create_x_image_and_pixmap (f, width, height, depth, ximg, pixmap)
7966 struct frame *f;
7967 int width, height, depth;
7968 XImage **ximg;
7969 Pixmap *pixmap;
7971 #if 0 /* NTEMACS_TODO: Image support for W32 */
7972 Display *display = FRAME_W32_DISPLAY (f);
7973 Screen *screen = FRAME_X_SCREEN (f);
7974 Window window = FRAME_W32_WINDOW (f);
7976 xassert (interrupt_input_blocked);
7978 if (depth <= 0)
7979 depth = DefaultDepthOfScreen (screen);
7980 *ximg = XCreateImage (display, DefaultVisualOfScreen (screen),
7981 depth, ZPixmap, 0, NULL, width, height,
7982 depth > 16 ? 32 : depth > 8 ? 16 : 8, 0);
7983 if (*ximg == NULL)
7985 image_error ("Unable to allocate X image", Qnil, Qnil);
7986 return 0;
7989 /* Allocate image raster. */
7990 (*ximg)->data = (char *) xmalloc ((*ximg)->bytes_per_line * height);
7992 /* Allocate a pixmap of the same size. */
7993 *pixmap = XCreatePixmap (display, window, width, height, depth);
7994 if (*pixmap == 0)
7996 x_destroy_x_image (*ximg);
7997 *ximg = NULL;
7998 image_error ("Unable to create X pixmap", Qnil, Qnil);
7999 return 0;
8001 #endif
8002 return 1;
8006 /* Destroy XImage XIMG. Free XIMG->data. */
8008 static void
8009 x_destroy_x_image (ximg)
8010 XImage *ximg;
8012 xassert (interrupt_input_blocked);
8013 if (ximg)
8015 xfree (ximg->data);
8016 ximg->data = NULL;
8017 XDestroyImage (ximg);
8022 /* Put XImage XIMG into pixmap PIXMAP on frame F. WIDTH and HEIGHT
8023 are width and height of both the image and pixmap. */
8025 static void
8026 x_put_x_image (f, ximg, pixmap, width, height)
8027 struct frame *f;
8028 XImage *ximg;
8029 Pixmap pixmap;
8031 GC gc;
8033 xassert (interrupt_input_blocked);
8034 gc = XCreateGC (NULL, pixmap, 0, NULL);
8035 XPutImage (NULL, pixmap, gc, ximg, 0, 0, 0, 0, width, height);
8036 XFreeGC (NULL, gc);
8039 #endif
8042 /***********************************************************************
8043 Searching files
8044 ***********************************************************************/
8046 static Lisp_Object x_find_image_file P_ ((Lisp_Object));
8048 /* Find image file FILE. Look in data-directory, then
8049 x-bitmap-file-path. Value is the full name of the file found, or
8050 nil if not found. */
8052 static Lisp_Object
8053 x_find_image_file (file)
8054 Lisp_Object file;
8056 Lisp_Object file_found, search_path;
8057 struct gcpro gcpro1, gcpro2;
8058 int fd;
8060 file_found = Qnil;
8061 search_path = Fcons (Vdata_directory, Vx_bitmap_file_path);
8062 GCPRO2 (file_found, search_path);
8064 /* Try to find FILE in data-directory, then x-bitmap-file-path. */
8065 fd = openp (search_path, file, "", &file_found, 0);
8067 if (fd < 0)
8068 file_found = Qnil;
8069 else
8070 close (fd);
8072 UNGCPRO;
8073 return file_found;
8078 /***********************************************************************
8079 XBM images
8080 ***********************************************************************/
8082 static int xbm_load P_ ((struct frame *f, struct image *img));
8083 static int xbm_load_image_from_file P_ ((struct frame *f, struct image *img,
8084 Lisp_Object file));
8085 static int xbm_image_p P_ ((Lisp_Object object));
8086 static int xbm_read_bitmap_file_data P_ ((char *, int *, int *,
8087 unsigned char **));
8090 /* Indices of image specification fields in xbm_format, below. */
8092 enum xbm_keyword_index
8094 XBM_TYPE,
8095 XBM_FILE,
8096 XBM_WIDTH,
8097 XBM_HEIGHT,
8098 XBM_DATA,
8099 XBM_FOREGROUND,
8100 XBM_BACKGROUND,
8101 XBM_ASCENT,
8102 XBM_MARGIN,
8103 XBM_RELIEF,
8104 XBM_ALGORITHM,
8105 XBM_HEURISTIC_MASK,
8106 XBM_LAST
8109 /* Vector of image_keyword structures describing the format
8110 of valid XBM image specifications. */
8112 static struct image_keyword xbm_format[XBM_LAST] =
8114 {":type", IMAGE_SYMBOL_VALUE, 1},
8115 {":file", IMAGE_STRING_VALUE, 0},
8116 {":width", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8117 {":height", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8118 {":data", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8119 {":foreground", IMAGE_STRING_VALUE, 0},
8120 {":background", IMAGE_STRING_VALUE, 0},
8121 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8122 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8123 {":relief", IMAGE_INTEGER_VALUE, 0},
8124 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8125 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8128 /* Structure describing the image type XBM. */
8130 static struct image_type xbm_type =
8132 &Qxbm,
8133 xbm_image_p,
8134 xbm_load,
8135 x_clear_image,
8136 NULL
8139 /* Tokens returned from xbm_scan. */
8141 enum xbm_token
8143 XBM_TK_IDENT = 256,
8144 XBM_TK_NUMBER
8148 /* Return non-zero if OBJECT is a valid XBM-type image specification.
8149 A valid specification is a list starting with the symbol `image'
8150 The rest of the list is a property list which must contain an
8151 entry `:type xbm..
8153 If the specification specifies a file to load, it must contain
8154 an entry `:file FILENAME' where FILENAME is a string.
8156 If the specification is for a bitmap loaded from memory it must
8157 contain `:width WIDTH', `:height HEIGHT', and `:data DATA', where
8158 WIDTH and HEIGHT are integers > 0. DATA may be:
8160 1. a string large enough to hold the bitmap data, i.e. it must
8161 have a size >= (WIDTH + 7) / 8 * HEIGHT
8163 2. a bool-vector of size >= WIDTH * HEIGHT
8165 3. a vector of strings or bool-vectors, one for each line of the
8166 bitmap.
8168 Both the file and data forms may contain the additional entries
8169 `:background COLOR' and `:foreground COLOR'. If not present,
8170 foreground and background of the frame on which the image is
8171 displayed, is used. */
8173 static int
8174 xbm_image_p (object)
8175 Lisp_Object object;
8177 struct image_keyword kw[XBM_LAST];
8179 bcopy (xbm_format, kw, sizeof kw);
8180 if (!parse_image_spec (object, kw, XBM_LAST, Qxbm))
8181 return 0;
8183 xassert (EQ (kw[XBM_TYPE].value, Qxbm));
8185 if (kw[XBM_FILE].count)
8187 if (kw[XBM_WIDTH].count || kw[XBM_HEIGHT].count || kw[XBM_DATA].count)
8188 return 0;
8190 else
8192 Lisp_Object data;
8193 int width, height;
8195 /* Entries for `:width', `:height' and `:data' must be present. */
8196 if (!kw[XBM_WIDTH].count
8197 || !kw[XBM_HEIGHT].count
8198 || !kw[XBM_DATA].count)
8199 return 0;
8201 data = kw[XBM_DATA].value;
8202 width = XFASTINT (kw[XBM_WIDTH].value);
8203 height = XFASTINT (kw[XBM_HEIGHT].value);
8205 /* Check type of data, and width and height against contents of
8206 data. */
8207 if (VECTORP (data))
8209 int i;
8211 /* Number of elements of the vector must be >= height. */
8212 if (XVECTOR (data)->size < height)
8213 return 0;
8215 /* Each string or bool-vector in data must be large enough
8216 for one line of the image. */
8217 for (i = 0; i < height; ++i)
8219 Lisp_Object elt = XVECTOR (data)->contents[i];
8221 if (STRINGP (elt))
8223 if (XSTRING (elt)->size
8224 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR)
8225 return 0;
8227 else if (BOOL_VECTOR_P (elt))
8229 if (XBOOL_VECTOR (elt)->size < width)
8230 return 0;
8232 else
8233 return 0;
8236 else if (STRINGP (data))
8238 if (XSTRING (data)->size
8239 < (width + BITS_PER_CHAR - 1) / BITS_PER_CHAR * height)
8240 return 0;
8242 else if (BOOL_VECTOR_P (data))
8244 if (XBOOL_VECTOR (data)->size < width * height)
8245 return 0;
8247 else
8248 return 0;
8251 /* Baseline must be a value between 0 and 100 (a percentage). */
8252 if (kw[XBM_ASCENT].count
8253 && XFASTINT (kw[XBM_ASCENT].value) > 100)
8254 return 0;
8256 return 1;
8260 /* Scan a bitmap file. FP is the stream to read from. Value is
8261 either an enumerator from enum xbm_token, or a character for a
8262 single-character token, or 0 at end of file. If scanning an
8263 identifier, store the lexeme of the identifier in SVAL. If
8264 scanning a number, store its value in *IVAL. */
8266 static int
8267 xbm_scan (fp, sval, ival)
8268 FILE *fp;
8269 char *sval;
8270 int *ival;
8272 int c;
8274 /* Skip white space. */
8275 while ((c = fgetc (fp)) != EOF && isspace (c))
8278 if (c == EOF)
8279 c = 0;
8280 else if (isdigit (c))
8282 int value = 0, digit;
8284 if (c == '0')
8286 c = fgetc (fp);
8287 if (c == 'x' || c == 'X')
8289 while ((c = fgetc (fp)) != EOF)
8291 if (isdigit (c))
8292 digit = c - '0';
8293 else if (c >= 'a' && c <= 'f')
8294 digit = c - 'a' + 10;
8295 else if (c >= 'A' && c <= 'F')
8296 digit = c - 'A' + 10;
8297 else
8298 break;
8299 value = 16 * value + digit;
8302 else if (isdigit (c))
8304 value = c - '0';
8305 while ((c = fgetc (fp)) != EOF
8306 && isdigit (c))
8307 value = 8 * value + c - '0';
8310 else
8312 value = c - '0';
8313 while ((c = fgetc (fp)) != EOF
8314 && isdigit (c))
8315 value = 10 * value + c - '0';
8318 if (c != EOF)
8319 ungetc (c, fp);
8320 *ival = value;
8321 c = XBM_TK_NUMBER;
8323 else if (isalpha (c) || c == '_')
8325 *sval++ = c;
8326 while ((c = fgetc (fp)) != EOF
8327 && (isalnum (c) || c == '_'))
8328 *sval++ = c;
8329 *sval = 0;
8330 if (c != EOF)
8331 ungetc (c, fp);
8332 c = XBM_TK_IDENT;
8335 return c;
8339 /* Replacement for XReadBitmapFileData which isn't available under old
8340 X versions. FILE is the name of the bitmap file to read. Set
8341 *WIDTH and *HEIGHT to the width and height of the image. Return in
8342 *DATA the bitmap data allocated with xmalloc. Value is non-zero if
8343 successful. */
8345 static int
8346 xbm_read_bitmap_file_data (file, width, height, data)
8347 char *file;
8348 int *width, *height;
8349 unsigned char **data;
8351 FILE *fp;
8352 char buffer[BUFSIZ];
8353 int padding_p = 0;
8354 int v10 = 0;
8355 int bytes_per_line, i, nbytes;
8356 unsigned char *p;
8357 int value;
8358 int LA1;
8360 #define match() \
8361 LA1 = xbm_scan (fp, buffer, &value)
8363 #define expect(TOKEN) \
8364 if (LA1 != (TOKEN)) \
8365 goto failure; \
8366 else \
8367 match ()
8369 #define expect_ident(IDENT) \
8370 if (LA1 == XBM_TK_IDENT && strcmp (buffer, (IDENT)) == 0) \
8371 match (); \
8372 else \
8373 goto failure
8375 fp = fopen (file, "r");
8376 if (fp == NULL)
8377 return 0;
8379 *width = *height = -1;
8380 *data = NULL;
8381 LA1 = xbm_scan (fp, buffer, &value);
8383 /* Parse defines for width, height and hot-spots. */
8384 while (LA1 == '#')
8386 match ();
8387 expect_ident ("define");
8388 expect (XBM_TK_IDENT);
8390 if (LA1 == XBM_TK_NUMBER);
8392 char *p = strrchr (buffer, '_');
8393 p = p ? p + 1 : buffer;
8394 if (strcmp (p, "width") == 0)
8395 *width = value;
8396 else if (strcmp (p, "height") == 0)
8397 *height = value;
8399 expect (XBM_TK_NUMBER);
8402 if (*width < 0 || *height < 0)
8403 goto failure;
8405 /* Parse bits. Must start with `static'. */
8406 expect_ident ("static");
8407 if (LA1 == XBM_TK_IDENT)
8409 if (strcmp (buffer, "unsigned") == 0)
8411 match ();
8412 expect_ident ("char");
8414 else if (strcmp (buffer, "short") == 0)
8416 match ();
8417 v10 = 1;
8418 if (*width % 16 && *width % 16 < 9)
8419 padding_p = 1;
8421 else if (strcmp (buffer, "char") == 0)
8422 match ();
8423 else
8424 goto failure;
8426 else
8427 goto failure;
8429 expect (XBM_TK_IDENT);
8430 expect ('[');
8431 expect (']');
8432 expect ('=');
8433 expect ('{');
8435 bytes_per_line = (*width + 7) / 8 + padding_p;
8436 nbytes = bytes_per_line * *height;
8437 p = *data = (char *) xmalloc (nbytes);
8439 if (v10)
8442 for (i = 0; i < nbytes; i += 2)
8444 int val = value;
8445 expect (XBM_TK_NUMBER);
8447 *p++ = val;
8448 if (!padding_p || ((i + 2) % bytes_per_line))
8449 *p++ = value >> 8;
8451 if (LA1 == ',' || LA1 == '}')
8452 match ();
8453 else
8454 goto failure;
8457 else
8459 for (i = 0; i < nbytes; ++i)
8461 int val = value;
8462 expect (XBM_TK_NUMBER);
8464 *p++ = val;
8466 if (LA1 == ',' || LA1 == '}')
8467 match ();
8468 else
8469 goto failure;
8473 fclose (fp);
8474 return 1;
8476 failure:
8478 fclose (fp);
8479 if (*data)
8481 xfree (*data);
8482 *data = NULL;
8484 return 0;
8486 #undef match
8487 #undef expect
8488 #undef expect_ident
8492 /* Load XBM image IMG which will be displayed on frame F from file
8493 SPECIFIED_FILE. Value is non-zero if successful. */
8495 static int
8496 xbm_load_image_from_file (f, img, specified_file)
8497 struct frame *f;
8498 struct image *img;
8499 Lisp_Object specified_file;
8501 int rc;
8502 unsigned char *data;
8503 int success_p = 0;
8504 Lisp_Object file;
8505 struct gcpro gcpro1;
8507 xassert (STRINGP (specified_file));
8508 file = Qnil;
8509 GCPRO1 (file);
8511 file = x_find_image_file (specified_file);
8512 if (!STRINGP (file))
8514 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8515 UNGCPRO;
8516 return 0;
8519 rc = xbm_read_bitmap_file_data (XSTRING (file)->data, &img->width,
8520 &img->height, &data);
8521 if (rc)
8523 int depth = one_w32_display_info.n_cbits;
8524 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8525 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8526 Lisp_Object value;
8528 xassert (img->width > 0 && img->height > 0);
8530 /* Get foreground and background colors, maybe allocate colors. */
8531 value = image_spec_value (img->spec, QCforeground, NULL);
8532 if (!NILP (value))
8533 foreground = x_alloc_image_color (f, img, value, foreground);
8535 value = image_spec_value (img->spec, QCbackground, NULL);
8536 if (!NILP (value))
8537 background = x_alloc_image_color (f, img, value, background);
8539 #if 0 /* NTEMACS_TODO : Port image display to W32 */
8540 BLOCK_INPUT;
8541 img->pixmap
8542 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
8543 FRAME_W32_WINDOW (f),
8544 data,
8545 img->width, img->height,
8546 foreground, background,
8547 depth);
8548 xfree (data);
8550 if (img->pixmap == 0)
8552 x_clear_image (f, img);
8553 image_error ("Unable to create X pixmap for `%s'", file, Qnil);
8555 else
8556 success_p = 1;
8558 UNBLOCK_INPUT;
8559 #endif
8561 else
8562 image_error ("Error loading XBM image `%s'", img->spec, Qnil);
8564 UNGCPRO;
8565 return success_p;
8569 /* Fill image IMG which is used on frame F with pixmap data. Value is
8570 non-zero if successful. */
8572 static int
8573 xbm_load (f, img)
8574 struct frame *f;
8575 struct image *img;
8577 int success_p = 0;
8578 Lisp_Object file_name;
8580 xassert (xbm_image_p (img->spec));
8582 /* If IMG->spec specifies a file name, create a non-file spec from it. */
8583 file_name = image_spec_value (img->spec, QCfile, NULL);
8584 if (STRINGP (file_name))
8585 success_p = xbm_load_image_from_file (f, img, file_name);
8586 else
8588 struct image_keyword fmt[XBM_LAST];
8589 Lisp_Object data;
8590 int depth;
8591 unsigned long foreground = FRAME_FOREGROUND_PIXEL (f);
8592 unsigned long background = FRAME_BACKGROUND_PIXEL (f);
8593 char *bits;
8594 int parsed_p;
8596 /* Parse the list specification. */
8597 bcopy (xbm_format, fmt, sizeof fmt);
8598 parsed_p = parse_image_spec (img->spec, fmt, XBM_LAST, Qxbm);
8599 xassert (parsed_p);
8601 /* Get specified width, and height. */
8602 img->width = XFASTINT (fmt[XBM_WIDTH].value);
8603 img->height = XFASTINT (fmt[XBM_HEIGHT].value);
8604 xassert (img->width > 0 && img->height > 0);
8606 BLOCK_INPUT;
8608 if (fmt[XBM_ASCENT].count)
8609 img->ascent = XFASTINT (fmt[XBM_ASCENT].value);
8611 /* Get foreground and background colors, maybe allocate colors. */
8612 if (fmt[XBM_FOREGROUND].count)
8613 foreground = x_alloc_image_color (f, img, fmt[XBM_FOREGROUND].value,
8614 foreground);
8615 if (fmt[XBM_BACKGROUND].count)
8616 background = x_alloc_image_color (f, img, fmt[XBM_BACKGROUND].value,
8617 background);
8619 /* Set bits to the bitmap image data. */
8620 data = fmt[XBM_DATA].value;
8621 if (VECTORP (data))
8623 int i;
8624 char *p;
8625 int nbytes = (img->width + BITS_PER_CHAR - 1) / BITS_PER_CHAR;
8627 p = bits = (char *) alloca (nbytes * img->height);
8628 for (i = 0; i < img->height; ++i, p += nbytes)
8630 Lisp_Object line = XVECTOR (data)->contents[i];
8631 if (STRINGP (line))
8632 bcopy (XSTRING (line)->data, p, nbytes);
8633 else
8634 bcopy (XBOOL_VECTOR (line)->data, p, nbytes);
8637 else if (STRINGP (data))
8638 bits = XSTRING (data)->data;
8639 else
8640 bits = XBOOL_VECTOR (data)->data;
8642 #if 0 /* NTEMACS_TODO : W32 XPM code */
8643 /* Create the pixmap. */
8644 depth = DefaultDepthOfScreen (FRAME_X_SCREEN (f));
8645 img->pixmap
8646 = XCreatePixmapFromBitmapData (FRAME_W32_DISPLAY (f),
8647 FRAME_W32_WINDOW (f),
8648 bits,
8649 img->width, img->height,
8650 foreground, background,
8651 depth);
8652 #endif /* NTEMACS_TODO */
8654 if (img->pixmap)
8655 success_p = 1;
8656 else
8658 image_error ("Unable to create pixmap for XBM image `%s'",
8659 img->spec, Qnil);
8660 x_clear_image (f, img);
8663 UNBLOCK_INPUT;
8666 return success_p;
8671 /***********************************************************************
8672 XPM images
8673 ***********************************************************************/
8675 #if HAVE_XPM
8677 static int xpm_image_p P_ ((Lisp_Object object));
8678 static int xpm_load P_ ((struct frame *f, struct image *img));
8679 static int xpm_valid_color_symbols_p P_ ((Lisp_Object));
8681 #include "X11/xpm.h"
8683 /* The symbol `xpm' identifying XPM-format images. */
8685 Lisp_Object Qxpm;
8687 /* Indices of image specification fields in xpm_format, below. */
8689 enum xpm_keyword_index
8691 XPM_TYPE,
8692 XPM_FILE,
8693 XPM_DATA,
8694 XPM_ASCENT,
8695 XPM_MARGIN,
8696 XPM_RELIEF,
8697 XPM_ALGORITHM,
8698 XPM_HEURISTIC_MASK,
8699 XPM_COLOR_SYMBOLS,
8700 XPM_LAST
8703 /* Vector of image_keyword structures describing the format
8704 of valid XPM image specifications. */
8706 static struct image_keyword xpm_format[XPM_LAST] =
8708 {":type", IMAGE_SYMBOL_VALUE, 1},
8709 {":file", IMAGE_STRING_VALUE, 0},
8710 {":data", IMAGE_STRING_VALUE, 0},
8711 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
8712 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
8713 {":relief", IMAGE_INTEGER_VALUE, 0},
8714 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8715 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
8716 {":color-symbols", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
8719 /* Structure describing the image type XBM. */
8721 static struct image_type xpm_type =
8723 &Qxpm,
8724 xpm_image_p,
8725 xpm_load,
8726 x_clear_image,
8727 NULL
8731 /* Value is non-zero if COLOR_SYMBOLS is a valid color symbols list
8732 for XPM images. Such a list must consist of conses whose car and
8733 cdr are strings. */
8735 static int
8736 xpm_valid_color_symbols_p (color_symbols)
8737 Lisp_Object color_symbols;
8739 while (CONSP (color_symbols))
8741 Lisp_Object sym = XCAR (color_symbols);
8742 if (!CONSP (sym)
8743 || !STRINGP (XCAR (sym))
8744 || !STRINGP (XCDR (sym)))
8745 break;
8746 color_symbols = XCDR (color_symbols);
8749 return NILP (color_symbols);
8753 /* Value is non-zero if OBJECT is a valid XPM image specification. */
8755 static int
8756 xpm_image_p (object)
8757 Lisp_Object object;
8759 struct image_keyword fmt[XPM_LAST];
8760 bcopy (xpm_format, fmt, sizeof fmt);
8761 return (parse_image_spec (object, fmt, XPM_LAST, Qxpm)
8762 /* Either `:file' or `:data' must be present. */
8763 && fmt[XPM_FILE].count + fmt[XPM_DATA].count == 1
8764 /* Either no `:color-symbols' or it's a list of conses
8765 whose car and cdr are strings. */
8766 && (fmt[XPM_COLOR_SYMBOLS].count == 0
8767 || xpm_valid_color_symbols_p (fmt[XPM_COLOR_SYMBOLS].value))
8768 && (fmt[XPM_ASCENT].count == 0
8769 || XFASTINT (fmt[XPM_ASCENT].value) < 100));
8773 /* Load image IMG which will be displayed on frame F. Value is
8774 non-zero if successful. */
8776 static int
8777 xpm_load (f, img)
8778 struct frame *f;
8779 struct image *img;
8781 int rc, i;
8782 XpmAttributes attrs;
8783 Lisp_Object specified_file, color_symbols;
8785 /* Configure the XPM lib. Use the visual of frame F. Allocate
8786 close colors. Return colors allocated. */
8787 bzero (&attrs, sizeof attrs);
8788 attrs.visual = FRAME_W32_DISPLAY_INFO (f)->visual;
8789 attrs.valuemask |= XpmVisual;
8790 attrs.valuemask |= XpmReturnAllocPixels;
8791 attrs.alloc_close_colors = 1;
8792 attrs.valuemask |= XpmAllocCloseColors;
8794 /* If image specification contains symbolic color definitions, add
8795 these to `attrs'. */
8796 color_symbols = image_spec_value (img->spec, QCcolor_symbols, NULL);
8797 if (CONSP (color_symbols))
8799 Lisp_Object tail;
8800 XpmColorSymbol *xpm_syms;
8801 int i, size;
8803 attrs.valuemask |= XpmColorSymbols;
8805 /* Count number of symbols. */
8806 attrs.numsymbols = 0;
8807 for (tail = color_symbols; CONSP (tail); tail = XCDR (tail))
8808 ++attrs.numsymbols;
8810 /* Allocate an XpmColorSymbol array. */
8811 size = attrs.numsymbols * sizeof *xpm_syms;
8812 xpm_syms = (XpmColorSymbol *) alloca (size);
8813 bzero (xpm_syms, size);
8814 attrs.colorsymbols = xpm_syms;
8816 /* Fill the color symbol array. */
8817 for (tail = color_symbols, i = 0;
8818 CONSP (tail);
8819 ++i, tail = XCDR (tail))
8821 Lisp_Object name = XCAR (XCAR (tail));
8822 Lisp_Object color = XCDR (XCAR (tail));
8823 xpm_syms[i].name = (char *) alloca (XSTRING (name)->size + 1);
8824 strcpy (xpm_syms[i].name, XSTRING (name)->data);
8825 xpm_syms[i].value = (char *) alloca (XSTRING (color)->size + 1);
8826 strcpy (xpm_syms[i].value, XSTRING (color)->data);
8830 /* Create a pixmap for the image, either from a file, or from a
8831 string buffer containing data in the same format as an XPM file. */
8832 BLOCK_INPUT;
8833 specified_file = image_spec_value (img->spec, QCfile, NULL);
8834 if (STRINGP (specified_file))
8836 Lisp_Object file = x_find_image_file (specified_file);
8837 if (!STRINGP (file))
8839 image_error ("Cannot find image file `%s'", specified_file, Qnil);
8840 UNBLOCK_INPUT;
8841 return 0;
8844 rc = XpmReadFileToPixmap (NULL, FRAME_W32_WINDOW (f),
8845 XSTRING (file)->data, &img->pixmap, &img->mask,
8846 &attrs);
8848 else
8850 Lisp_Object buffer = image_spec_value (img->spec, QCdata, NULL);
8851 rc = XpmCreatePixmapFromBuffer (NULL, FRAME_W32_WINDOW (f),
8852 XSTRING (buffer)->data,
8853 &img->pixmap, &img->mask,
8854 &attrs);
8856 UNBLOCK_INPUT;
8858 if (rc == XpmSuccess)
8860 /* Remember allocated colors. */
8861 img->ncolors = attrs.nalloc_pixels;
8862 img->colors = (unsigned long *) xmalloc (img->ncolors
8863 * sizeof *img->colors);
8864 for (i = 0; i < attrs.nalloc_pixels; ++i)
8865 img->colors[i] = attrs.alloc_pixels[i];
8867 img->width = attrs.width;
8868 img->height = attrs.height;
8869 xassert (img->width > 0 && img->height > 0);
8871 /* The call to XpmFreeAttributes below frees attrs.alloc_pixels. */
8872 BLOCK_INPUT;
8873 XpmFreeAttributes (&attrs);
8874 UNBLOCK_INPUT;
8876 else
8878 switch (rc)
8880 case XpmOpenFailed:
8881 image_error ("Error opening XPM file (%s)", img->spec, Qnil);
8882 break;
8884 case XpmFileInvalid:
8885 image_error ("Invalid XPM file (%s)", img->spec, Qnil);
8886 break;
8888 case XpmNoMemory:
8889 image_error ("Out of memory (%s)", img->spec, Qnil);
8890 break;
8892 case XpmColorFailed:
8893 image_error ("Color allocation error (%s)", img->spec, Qnil);
8894 break;
8896 default:
8897 image_error ("Unknown error (%s)", img->spec, Qnil);
8898 break;
8902 return rc == XpmSuccess;
8905 #endif /* HAVE_XPM != 0 */
8908 #if 0 /* NTEMACS_TODO : Color tables on W32. */
8909 /***********************************************************************
8910 Color table
8911 ***********************************************************************/
8913 /* An entry in the color table mapping an RGB color to a pixel color. */
8915 struct ct_color
8917 int r, g, b;
8918 unsigned long pixel;
8920 /* Next in color table collision list. */
8921 struct ct_color *next;
8924 /* The bucket vector size to use. Must be prime. */
8926 #define CT_SIZE 101
8928 /* Value is a hash of the RGB color given by R, G, and B. */
8930 #define CT_HASH_RGB(R, G, B) (((R) << 16) ^ ((G) << 8) ^ (B))
8932 /* The color hash table. */
8934 struct ct_color **ct_table;
8936 /* Number of entries in the color table. */
8938 int ct_colors_allocated;
8940 /* Function prototypes. */
8942 static void init_color_table P_ ((void));
8943 static void free_color_table P_ ((void));
8944 static unsigned long *colors_in_color_table P_ ((int *n));
8945 static unsigned long lookup_rgb_color P_ ((struct frame *f, int r, int g, int b));
8946 static unsigned long lookup_pixel_color P_ ((struct frame *f, unsigned long p));
8949 /* Initialize the color table. */
8951 static void
8952 init_color_table ()
8954 int size = CT_SIZE * sizeof (*ct_table);
8955 ct_table = (struct ct_color **) xmalloc (size);
8956 bzero (ct_table, size);
8957 ct_colors_allocated = 0;
8961 /* Free memory associated with the color table. */
8963 static void
8964 free_color_table ()
8966 int i;
8967 struct ct_color *p, *next;
8969 for (i = 0; i < CT_SIZE; ++i)
8970 for (p = ct_table[i]; p; p = next)
8972 next = p->next;
8973 xfree (p);
8976 xfree (ct_table);
8977 ct_table = NULL;
8981 /* Value is a pixel color for RGB color R, G, B on frame F. If an
8982 entry for that color already is in the color table, return the
8983 pixel color of that entry. Otherwise, allocate a new color for R,
8984 G, B, and make an entry in the color table. */
8986 static unsigned long
8987 lookup_rgb_color (f, r, g, b)
8988 struct frame *f;
8989 int r, g, b;
8991 unsigned hash = CT_HASH_RGB (r, g, b);
8992 int i = hash % CT_SIZE;
8993 struct ct_color *p;
8995 for (p = ct_table[i]; p; p = p->next)
8996 if (p->r == r && p->g == g && p->b == b)
8997 break;
8999 if (p == NULL)
9001 COLORREF color;
9002 Colormap cmap;
9003 int rc;
9005 color = PALETTERGB (r, g, b);
9007 ++ct_colors_allocated;
9009 p = (struct ct_color *) xmalloc (sizeof *p);
9010 p->r = r;
9011 p->g = g;
9012 p->b = b;
9013 p->pixel = color;
9014 p->next = ct_table[i];
9015 ct_table[i] = p;
9018 return p->pixel;
9022 /* Look up pixel color PIXEL which is used on frame F in the color
9023 table. If not already present, allocate it. Value is PIXEL. */
9025 static unsigned long
9026 lookup_pixel_color (f, pixel)
9027 struct frame *f;
9028 unsigned long pixel;
9030 int i = pixel % CT_SIZE;
9031 struct ct_color *p;
9033 for (p = ct_table[i]; p; p = p->next)
9034 if (p->pixel == pixel)
9035 break;
9037 if (p == NULL)
9039 XColor color;
9040 Colormap cmap;
9041 int rc;
9043 BLOCK_INPUT;
9045 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9046 color.pixel = pixel;
9047 XQueryColor (NULL, cmap, &color);
9048 rc = x_alloc_nearest_color (f, cmap, &color);
9049 UNBLOCK_INPUT;
9051 if (rc)
9053 ++ct_colors_allocated;
9055 p = (struct ct_color *) xmalloc (sizeof *p);
9056 p->r = color.red;
9057 p->g = color.green;
9058 p->b = color.blue;
9059 p->pixel = pixel;
9060 p->next = ct_table[i];
9061 ct_table[i] = p;
9063 else
9064 return FRAME_FOREGROUND_PIXEL (f);
9066 return p->pixel;
9070 /* Value is a vector of all pixel colors contained in the color table,
9071 allocated via xmalloc. Set *N to the number of colors. */
9073 static unsigned long *
9074 colors_in_color_table (n)
9075 int *n;
9077 int i, j;
9078 struct ct_color *p;
9079 unsigned long *colors;
9081 if (ct_colors_allocated == 0)
9083 *n = 0;
9084 colors = NULL;
9086 else
9088 colors = (unsigned long *) xmalloc (ct_colors_allocated
9089 * sizeof *colors);
9090 *n = ct_colors_allocated;
9092 for (i = j = 0; i < CT_SIZE; ++i)
9093 for (p = ct_table[i]; p; p = p->next)
9094 colors[j++] = p->pixel;
9097 return colors;
9100 #endif /* NTEMACS_TODO */
9103 /***********************************************************************
9104 Algorithms
9105 ***********************************************************************/
9107 #if 0 /* NTEMACS_TODO : W32 versions of low level algorithms */
9108 static void x_laplace_write_row P_ ((struct frame *, long *,
9109 int, XImage *, int));
9110 static void x_laplace_read_row P_ ((struct frame *, Colormap,
9111 XColor *, int, XImage *, int));
9114 /* Fill COLORS with RGB colors from row Y of image XIMG. F is the
9115 frame we operate on, CMAP is the color-map in effect, and WIDTH is
9116 the width of one row in the image. */
9118 static void
9119 x_laplace_read_row (f, cmap, colors, width, ximg, y)
9120 struct frame *f;
9121 Colormap cmap;
9122 XColor *colors;
9123 int width;
9124 XImage *ximg;
9125 int y;
9127 int x;
9129 for (x = 0; x < width; ++x)
9130 colors[x].pixel = XGetPixel (ximg, x, y);
9132 XQueryColors (NULL, cmap, colors, width);
9136 /* Write row Y of image XIMG. PIXELS is an array of WIDTH longs
9137 containing the pixel colors to write. F is the frame we are
9138 working on. */
9140 static void
9141 x_laplace_write_row (f, pixels, width, ximg, y)
9142 struct frame *f;
9143 long *pixels;
9144 int width;
9145 XImage *ximg;
9146 int y;
9148 int x;
9150 for (x = 0; x < width; ++x)
9151 XPutPixel (ximg, x, y, pixels[x]);
9153 #endif
9155 /* Transform image IMG which is used on frame F with a Laplace
9156 edge-detection algorithm. The result is an image that can be used
9157 to draw disabled buttons, for example. */
9159 static void
9160 x_laplace (f, img)
9161 struct frame *f;
9162 struct image *img;
9164 #if 0 /* NTEMACS_TODO : W32 version */
9165 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9166 XImage *ximg, *oimg;
9167 XColor *in[3];
9168 long *out;
9169 Pixmap pixmap;
9170 int x, y, i;
9171 long pixel;
9172 int in_y, out_y, rc;
9173 int mv2 = 45000;
9175 BLOCK_INPUT;
9177 /* Get the X image IMG->pixmap. */
9178 ximg = XGetImage (NULL, img->pixmap,
9179 0, 0, img->width, img->height, ~0, ZPixmap);
9181 /* Allocate 3 input rows, and one output row of colors. */
9182 for (i = 0; i < 3; ++i)
9183 in[i] = (XColor *) alloca (img->width * sizeof (XColor));
9184 out = (long *) alloca (img->width * sizeof (long));
9186 /* Create an X image for output. */
9187 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 0,
9188 &oimg, &pixmap);
9190 /* Fill first two rows. */
9191 x_laplace_read_row (f, cmap, in[0], img->width, ximg, 0);
9192 x_laplace_read_row (f, cmap, in[1], img->width, ximg, 1);
9193 in_y = 2;
9195 /* Write first row, all zeros. */
9196 init_color_table ();
9197 pixel = lookup_rgb_color (f, 0, 0, 0);
9198 for (x = 0; x < img->width; ++x)
9199 out[x] = pixel;
9200 x_laplace_write_row (f, out, img->width, oimg, 0);
9201 out_y = 1;
9203 for (y = 2; y < img->height; ++y)
9205 int rowa = y % 3;
9206 int rowb = (y + 2) % 3;
9208 x_laplace_read_row (f, cmap, in[rowa], img->width, ximg, in_y++);
9210 for (x = 0; x < img->width - 2; ++x)
9212 int r = in[rowa][x].red + mv2 - in[rowb][x + 2].red;
9213 int g = in[rowa][x].green + mv2 - in[rowb][x + 2].green;
9214 int b = in[rowa][x].blue + mv2 - in[rowb][x + 2].blue;
9216 out[x + 1] = lookup_rgb_color (f, r & 0xffff, g & 0xffff,
9217 b & 0xffff);
9220 x_laplace_write_row (f, out, img->width, oimg, out_y++);
9223 /* Write last line, all zeros. */
9224 for (x = 0; x < img->width; ++x)
9225 out[x] = pixel;
9226 x_laplace_write_row (f, out, img->width, oimg, out_y);
9228 /* Free the input image, and free resources of IMG. */
9229 XDestroyImage (ximg);
9230 x_clear_image (f, img);
9232 /* Put the output image into pixmap, and destroy it. */
9233 x_put_x_image (f, oimg, pixmap, img->width, img->height);
9234 x_destroy_x_image (oimg);
9236 /* Remember new pixmap and colors in IMG. */
9237 img->pixmap = pixmap;
9238 img->colors = colors_in_color_table (&img->ncolors);
9239 free_color_table ();
9241 UNBLOCK_INPUT;
9242 #endif /* NTEMACS_TODO */
9246 /* Build a mask for image IMG which is used on frame F. FILE is the
9247 name of an image file, for error messages. HOW determines how to
9248 determine the background color of IMG. If it is a list '(R G B)',
9249 with R, G, and B being integers >= 0, take that as the color of the
9250 background. Otherwise, determine the background color of IMG
9251 heuristically. Value is non-zero if successful. */
9253 static int
9254 x_build_heuristic_mask (f, img, how)
9255 struct frame *f;
9256 struct image *img;
9257 Lisp_Object how;
9259 #if 0 /* NTEMACS_TODO : W32 version */
9260 Display *dpy = FRAME_W32_DISPLAY (f);
9261 XImage *ximg, *mask_img;
9262 int x, y, rc, look_at_corners_p;
9263 unsigned long bg;
9265 BLOCK_INPUT;
9267 /* Create an image and pixmap serving as mask. */
9268 rc = x_create_x_image_and_pixmap (f, img->width, img->height, 1,
9269 &mask_img, &img->mask);
9270 if (!rc)
9272 UNBLOCK_INPUT;
9273 return 0;
9276 /* Get the X image of IMG->pixmap. */
9277 ximg = XGetImage (dpy, img->pixmap, 0, 0, img->width, img->height,
9278 ~0, ZPixmap);
9280 /* Determine the background color of ximg. If HOW is `(R G B)'
9281 take that as color. Otherwise, try to determine the color
9282 heuristically. */
9283 look_at_corners_p = 1;
9285 if (CONSP (how))
9287 int rgb[3], i = 0;
9289 while (i < 3
9290 && CONSP (how)
9291 && NATNUMP (XCAR (how)))
9293 rgb[i] = XFASTINT (XCAR (how)) & 0xffff;
9294 how = XCDR (how);
9297 if (i == 3 && NILP (how))
9299 char color_name[30];
9300 XColor exact, color;
9301 Colormap cmap;
9303 sprintf (color_name, "#%04x%04x%04x", rgb[0], rgb[1], rgb[2]);
9305 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
9306 if (XLookupColor (dpy, cmap, color_name, &exact, &color))
9308 bg = color.pixel;
9309 look_at_corners_p = 0;
9314 if (look_at_corners_p)
9316 unsigned long corners[4];
9317 int i, best_count;
9319 /* Get the colors at the corners of ximg. */
9320 corners[0] = XGetPixel (ximg, 0, 0);
9321 corners[1] = XGetPixel (ximg, img->width - 1, 0);
9322 corners[2] = XGetPixel (ximg, img->width - 1, img->height - 1);
9323 corners[3] = XGetPixel (ximg, 0, img->height - 1);
9325 /* Choose the most frequently found color as background. */
9326 for (i = best_count = 0; i < 4; ++i)
9328 int j, n;
9330 for (j = n = 0; j < 4; ++j)
9331 if (corners[i] == corners[j])
9332 ++n;
9334 if (n > best_count)
9335 bg = corners[i], best_count = n;
9339 /* Set all bits in mask_img to 1 whose color in ximg is different
9340 from the background color bg. */
9341 for (y = 0; y < img->height; ++y)
9342 for (x = 0; x < img->width; ++x)
9343 XPutPixel (mask_img, x, y, XGetPixel (ximg, x, y) != bg);
9345 /* Put mask_img into img->mask. */
9346 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
9347 x_destroy_x_image (mask_img);
9348 XDestroyImage (ximg);
9350 UNBLOCK_INPUT;
9351 #endif /* NTEMACS_TODO */
9353 return 1;
9358 /***********************************************************************
9359 PBM (mono, gray, color)
9360 ***********************************************************************/
9361 #ifdef HAVE_PBM
9363 static int pbm_image_p P_ ((Lisp_Object object));
9364 static int pbm_load P_ ((struct frame *f, struct image *img));
9365 static int pbm_scan_number P_ ((unsigned char **, unsigned char *));
9367 /* The symbol `pbm' identifying images of this type. */
9369 Lisp_Object Qpbm;
9371 /* Indices of image specification fields in gs_format, below. */
9373 enum pbm_keyword_index
9375 PBM_TYPE,
9376 PBM_FILE,
9377 PBM_DATA,
9378 PBM_ASCENT,
9379 PBM_MARGIN,
9380 PBM_RELIEF,
9381 PBM_ALGORITHM,
9382 PBM_HEURISTIC_MASK,
9383 PBM_LAST
9386 /* Vector of image_keyword structures describing the format
9387 of valid user-defined image specifications. */
9389 static struct image_keyword pbm_format[PBM_LAST] =
9391 {":type", IMAGE_SYMBOL_VALUE, 1},
9392 {":file", IMAGE_STRING_VALUE, 0},
9393 {":data", IMAGE_STRING_VALUE, 0},
9394 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9395 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9396 {":relief", IMAGE_INTEGER_VALUE, 0},
9397 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9398 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9401 /* Structure describing the image type `pbm'. */
9403 static struct image_type pbm_type =
9405 &Qpbm,
9406 pbm_image_p,
9407 pbm_load,
9408 x_clear_image,
9409 NULL
9413 /* Return non-zero if OBJECT is a valid PBM image specification. */
9415 static int
9416 pbm_image_p (object)
9417 Lisp_Object object;
9419 struct image_keyword fmt[PBM_LAST];
9421 bcopy (pbm_format, fmt, sizeof fmt);
9423 if (!parse_image_spec (object, fmt, PBM_LAST, Qpbm)
9424 || (fmt[PBM_ASCENT].count
9425 && XFASTINT (fmt[PBM_ASCENT].value) > 100))
9426 return 0;
9428 /* Must specify either :data or :file. */
9429 return fmt[PBM_DATA].count + fmt[PBM_FILE].count == 1;
9433 /* Scan a decimal number from *S and return it. Advance *S while
9434 reading the number. END is the end of the string. Value is -1 at
9435 end of input. */
9437 static int
9438 pbm_scan_number (s, end)
9439 unsigned char **s, *end;
9441 int c, val = -1;
9443 while (*s < end)
9445 /* Skip white-space. */
9446 while (*s < end && (c = *(*s)++, isspace (c)))
9449 if (c == '#')
9451 /* Skip comment to end of line. */
9452 while (*s < end && (c = *(*s)++, c != '\n'))
9455 else if (isdigit (c))
9457 /* Read decimal number. */
9458 val = c - '0';
9459 while (*s < end && (c = *(*s)++, isdigit (c)))
9460 val = 10 * val + c - '0';
9461 break;
9463 else
9464 break;
9467 return val;
9471 /* Read FILE into memory. Value is a pointer to a buffer allocated
9472 with xmalloc holding FILE's contents. Value is null if an error
9473 occured. *SIZE is set to the size of the file. */
9475 static char *
9476 pbm_read_file (file, size)
9477 Lisp_Object file;
9478 int *size;
9480 FILE *fp = NULL;
9481 char *buf = NULL;
9482 struct stat st;
9484 if (stat (XSTRING (file)->data, &st) == 0
9485 && (fp = fopen (XSTRING (file)->data, "r")) != NULL
9486 && (buf = (char *) xmalloc (st.st_size),
9487 fread (buf, 1, st.st_size, fp) == st.st_size))
9489 *size = st.st_size;
9490 fclose (fp);
9492 else
9494 if (fp)
9495 fclose (fp);
9496 if (buf)
9498 xfree (buf);
9499 buf = NULL;
9503 return buf;
9507 /* Load PBM image IMG for use on frame F. */
9509 static int
9510 pbm_load (f, img)
9511 struct frame *f;
9512 struct image *img;
9514 int raw_p, x, y;
9515 int width, height, max_color_idx = 0;
9516 XImage *ximg;
9517 Lisp_Object file, specified_file;
9518 enum {PBM_MONO, PBM_GRAY, PBM_COLOR} type;
9519 struct gcpro gcpro1;
9520 unsigned char *contents = NULL;
9521 unsigned char *end, *p;
9522 int size;
9524 specified_file = image_spec_value (img->spec, QCfile, NULL);
9525 file = Qnil;
9526 GCPRO1 (file);
9528 if (STRINGP (specified_file))
9530 file = x_find_image_file (specified_file);
9531 if (!STRINGP (file))
9533 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9534 UNGCPRO;
9535 return 0;
9538 contents = pbm_read_file (file, &size);
9539 if (contents == NULL)
9541 image_error ("Error reading `%s'", file, Qnil);
9542 UNGCPRO;
9543 return 0;
9546 p = contents;
9547 end = contents + size;
9549 else
9551 Lisp_Object data;
9552 data = image_spec_value (img->spec, QCdata, NULL);
9553 p = XSTRING (data)->data;
9554 end = p + STRING_BYTES (XSTRING (data));
9557 /* Check magic number. */
9558 if (end - p < 2 || *p++ != 'P')
9560 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
9561 error:
9562 xfree (contents);
9563 UNGCPRO;
9564 return 0;
9567 if (*magic != 'P')
9569 fclose (fp);
9570 image_error ("Not a PBM image file: %s", file, Qnil);
9571 UNGCPRO;
9572 return 0;
9575 switch (*p++)
9577 case '1':
9578 raw_p = 0, type = PBM_MONO;
9579 break;
9581 case '2':
9582 raw_p = 0, type = PBM_GRAY;
9583 break;
9585 case '3':
9586 raw_p = 0, type = PBM_COLOR;
9587 break;
9589 case '4':
9590 raw_p = 1, type = PBM_MONO;
9591 break;
9593 case '5':
9594 raw_p = 1, type = PBM_GRAY;
9595 break;
9597 case '6':
9598 raw_p = 1, type = PBM_COLOR;
9599 break;
9601 default:
9602 image_error ("Not a PBM image: `%s'", img->spec, Qnil);
9603 goto error;
9606 /* Read width, height, maximum color-component. Characters
9607 starting with `#' up to the end of a line are ignored. */
9608 width = pbm_scan_number (&p, end);
9609 height = pbm_scan_number (&p, end);
9611 if (type != PBM_MONO)
9613 max_color_idx = pbm_scan_number (&p, end);
9614 if (raw_p && max_color_idx > 255)
9615 max_color_idx = 255;
9618 if (width < 0
9619 || height < 0
9620 || (type != PBM_MONO && max_color_idx < 0))
9621 goto error;
9623 BLOCK_INPUT;
9624 if (!x_create_x_image_and_pixmap (f, width, height, 0,
9625 &ximg, &img->pixmap))
9627 UNBLOCK_INPUT;
9628 goto error;
9631 /* Initialize the color hash table. */
9632 init_color_table ();
9634 if (type == PBM_MONO)
9636 int c = 0, g;
9638 for (y = 0; y < height; ++y)
9639 for (x = 0; x < width; ++x)
9641 if (raw_p)
9643 if ((x & 7) == 0)
9644 c = *p++;
9645 g = c & 0x80;
9646 c <<= 1;
9648 else
9649 g = pbm_scan_number (&p, end);
9651 XPutPixel (ximg, x, y, (g
9652 ? FRAME_FOREGROUND_PIXEL (f)
9653 : FRAME_BACKGROUND_PIXEL (f)));
9656 else
9658 for (y = 0; y < height; ++y)
9659 for (x = 0; x < width; ++x)
9661 int r, g, b;
9663 if (type == PBM_GRAY)
9664 r = g = b = raw_p ? *p++ : pbm_scan_number (&p, end);
9665 else if (raw_p)
9667 r = *p++;
9668 g = *p++;
9669 b = *p++;
9671 else
9673 r = pbm_scan_number (&p, end);
9674 g = pbm_scan_number (&p, end);
9675 b = pbm_scan_number (&p, end);
9678 if (r < 0 || g < 0 || b < 0)
9680 b xfree (ximg->data);
9681 ximg->data = NULL;
9682 XDestroyImage (ximg);
9683 UNBLOCK_INPUT;
9684 image_error ("Invalid pixel value in image `%s'",
9685 img->spec, Qnil);
9686 goto error;
9689 /* RGB values are now in the range 0..max_color_idx.
9690 Scale this to the range 0..0xffff supported by X. */
9691 r = (double) r * 65535 / max_color_idx;
9692 g = (double) g * 65535 / max_color_idx;
9693 b = (double) b * 65535 / max_color_idx;
9694 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
9698 /* Store in IMG->colors the colors allocated for the image, and
9699 free the color table. */
9700 img->colors = colors_in_color_table (&img->ncolors);
9701 free_color_table ();
9703 /* Put the image into a pixmap. */
9704 x_put_x_image (f, ximg, img->pixmap, width, height);
9705 x_destroy_x_image (ximg);
9706 UNBLOCK_INPUT;
9708 img->width = width;
9709 img->height = height;
9711 UNGCPRO;
9712 xfree (contents);
9713 return 1;
9715 #endif /* HAVE_PBM */
9718 /***********************************************************************
9720 ***********************************************************************/
9722 #if HAVE_PNG
9724 #include <png.h>
9726 /* Function prototypes. */
9728 static int png_image_p P_ ((Lisp_Object object));
9729 static int png_load P_ ((struct frame *f, struct image *img));
9731 /* The symbol `png' identifying images of this type. */
9733 Lisp_Object Qpng;
9735 /* Indices of image specification fields in png_format, below. */
9737 enum png_keyword_index
9739 PNG_TYPE,
9740 PNG_DATA,
9741 PNG_FILE,
9742 PNG_ASCENT,
9743 PNG_MARGIN,
9744 PNG_RELIEF,
9745 PNG_ALGORITHM,
9746 PNG_HEURISTIC_MASK,
9747 PNG_LAST
9750 /* Vector of image_keyword structures describing the format
9751 of valid user-defined image specifications. */
9753 static struct image_keyword png_format[PNG_LAST] =
9755 {":type", IMAGE_SYMBOL_VALUE, 1},
9756 {":data", IMAGE_STRING_VALUE, 0},
9757 {":file", IMAGE_STRING_VALUE, 0},
9758 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
9759 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
9760 {":relief", IMAGE_INTEGER_VALUE, 0},
9761 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
9762 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
9765 /* Structure describing the image type `png'. */
9767 static struct image_type png_type =
9769 &Qpng,
9770 png_image_p,
9771 png_load,
9772 x_clear_image,
9773 NULL
9777 /* Return non-zero if OBJECT is a valid PNG image specification. */
9779 static int
9780 png_image_p (object)
9781 Lisp_Object object;
9783 struct image_keyword fmt[PNG_LAST];
9784 bcopy (png_format, fmt, sizeof fmt);
9786 if (!parse_image_spec (object, fmt, PNG_LAST, Qpng)
9787 || (fmt[PNG_ASCENT].count
9788 && XFASTINT (fmt[PNG_ASCENT].value) > 100))
9789 return 0;
9791 /* Must specify either the :data or :file keyword. */
9792 return fmt[PNG_FILE].count + fmt[PNG_DATA].count == 1;
9796 /* Error and warning handlers installed when the PNG library
9797 is initialized. */
9799 static void
9800 my_png_error (png_ptr, msg)
9801 png_struct *png_ptr;
9802 char *msg;
9804 xassert (png_ptr != NULL);
9805 image_error ("PNG error: %s", build_string (msg), Qnil);
9806 longjmp (png_ptr->jmpbuf, 1);
9810 static void
9811 my_png_warning (png_ptr, msg)
9812 png_struct *png_ptr;
9813 char *msg;
9815 xassert (png_ptr != NULL);
9816 image_error ("PNG warning: %s", build_string (msg), Qnil);
9820 /* Memory source for PNG decoding. */
9822 struct png_memory_storage
9824 unsigned char *bytes; /* The data */
9825 size_t len; /* How big is it? */
9826 int index; /* Where are we? */
9830 /* Function set as reader function when reading PNG image from memory.
9831 PNG_PTR is a pointer to the PNG control structure. Copy LENGTH
9832 bytes from the input to DATA. */
9834 static void
9835 png_read_from_memory (png_ptr, data, length)
9836 png_structp png_ptr;
9837 png_bytep data;
9838 png_size_t length;
9840 struct png_memory_storage *tbr
9841 = (struct png_memory_storage *) png_get_io_ptr (png_ptr);
9843 if (length > tbr->len - tbr->index)
9844 png_error (png_ptr, "Read error");
9846 bcopy (tbr->bytes + tbr->index, data, length);
9847 tbr->index = tbr->index + length;
9851 /* Load PNG image IMG for use on frame F. Value is non-zero if
9852 successful. */
9854 static int
9855 png_load (f, img)
9856 struct frame *f;
9857 struct image *img;
9859 Lisp_Object file, specified_file;
9860 Lisp_Object specified_data;
9861 int x, y, i;
9862 XImage *ximg, *mask_img = NULL;
9863 struct gcpro gcpro1;
9864 png_struct *png_ptr = NULL;
9865 png_info *info_ptr = NULL, *end_info = NULL;
9866 FILE *fp = NULL;
9867 png_byte sig[8];
9868 png_byte *pixels = NULL;
9869 png_byte **rows = NULL;
9870 png_uint_32 width, height;
9871 int bit_depth, color_type, interlace_type;
9872 png_byte channels;
9873 png_uint_32 row_bytes;
9874 int transparent_p;
9875 char *gamma_str;
9876 double screen_gamma, image_gamma;
9877 int intent;
9878 struct png_memory_storage tbr; /* Data to be read */
9880 /* Find out what file to load. */
9881 specified_file = image_spec_value (img->spec, QCfile, NULL);
9882 specified_data = image_spec_value (img->spec, QCdata, NULL);
9883 file = Qnil;
9884 GCPRO1 (file);
9886 if (NILP (specified_data))
9888 file = x_find_image_file (specified_file);
9889 if (!STRINGP (file))
9891 image_error ("Cannot find image file `%s'", specified_file, Qnil);
9892 UNGCPRO;
9893 return 0;
9896 /* Open the image file. */
9897 fp = fopen (XSTRING (file)->data, "rb");
9898 if (!fp)
9900 image_error ("Cannot open image file `%s'", file, Qnil);
9901 UNGCPRO;
9902 fclose (fp);
9903 return 0;
9906 /* Check PNG signature. */
9907 if (fread (sig, 1, sizeof sig, fp) != sizeof sig
9908 || !png_check_sig (sig, sizeof sig))
9910 image_error ("Not a PNG file:` %s'", file, Qnil);
9911 UNGCPRO;
9912 fclose (fp);
9913 return 0;
9916 else
9918 /* Read from memory. */
9919 tbr.bytes = XSTRING (specified_data)->data;
9920 tbr.len = STRING_BYTES (XSTRING (specified_data));
9921 tbr.index = 0;
9923 /* Check PNG signature. */
9924 if (tbr.len < sizeof sig
9925 || !png_check_sig (tbr.bytes, sizeof sig))
9927 image_error ("Not a PNG image: `%s'", img->spec, Qnil);
9928 UNGCPRO;
9929 return 0;
9932 /* Need to skip past the signature. */
9933 tbr.bytes += sizeof (sig);
9937 /* Initialize read and info structs for PNG lib. */
9938 png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, NULL,
9939 my_png_error, my_png_warning);
9940 if (!png_ptr)
9942 if (fp) fclose (fp);
9943 UNGCPRO;
9944 return 0;
9947 info_ptr = png_create_info_struct (png_ptr);
9948 if (!info_ptr)
9950 png_destroy_read_struct (&png_ptr, NULL, NULL);
9951 if (fp) fclose (fp);
9952 UNGCPRO;
9953 return 0;
9956 end_info = png_create_info_struct (png_ptr);
9957 if (!end_info)
9959 png_destroy_read_struct (&png_ptr, &info_ptr, NULL);
9960 if (fp) fclose (fp);
9961 UNGCPRO;
9962 return 0;
9965 /* Set error jump-back. We come back here when the PNG library
9966 detects an error. */
9967 if (setjmp (png_ptr->jmpbuf))
9969 error:
9970 if (png_ptr)
9971 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
9972 xfree (pixels);
9973 xfree (rows);
9974 if (fp) fclose (fp);
9975 UNGCPRO;
9976 return 0;
9979 /* Read image info. */
9980 if (!NILP (specified_data))
9981 png_set_read_fn (png_ptr, (void *) &tbr, png_read_from_memory);
9982 else
9983 png_init_io (png_ptr, fp);
9985 png_set_sig_bytes (png_ptr, sizeof sig);
9986 png_read_info (png_ptr, info_ptr);
9987 png_get_IHDR (png_ptr, info_ptr, &width, &height, &bit_depth, &color_type,
9988 &interlace_type, NULL, NULL);
9990 /* If image contains simply transparency data, we prefer to
9991 construct a clipping mask. */
9992 if (png_get_valid (png_ptr, info_ptr, PNG_INFO_tRNS))
9993 transparent_p = 1;
9994 else
9995 transparent_p = 0;
9997 /* This function is easier to write if we only have to handle
9998 one data format: RGB or RGBA with 8 bits per channel. Let's
9999 transform other formats into that format. */
10001 /* Strip more than 8 bits per channel. */
10002 if (bit_depth == 16)
10003 png_set_strip_16 (png_ptr);
10005 /* Expand data to 24 bit RGB, or 8 bit grayscale, with alpha channel
10006 if available. */
10007 png_set_expand (png_ptr);
10009 /* Convert grayscale images to RGB. */
10010 if (color_type == PNG_COLOR_TYPE_GRAY
10011 || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
10012 png_set_gray_to_rgb (png_ptr);
10014 /* The value 2.2 is a guess for PC monitors from PNG example.c. */
10015 gamma_str = getenv ("SCREEN_GAMMA");
10016 screen_gamma = gamma_str ? atof (gamma_str) : 2.2;
10018 /* Tell the PNG lib to handle gamma correction for us. */
10020 #if defined(PNG_READ_sRGB_SUPPORTED) || defined(PNG_WRITE_sRGB_SUPPORTED)
10021 if (png_get_sRGB (png_ptr, info_ptr, &intent))
10022 /* There is a special chunk in the image specifying the gamma. */
10023 png_set_sRGB (png_ptr, info_ptr, intent);
10024 else
10025 #endif
10026 if (png_get_gAMA (png_ptr, info_ptr, &image_gamma))
10027 /* Image contains gamma information. */
10028 png_set_gamma (png_ptr, screen_gamma, image_gamma);
10029 else
10030 /* Use a default of 0.5 for the image gamma. */
10031 png_set_gamma (png_ptr, screen_gamma, 0.5);
10033 /* Handle alpha channel by combining the image with a background
10034 color. Do this only if a real alpha channel is supplied. For
10035 simple transparency, we prefer a clipping mask. */
10036 if (!transparent_p)
10038 png_color_16 *image_background;
10040 if (png_get_bKGD (png_ptr, info_ptr, &image_background))
10041 /* Image contains a background color with which to
10042 combine the image. */
10043 png_set_background (png_ptr, image_background,
10044 PNG_BACKGROUND_GAMMA_FILE, 1, 1.0);
10045 else
10047 /* Image does not contain a background color with which
10048 to combine the image data via an alpha channel. Use
10049 the frame's background instead. */
10050 XColor color;
10051 Colormap cmap;
10052 png_color_16 frame_background;
10054 BLOCK_INPUT;
10055 cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
10056 color.pixel = FRAME_BACKGROUND_PIXEL (f);
10057 XQueryColor (FRAME_W32_DISPLAY (f), cmap, &color);
10058 UNBLOCK_INPUT;
10060 bzero (&frame_background, sizeof frame_background);
10061 frame_background.red = color.red;
10062 frame_background.green = color.green;
10063 frame_background.blue = color.blue;
10065 png_set_background (png_ptr, &frame_background,
10066 PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
10070 /* Update info structure. */
10071 png_read_update_info (png_ptr, info_ptr);
10073 /* Get number of channels. Valid values are 1 for grayscale images
10074 and images with a palette, 2 for grayscale images with transparency
10075 information (alpha channel), 3 for RGB images, and 4 for RGB
10076 images with alpha channel, i.e. RGBA. If conversions above were
10077 sufficient we should only have 3 or 4 channels here. */
10078 channels = png_get_channels (png_ptr, info_ptr);
10079 xassert (channels == 3 || channels == 4);
10081 /* Number of bytes needed for one row of the image. */
10082 row_bytes = png_get_rowbytes (png_ptr, info_ptr);
10084 /* Allocate memory for the image. */
10085 pixels = (png_byte *) xmalloc (row_bytes * height * sizeof *pixels);
10086 rows = (png_byte **) xmalloc (height * sizeof *rows);
10087 for (i = 0; i < height; ++i)
10088 rows[i] = pixels + i * row_bytes;
10090 /* Read the entire image. */
10091 png_read_image (png_ptr, rows);
10092 png_read_end (png_ptr, info_ptr);
10093 if (fp)
10095 fclose (fp);
10096 fp = NULL;
10099 BLOCK_INPUT;
10101 /* Create the X image and pixmap. */
10102 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10103 &img->pixmap))
10105 UNBLOCK_INPUT;
10106 goto error;
10109 /* Create an image and pixmap serving as mask if the PNG image
10110 contains an alpha channel. */
10111 if (channels == 4
10112 && !transparent_p
10113 && !x_create_x_image_and_pixmap (f, width, height, 1,
10114 &mask_img, &img->mask))
10116 x_destroy_x_image (ximg);
10117 XFreePixmap (FRAME_W32_DISPLAY (f), img->pixmap);
10118 img->pixmap = 0;
10119 UNBLOCK_INPUT;
10120 goto error;
10123 /* Fill the X image and mask from PNG data. */
10124 init_color_table ();
10126 for (y = 0; y < height; ++y)
10128 png_byte *p = rows[y];
10130 for (x = 0; x < width; ++x)
10132 unsigned r, g, b;
10134 r = *p++ << 8;
10135 g = *p++ << 8;
10136 b = *p++ << 8;
10137 XPutPixel (ximg, x, y, lookup_rgb_color (f, r, g, b));
10139 /* An alpha channel, aka mask channel, associates variable
10140 transparency with an image. Where other image formats
10141 support binary transparency---fully transparent or fully
10142 opaque---PNG allows up to 254 levels of partial transparency.
10143 The PNG library implements partial transparency by combining
10144 the image with a specified background color.
10146 I'm not sure how to handle this here nicely: because the
10147 background on which the image is displayed may change, for
10148 real alpha channel support, it would be necessary to create
10149 a new image for each possible background.
10151 What I'm doing now is that a mask is created if we have
10152 boolean transparency information. Otherwise I'm using
10153 the frame's background color to combine the image with. */
10155 if (channels == 4)
10157 if (mask_img)
10158 XPutPixel (mask_img, x, y, *p > 0);
10159 ++p;
10164 /* Remember colors allocated for this image. */
10165 img->colors = colors_in_color_table (&img->ncolors);
10166 free_color_table ();
10168 /* Clean up. */
10169 png_destroy_read_struct (&png_ptr, &info_ptr, &end_info);
10170 xfree (rows);
10171 xfree (pixels);
10173 img->width = width;
10174 img->height = height;
10176 /* Put the image into the pixmap, then free the X image and its buffer. */
10177 x_put_x_image (f, ximg, img->pixmap, width, height);
10178 x_destroy_x_image (ximg);
10180 /* Same for the mask. */
10181 if (mask_img)
10183 x_put_x_image (f, mask_img, img->mask, img->width, img->height);
10184 x_destroy_x_image (mask_img);
10187 UNBLOCK_INPUT;
10188 UNGCPRO;
10189 return 1;
10192 #endif /* HAVE_PNG != 0 */
10196 /***********************************************************************
10197 JPEG
10198 ***********************************************************************/
10200 #if HAVE_JPEG
10202 /* Work around a warning about HAVE_STDLIB_H being redefined in
10203 jconfig.h. */
10204 #ifdef HAVE_STDLIB_H
10205 #define HAVE_STDLIB_H_1
10206 #undef HAVE_STDLIB_H
10207 #endif /* HAVE_STLIB_H */
10209 #include <jpeglib.h>
10210 #include <jerror.h>
10211 #include <setjmp.h>
10213 #ifdef HAVE_STLIB_H_1
10214 #define HAVE_STDLIB_H 1
10215 #endif
10217 static int jpeg_image_p P_ ((Lisp_Object object));
10218 static int jpeg_load P_ ((struct frame *f, struct image *img));
10220 /* The symbol `jpeg' identifying images of this type. */
10222 Lisp_Object Qjpeg;
10224 /* Indices of image specification fields in gs_format, below. */
10226 enum jpeg_keyword_index
10228 JPEG_TYPE,
10229 JPEG_DATA,
10230 JPEG_FILE,
10231 JPEG_ASCENT,
10232 JPEG_MARGIN,
10233 JPEG_RELIEF,
10234 JPEG_ALGORITHM,
10235 JPEG_HEURISTIC_MASK,
10236 JPEG_LAST
10239 /* Vector of image_keyword structures describing the format
10240 of valid user-defined image specifications. */
10242 static struct image_keyword jpeg_format[JPEG_LAST] =
10244 {":type", IMAGE_SYMBOL_VALUE, 1},
10245 {":data", IMAGE_STRING_VALUE, 0},
10246 {":file", IMAGE_STRING_VALUE, 0},
10247 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10248 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10249 {":relief", IMAGE_INTEGER_VALUE, 0},
10250 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10251 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10254 /* Structure describing the image type `jpeg'. */
10256 static struct image_type jpeg_type =
10258 &Qjpeg,
10259 jpeg_image_p,
10260 jpeg_load,
10261 x_clear_image,
10262 NULL
10266 /* Return non-zero if OBJECT is a valid JPEG image specification. */
10268 static int
10269 jpeg_image_p (object)
10270 Lisp_Object object;
10272 struct image_keyword fmt[JPEG_LAST];
10274 bcopy (jpeg_format, fmt, sizeof fmt);
10276 if (!parse_image_spec (object, fmt, JPEG_LAST, Qjpeg)
10277 || (fmt[JPEG_ASCENT].count
10278 && XFASTINT (fmt[JPEG_ASCENT].value) > 100))
10279 return 0;
10281 /* Must specify either the :data or :file keyword. */
10282 return fmt[JPEG_FILE].count + fmt[JPEG_DATA].count == 1;
10286 struct my_jpeg_error_mgr
10288 struct jpeg_error_mgr pub;
10289 jmp_buf setjmp_buffer;
10292 static void
10293 my_error_exit (cinfo)
10294 j_common_ptr cinfo;
10296 struct my_jpeg_error_mgr *mgr = (struct my_jpeg_error_mgr *) cinfo->err;
10297 longjmp (mgr->setjmp_buffer, 1);
10301 /* Init source method for JPEG data source manager. Called by
10302 jpeg_read_header() before any data is actually read. See
10303 libjpeg.doc from the JPEG lib distribution. */
10305 static void
10306 our_init_source (cinfo)
10307 j_decompress_ptr cinfo;
10312 /* Fill input buffer method for JPEG data source manager. Called
10313 whenever more data is needed. We read the whole image in one step,
10314 so this only adds a fake end of input marker at the end. */
10316 static boolean
10317 our_fill_input_buffer (cinfo)
10318 j_decompress_ptr cinfo;
10320 /* Insert a fake EOI marker. */
10321 struct jpeg_source_mgr *src = cinfo->src;
10322 static JOCTET buffer[2];
10324 buffer[0] = (JOCTET) 0xFF;
10325 buffer[1] = (JOCTET) JPEG_EOI;
10327 src->next_input_byte = buffer;
10328 src->bytes_in_buffer = 2;
10329 return TRUE;
10333 /* Method to skip over NUM_BYTES bytes in the image data. CINFO->src
10334 is the JPEG data source manager. */
10336 static void
10337 our_skip_input_data (cinfo, num_bytes)
10338 j_decompress_ptr cinfo;
10339 long num_bytes;
10341 struct jpeg_source_mgr *src = (struct jpeg_source_mgr *) cinfo->src;
10343 if (src)
10345 if (num_bytes > src->bytes_in_buffer)
10346 ERREXIT (cinfo, JERR_INPUT_EOF);
10348 src->bytes_in_buffer -= num_bytes;
10349 src->next_input_byte += num_bytes;
10354 /* Method to terminate data source. Called by
10355 jpeg_finish_decompress() after all data has been processed. */
10357 static void
10358 our_term_source (cinfo)
10359 j_decompress_ptr cinfo;
10364 /* Set up the JPEG lib for reading an image from DATA which contains
10365 LEN bytes. CINFO is the decompression info structure created for
10366 reading the image. */
10368 static void
10369 jpeg_memory_src (cinfo, data, len)
10370 j_decompress_ptr cinfo;
10371 JOCTET *data;
10372 unsigned int len;
10374 struct jpeg_source_mgr *src;
10376 if (cinfo->src == NULL)
10378 /* First time for this JPEG object? */
10379 cinfo->src = (struct jpeg_source_mgr *)
10380 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
10381 sizeof (struct jpeg_source_mgr));
10382 src = (struct jpeg_source_mgr *) cinfo->src;
10383 src->next_input_byte = data;
10386 src = (struct jpeg_source_mgr *) cinfo->src;
10387 src->init_source = our_init_source;
10388 src->fill_input_buffer = our_fill_input_buffer;
10389 src->skip_input_data = our_skip_input_data;
10390 src->resync_to_restart = jpeg_resync_to_restart; /* Use default method. */
10391 src->term_source = our_term_source;
10392 src->bytes_in_buffer = len;
10393 src->next_input_byte = data;
10397 /* Load image IMG for use on frame F. Patterned after example.c
10398 from the JPEG lib. */
10400 static int
10401 jpeg_load (f, img)
10402 struct frame *f;
10403 struct image *img;
10405 struct jpeg_decompress_struct cinfo;
10406 struct my_jpeg_error_mgr mgr;
10407 Lisp_Object file, specified_file;
10408 Lisp_Object specified_data;
10409 FILE *fp = NULL;
10410 JSAMPARRAY buffer;
10411 int row_stride, x, y;
10412 XImage *ximg = NULL;
10413 int rc;
10414 unsigned long *colors;
10415 int width, height;
10416 struct gcpro gcpro1;
10418 /* Open the JPEG file. */
10419 specified_file = image_spec_value (img->spec, QCfile, NULL);
10420 specified_data = image_spec_value (img->spec, QCdata, NULL);
10421 file = Qnil;
10422 GCPRO1 (file);
10425 if (NILP (specified_data))
10427 file = x_find_image_file (specified_file);
10428 if (!STRINGP (file))
10430 image_error ("Cannot find image file `%s'", specified_file, Qnil);
10431 UNGCPRO;
10432 return 0;
10435 fp = fopen (XSTRING (file)->data, "r");
10436 if (fp == NULL)
10438 image_error ("Cannot open `%s'", file, Qnil);
10439 UNGCPRO;
10440 return 0;
10444 /* Customize libjpeg's error handling to call my_error_exit when an
10445 error is detected. This function will perform a longjmp. */
10446 mgr.pub.error_exit = my_error_exit;
10447 cinfo.err = jpeg_std_error (&mgr.pub);
10449 if ((rc = setjmp (mgr.setjmp_buffer)) != 0)
10451 if (rc == 1)
10453 /* Called from my_error_exit. Display a JPEG error. */
10454 char buffer[JMSG_LENGTH_MAX];
10455 cinfo.err->format_message ((j_common_ptr) &cinfo, buffer);
10456 image_error ("Error reading JPEG image `%s': %s", img->spec,
10457 build_string (buffer));
10460 /* Close the input file and destroy the JPEG object. */
10461 if (fp)
10462 fclose (fp);
10463 jpeg_destroy_decompress (&cinfo);
10465 BLOCK_INPUT;
10467 /* If we already have an XImage, free that. */
10468 x_destroy_x_image (ximg);
10470 /* Free pixmap and colors. */
10471 x_clear_image (f, img);
10473 UNBLOCK_INPUT;
10474 UNGCPRO;
10475 return 0;
10478 /* Create the JPEG decompression object. Let it read from fp.
10479 Read the JPEG image header. */
10480 jpeg_create_decompress (&cinfo);
10482 if (NILP (specified_data))
10483 jpeg_stdio_src (&cinfo, fp);
10484 else
10485 jpeg_memory_src (&cinfo, XSTRING (specified_data)->data,
10486 STRING_BYTES (XSTRING (specified_data)));
10488 jpeg_read_header (&cinfo, TRUE);
10490 /* Customize decompression so that color quantization will be used.
10491 Start decompression. */
10492 cinfo.quantize_colors = TRUE;
10493 jpeg_start_decompress (&cinfo);
10494 width = img->width = cinfo.output_width;
10495 height = img->height = cinfo.output_height;
10497 BLOCK_INPUT;
10499 /* Create X image and pixmap. */
10500 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg,
10501 &img->pixmap))
10503 UNBLOCK_INPUT;
10504 longjmp (mgr.setjmp_buffer, 2);
10507 /* Allocate colors. When color quantization is used,
10508 cinfo.actual_number_of_colors has been set with the number of
10509 colors generated, and cinfo.colormap is a two-dimensional array
10510 of color indices in the range 0..cinfo.actual_number_of_colors.
10511 No more than 255 colors will be generated. */
10513 int i, ir, ig, ib;
10515 if (cinfo.out_color_components > 2)
10516 ir = 0, ig = 1, ib = 2;
10517 else if (cinfo.out_color_components > 1)
10518 ir = 0, ig = 1, ib = 0;
10519 else
10520 ir = 0, ig = 0, ib = 0;
10522 /* Use the color table mechanism because it handles colors that
10523 cannot be allocated nicely. Such colors will be replaced with
10524 a default color, and we don't have to care about which colors
10525 can be freed safely, and which can't. */
10526 init_color_table ();
10527 colors = (unsigned long *) alloca (cinfo.actual_number_of_colors
10528 * sizeof *colors);
10530 for (i = 0; i < cinfo.actual_number_of_colors; ++i)
10532 /* Multiply RGB values with 255 because X expects RGB values
10533 in the range 0..0xffff. */
10534 int r = cinfo.colormap[ir][i] << 8;
10535 int g = cinfo.colormap[ig][i] << 8;
10536 int b = cinfo.colormap[ib][i] << 8;
10537 colors[i] = lookup_rgb_color (f, r, g, b);
10540 /* Remember those colors actually allocated. */
10541 img->colors = colors_in_color_table (&img->ncolors);
10542 free_color_table ();
10545 /* Read pixels. */
10546 row_stride = width * cinfo.output_components;
10547 buffer = cinfo.mem->alloc_sarray ((j_common_ptr) &cinfo, JPOOL_IMAGE,
10548 row_stride, 1);
10549 for (y = 0; y < height; ++y)
10551 jpeg_read_scanlines (&cinfo, buffer, 1);
10552 for (x = 0; x < cinfo.output_width; ++x)
10553 XPutPixel (ximg, x, y, colors[buffer[0][x]]);
10556 /* Clean up. */
10557 jpeg_finish_decompress (&cinfo);
10558 jpeg_destroy_decompress (&cinfo);
10559 if (fp)
10560 fclose (fp);
10562 /* Put the image into the pixmap. */
10563 x_put_x_image (f, ximg, img->pixmap, width, height);
10564 x_destroy_x_image (ximg);
10565 UNBLOCK_INPUT;
10566 UNGCPRO;
10567 return 1;
10570 #endif /* HAVE_JPEG */
10574 /***********************************************************************
10575 TIFF
10576 ***********************************************************************/
10578 #if HAVE_TIFF
10580 #include <tiffio.h>
10582 static int tiff_image_p P_ ((Lisp_Object object));
10583 static int tiff_load P_ ((struct frame *f, struct image *img));
10585 /* The symbol `tiff' identifying images of this type. */
10587 Lisp_Object Qtiff;
10589 /* Indices of image specification fields in tiff_format, below. */
10591 enum tiff_keyword_index
10593 TIFF_TYPE,
10594 TIFF_DATA,
10595 TIFF_FILE,
10596 TIFF_ASCENT,
10597 TIFF_MARGIN,
10598 TIFF_RELIEF,
10599 TIFF_ALGORITHM,
10600 TIFF_HEURISTIC_MASK,
10601 TIFF_LAST
10604 /* Vector of image_keyword structures describing the format
10605 of valid user-defined image specifications. */
10607 static struct image_keyword tiff_format[TIFF_LAST] =
10609 {":type", IMAGE_SYMBOL_VALUE, 1},
10610 {":data", IMAGE_STRING_VALUE, 0},
10611 {":file", IMAGE_STRING_VALUE, 0},
10612 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10613 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10614 {":relief", IMAGE_INTEGER_VALUE, 0},
10615 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10616 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
10619 /* Structure describing the image type `tiff'. */
10621 static struct image_type tiff_type =
10623 &Qtiff,
10624 tiff_image_p,
10625 tiff_load,
10626 x_clear_image,
10627 NULL
10631 /* Return non-zero if OBJECT is a valid TIFF image specification. */
10633 static int
10634 tiff_image_p (object)
10635 Lisp_Object object;
10637 struct image_keyword fmt[TIFF_LAST];
10638 bcopy (tiff_format, fmt, sizeof fmt);
10640 if (!parse_image_spec (object, fmt, TIFF_LAST, Qtiff)
10641 || (fmt[TIFF_ASCENT].count
10642 && XFASTINT (fmt[TIFF_ASCENT].value) > 100))
10643 return 0;
10645 /* Must specify either the :data or :file keyword. */
10646 return fmt[TIFF_FILE].count + fmt[TIFF_DATA].count == 1;
10650 /* Reading from a memory buffer for TIFF images Based on the PNG
10651 memory source, but we have to provide a lot of extra functions.
10652 Blah.
10654 We really only need to implement read and seek, but I am not
10655 convinced that the TIFF library is smart enough not to destroy
10656 itself if we only hand it the function pointers we need to
10657 override. */
10659 typedef struct
10661 unsigned char *bytes;
10662 size_t len;
10663 int index;
10665 tiff_memory_source;
10667 static size_t
10668 tiff_read_from_memory (data, buf, size)
10669 thandle_t data;
10670 tdata_t buf;
10671 tsize_t size;
10673 tiff_memory_source *src = (tiff_memory_source *) data;
10675 if (size > src->len - src->index)
10676 return (size_t) -1;
10677 bcopy (src->bytes + src->index, buf, size);
10678 src->index += size;
10679 return size;
10682 static size_t
10683 tiff_write_from_memory (data, buf, size)
10684 thandle_t data;
10685 tdata_t buf;
10686 tsize_t size;
10688 return (size_t) -1;
10691 static toff_t
10692 tiff_seek_in_memory (data, off, whence)
10693 thandle_t data;
10694 toff_t off;
10695 int whence;
10697 tiff_memory_source *src = (tiff_memory_source *) data;
10698 int idx;
10700 switch (whence)
10702 case SEEK_SET: /* Go from beginning of source. */
10703 idx = off;
10704 break;
10706 case SEEK_END: /* Go from end of source. */
10707 idx = src->len + off;
10708 break;
10710 case SEEK_CUR: /* Go from current position. */
10711 idx = src->index + off;
10712 break;
10714 default: /* Invalid `whence'. */
10715 return -1;
10718 if (idx > src->len || idx < 0)
10719 return -1;
10721 src->index = idx;
10722 return src->index;
10725 static int
10726 tiff_close_memory (data)
10727 thandle_t data;
10729 /* NOOP */
10730 return 0;
10733 static int
10734 tiff_mmap_memory (data, pbase, psize)
10735 thandle_t data;
10736 tdata_t *pbase;
10737 toff_t *psize;
10739 /* It is already _IN_ memory. */
10740 return 0;
10743 static void
10744 tiff_unmap_memory (data, base, size)
10745 thandle_t data;
10746 tdata_t base;
10747 toff_t size;
10749 /* We don't need to do this. */
10752 static toff_t
10753 tiff_size_of_memory (data)
10754 thandle_t data;
10756 return ((tiff_memory_source *) data)->len;
10760 /* Load TIFF image IMG for use on frame F. Value is non-zero if
10761 successful. */
10763 static int
10764 tiff_load (f, img)
10765 struct frame *f;
10766 struct image *img;
10768 Lisp_Object file, specified_file;
10769 Lisp_Object specified_data;
10770 TIFF *tiff;
10771 int width, height, x, y;
10772 uint32 *buf;
10773 int rc;
10774 XImage *ximg;
10775 struct gcpro gcpro1;
10776 tiff_memory_source memsrc;
10778 specified_file = image_spec_value (img->spec, QCfile, NULL);
10779 specified_data = image_spec_value (img->spec, QCdata, NULL);
10780 file = Qnil;
10781 GCPRO1 (file);
10783 if (NILP (specified_data))
10785 /* Read from a file */
10786 file = x_find_image_file (specified_file);
10787 if (!STRINGP (file))
10789 image_error ("Cannot find image file `%s'", file, Qnil);
10790 UNGCPRO;
10791 return 0;
10794 /* Try to open the image file. */
10795 tiff = TIFFOpen (XSTRING (file)->data, "r");
10796 if (tiff == NULL)
10798 image_error ("Cannot open `%s'", file, Qnil);
10799 UNGCPRO;
10800 return 0;
10803 else
10805 /* Memory source! */
10806 memsrc.bytes = XSTRING (specified_data)->data;
10807 memsrc.len = STRING_BYTES (XSTRING (specified_data));
10808 memsrc.index = 0;
10810 tiff = TIFFClientOpen ("memory_source", "r", &memsrc,
10811 (TIFFReadWriteProc) tiff_read_from_memory,
10812 (TIFFReadWriteProc) tiff_write_from_memory,
10813 tiff_seek_in_memory,
10814 tiff_close_memory,
10815 tiff_size_of_memory,
10816 tiff_mmap_memory,
10817 tiff_unmap_memory);
10819 if (!tiff)
10821 image_error ("Cannot open memory source for `%s'", img->spec, Qnil);
10822 UNGCPRO;
10823 return 0;
10827 /* Get width and height of the image, and allocate a raster buffer
10828 of width x height 32-bit values. */
10829 TIFFGetField (tiff, TIFFTAG_IMAGEWIDTH, &width);
10830 TIFFGetField (tiff, TIFFTAG_IMAGELENGTH, &height);
10831 buf = (uint32 *) xmalloc (width * height * sizeof *buf);
10833 rc = TIFFReadRGBAImage (tiff, width, height, buf, 0);
10834 TIFFClose (tiff);
10835 if (!rc)
10837 image_error ("Error reading TIFF image `%s'", img->spec, Qnil);
10838 xfree (buf);
10839 UNGCPRO;
10840 return 0;
10843 BLOCK_INPUT;
10845 /* Create the X image and pixmap. */
10846 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
10848 UNBLOCK_INPUT;
10849 xfree (buf);
10850 UNGCPRO;
10851 return 0;
10854 /* Initialize the color table. */
10855 init_color_table ();
10857 /* Process the pixel raster. Origin is in the lower-left corner. */
10858 for (y = 0; y < height; ++y)
10860 uint32 *row = buf + y * width;
10862 for (x = 0; x < width; ++x)
10864 uint32 abgr = row[x];
10865 int r = TIFFGetR (abgr) << 8;
10866 int g = TIFFGetG (abgr) << 8;
10867 int b = TIFFGetB (abgr) << 8;
10868 XPutPixel (ximg, x, height - 1 - y, lookup_rgb_color (f, r, g, b));
10872 /* Remember the colors allocated for the image. Free the color table. */
10873 img->colors = colors_in_color_table (&img->ncolors);
10874 free_color_table ();
10876 /* Put the image into the pixmap, then free the X image and its buffer. */
10877 x_put_x_image (f, ximg, img->pixmap, width, height);
10878 x_destroy_x_image (ximg);
10879 xfree (buf);
10880 UNBLOCK_INPUT;
10882 img->width = width;
10883 img->height = height;
10885 UNGCPRO;
10886 return 1;
10889 #endif /* HAVE_TIFF != 0 */
10893 /***********************************************************************
10895 ***********************************************************************/
10897 #if HAVE_GIF
10899 #include <gif_lib.h>
10901 static int gif_image_p P_ ((Lisp_Object object));
10902 static int gif_load P_ ((struct frame *f, struct image *img));
10904 /* The symbol `gif' identifying images of this type. */
10906 Lisp_Object Qgif;
10908 /* Indices of image specification fields in gif_format, below. */
10910 enum gif_keyword_index
10912 GIF_TYPE,
10913 GIF_DATA,
10914 GIF_FILE,
10915 GIF_ASCENT,
10916 GIF_MARGIN,
10917 GIF_RELIEF,
10918 GIF_ALGORITHM,
10919 GIF_HEURISTIC_MASK,
10920 GIF_IMAGE,
10921 GIF_LAST
10924 /* Vector of image_keyword structures describing the format
10925 of valid user-defined image specifications. */
10927 static struct image_keyword gif_format[GIF_LAST] =
10929 {":type", IMAGE_SYMBOL_VALUE, 1},
10930 {":data", IMAGE_STRING_VALUE, 0},
10931 {":file", IMAGE_STRING_VALUE, 0},
10932 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
10933 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
10934 {":relief", IMAGE_INTEGER_VALUE, 0},
10935 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10936 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
10937 {":image", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0}
10940 /* Structure describing the image type `gif'. */
10942 static struct image_type gif_type =
10944 &Qgif,
10945 gif_image_p,
10946 gif_load,
10947 x_clear_image,
10948 NULL
10951 /* Return non-zero if OBJECT is a valid GIF image specification. */
10953 static int
10954 gif_image_p (object)
10955 Lisp_Object object;
10957 struct image_keyword fmt[GIF_LAST];
10958 bcopy (gif_format, fmt, sizeof fmt);
10960 if (!parse_image_spec (object, fmt, GIF_LAST, Qgif)
10961 || (fmt[GIF_ASCENT].count
10962 && XFASTINT (fmt[GIF_ASCENT].value) > 100))
10963 return 0;
10965 /* Must specify either the :data or :file keyword. */
10966 return fmt[GIF_FILE].count + fmt[GIF_DATA].count == 1;
10969 /* Reading a GIF image from memory
10970 Based on the PNG memory stuff to a certain extent. */
10972 typedef struct
10974 unsigned char *bytes;
10975 size_t len;
10976 int index;
10978 gif_memory_source;
10980 /* Make the current memory source available to gif_read_from_memory.
10981 It's done this way because not all versions of libungif support
10982 a UserData field in the GifFileType structure. */
10983 static gif_memory_source *current_gif_memory_src;
10985 static int
10986 gif_read_from_memory (file, buf, len)
10987 GifFileType *file;
10988 GifByteType *buf;
10989 int len;
10991 gif_memory_source *src = current_gif_memory_src;
10993 if (len > src->len - src->index)
10994 return -1;
10996 bcopy (src->bytes + src->index, buf, len);
10997 src->index += len;
10998 return len;
11002 /* Load GIF image IMG for use on frame F. Value is non-zero if
11003 successful. */
11005 static int
11006 gif_load (f, img)
11007 struct frame *f;
11008 struct image *img;
11010 Lisp_Object file, specified_file;
11011 Lisp_Object specified_data;
11012 int rc, width, height, x, y, i;
11013 XImage *ximg;
11014 ColorMapObject *gif_color_map;
11015 unsigned long pixel_colors[256];
11016 GifFileType *gif;
11017 struct gcpro gcpro1;
11018 Lisp_Object image;
11019 int ino, image_left, image_top, image_width, image_height;
11020 gif_memory_source memsrc;
11021 unsigned char *raster;
11023 specified_file = image_spec_value (img->spec, QCfile, NULL);
11024 specified_data = image_spec_value (img->spec, QCdata, NULL);
11025 file = Qnil;
11027 if (NILP (specified_data))
11029 file = x_find_image_file (specified_file);
11030 GCPRO1 (file);
11031 if (!STRINGP (file))
11033 image_error ("Cannot find image file `%s'", specified_file, Qnil);
11034 UNGCPRO;
11035 return 0;
11038 /* Open the GIF file. */
11039 gif = DGifOpenFileName (XSTRING (file)->data);
11040 if (gif == NULL)
11042 image_error ("Cannot open `%s'", file, Qnil);
11043 UNGCPRO;
11044 return 0;
11047 else
11049 /* Read from memory! */
11050 current_gif_memory_src = &memsrc;
11051 memsrc.bytes = XSTRING (specified_data)->data;
11052 memsrc.len = STRING_BYTES (XSTRING (specified_data));
11053 memsrc.index = 0;
11055 gif = DGifOpen(&memsrc, gif_read_from_memory);
11056 if (!gif)
11058 image_error ("Cannot open memory source `%s'", img->spec, Qnil);
11059 UNGCPRO;
11060 return 0;
11064 /* Read entire contents. */
11065 rc = DGifSlurp (gif);
11066 if (rc == GIF_ERROR)
11068 image_error ("Error reading `%s'", img->spec, Qnil);
11069 DGifCloseFile (gif);
11070 UNGCPRO;
11071 return 0;
11074 image = image_spec_value (img->spec, QCindex, NULL);
11075 ino = INTEGERP (image) ? XFASTINT (image) : 0;
11076 if (ino >= gif->ImageCount)
11078 image_error ("Invalid image number `%s' in image `%s'",
11079 image, img->spec);
11080 DGifCloseFile (gif);
11081 UNGCPRO;
11082 return 0;
11085 width = img->width = gif->SWidth;
11086 height = img->height = gif->SHeight;
11088 BLOCK_INPUT;
11090 /* Create the X image and pixmap. */
11091 if (!x_create_x_image_and_pixmap (f, width, height, 0, &ximg, &img->pixmap))
11093 UNBLOCK_INPUT;
11094 DGifCloseFile (gif);
11095 UNGCPRO;
11096 return 0;
11099 /* Allocate colors. */
11100 gif_color_map = gif->SavedImages[ino].ImageDesc.ColorMap;
11101 if (!gif_color_map)
11102 gif_color_map = gif->SColorMap;
11103 init_color_table ();
11104 bzero (pixel_colors, sizeof pixel_colors);
11106 for (i = 0; i < gif_color_map->ColorCount; ++i)
11108 int r = gif_color_map->Colors[i].Red << 8;
11109 int g = gif_color_map->Colors[i].Green << 8;
11110 int b = gif_color_map->Colors[i].Blue << 8;
11111 pixel_colors[i] = lookup_rgb_color (f, r, g, b);
11114 img->colors = colors_in_color_table (&img->ncolors);
11115 free_color_table ();
11117 /* Clear the part of the screen image that are not covered by
11118 the image from the GIF file. Full animated GIF support
11119 requires more than can be done here (see the gif89 spec,
11120 disposal methods). Let's simply assume that the part
11121 not covered by a sub-image is in the frame's background color. */
11122 image_top = gif->SavedImages[ino].ImageDesc.Top;
11123 image_left = gif->SavedImages[ino].ImageDesc.Left;
11124 image_width = gif->SavedImages[ino].ImageDesc.Width;
11125 image_height = gif->SavedImages[ino].ImageDesc.Height;
11127 for (y = 0; y < image_top; ++y)
11128 for (x = 0; x < width; ++x)
11129 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11131 for (y = image_top + image_height; y < height; ++y)
11132 for (x = 0; x < width; ++x)
11133 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11135 for (y = image_top; y < image_top + image_height; ++y)
11137 for (x = 0; x < image_left; ++x)
11138 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11139 for (x = image_left + image_width; x < width; ++x)
11140 XPutPixel (ximg, x, y, FRAME_BACKGROUND_PIXEL (f));
11143 /* Read the GIF image into the X image. We use a local variable
11144 `raster' here because RasterBits below is a char *, and invites
11145 problems with bytes >= 0x80. */
11146 raster = (unsigned char *) gif->SavedImages[ino].RasterBits;
11148 if (gif->SavedImages[ino].ImageDesc.Interlace)
11150 static int interlace_start[] = {0, 4, 2, 1};
11151 static int interlace_increment[] = {8, 8, 4, 2};
11152 int pass, inc;
11153 int row = interlace_start[0];
11155 pass = 0;
11157 for (y = 0; y < image_height; y++)
11159 if (row >= image_height)
11161 row = interlace_start[++pass];
11162 while (row >= image_height)
11163 row = interlace_start[++pass];
11166 for (x = 0; x < image_width; x++)
11168 int i = raster[(y * image_width) + x];
11169 XPutPixel (ximg, x + image_left, row + image_top,
11170 pixel_colors[i]);
11173 row += interlace_increment[pass];
11176 else
11178 for (y = 0; y < image_height; ++y)
11179 for (x = 0; x < image_width; ++x)
11181 int i = raster[y* image_width + x];
11182 XPutPixel (ximg, x + image_left, y + image_top, pixel_colors[i]);
11186 DGifCloseFile (gif);
11188 /* Put the image into the pixmap, then free the X image and its buffer. */
11189 x_put_x_image (f, ximg, img->pixmap, width, height);
11190 x_destroy_x_image (ximg);
11191 UNBLOCK_INPUT;
11193 UNGCPRO;
11194 return 1;
11197 #endif /* HAVE_GIF != 0 */
11201 /***********************************************************************
11202 Ghostscript
11203 ***********************************************************************/
11205 #ifdef HAVE_GHOSTSCRIPT
11206 static int gs_image_p P_ ((Lisp_Object object));
11207 static int gs_load P_ ((struct frame *f, struct image *img));
11208 static void gs_clear_image P_ ((struct frame *f, struct image *img));
11210 /* The symbol `postscript' identifying images of this type. */
11212 Lisp_Object Qpostscript;
11214 /* Keyword symbols. */
11216 Lisp_Object QCloader, QCbounding_box, QCpt_width, QCpt_height;
11218 /* Indices of image specification fields in gs_format, below. */
11220 enum gs_keyword_index
11222 GS_TYPE,
11223 GS_PT_WIDTH,
11224 GS_PT_HEIGHT,
11225 GS_FILE,
11226 GS_LOADER,
11227 GS_BOUNDING_BOX,
11228 GS_ASCENT,
11229 GS_MARGIN,
11230 GS_RELIEF,
11231 GS_ALGORITHM,
11232 GS_HEURISTIC_MASK,
11233 GS_LAST
11236 /* Vector of image_keyword structures describing the format
11237 of valid user-defined image specifications. */
11239 static struct image_keyword gs_format[GS_LAST] =
11241 {":type", IMAGE_SYMBOL_VALUE, 1},
11242 {":pt-width", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11243 {":pt-height", IMAGE_POSITIVE_INTEGER_VALUE, 1},
11244 {":file", IMAGE_STRING_VALUE, 1},
11245 {":loader", IMAGE_FUNCTION_VALUE, 0},
11246 {":bounding-box", IMAGE_DONT_CHECK_VALUE_TYPE, 1},
11247 {":ascent", IMAGE_NON_NEGATIVE_INTEGER_VALUE, 0},
11248 {":margin", IMAGE_POSITIVE_INTEGER_VALUE, 0},
11249 {":relief", IMAGE_INTEGER_VALUE, 0},
11250 {":algorithm", IMAGE_DONT_CHECK_VALUE_TYPE, 0},
11251 {":heuristic-mask", IMAGE_DONT_CHECK_VALUE_TYPE, 0}
11254 /* Structure describing the image type `ghostscript'. */
11256 static struct image_type gs_type =
11258 &Qpostscript,
11259 gs_image_p,
11260 gs_load,
11261 gs_clear_image,
11262 NULL
11266 /* Free X resources of Ghostscript image IMG which is used on frame F. */
11268 static void
11269 gs_clear_image (f, img)
11270 struct frame *f;
11271 struct image *img;
11273 /* IMG->data.ptr_val may contain a recorded colormap. */
11274 xfree (img->data.ptr_val);
11275 x_clear_image (f, img);
11279 /* Return non-zero if OBJECT is a valid Ghostscript image
11280 specification. */
11282 static int
11283 gs_image_p (object)
11284 Lisp_Object object;
11286 struct image_keyword fmt[GS_LAST];
11287 Lisp_Object tem;
11288 int i;
11290 bcopy (gs_format, fmt, sizeof fmt);
11292 if (!parse_image_spec (object, fmt, GS_LAST, Qpostscript)
11293 || (fmt[GS_ASCENT].count
11294 && XFASTINT (fmt[GS_ASCENT].value) > 100))
11295 return 0;
11297 /* Bounding box must be a list or vector containing 4 integers. */
11298 tem = fmt[GS_BOUNDING_BOX].value;
11299 if (CONSP (tem))
11301 for (i = 0; i < 4; ++i, tem = XCDR (tem))
11302 if (!CONSP (tem) || !INTEGERP (XCAR (tem)))
11303 return 0;
11304 if (!NILP (tem))
11305 return 0;
11307 else if (VECTORP (tem))
11309 if (XVECTOR (tem)->size != 4)
11310 return 0;
11311 for (i = 0; i < 4; ++i)
11312 if (!INTEGERP (XVECTOR (tem)->contents[i]))
11313 return 0;
11315 else
11316 return 0;
11318 return 1;
11322 /* Load Ghostscript image IMG for use on frame F. Value is non-zero
11323 if successful. */
11325 static int
11326 gs_load (f, img)
11327 struct frame *f;
11328 struct image *img;
11330 char buffer[100];
11331 Lisp_Object window_and_pixmap_id = Qnil, loader, pt_height, pt_width;
11332 struct gcpro gcpro1, gcpro2;
11333 Lisp_Object frame;
11334 double in_width, in_height;
11335 Lisp_Object pixel_colors = Qnil;
11337 /* Compute pixel size of pixmap needed from the given size in the
11338 image specification. Sizes in the specification are in pt. 1 pt
11339 = 1/72 in, xdpi and ydpi are stored in the frame's X display
11340 info. */
11341 pt_width = image_spec_value (img->spec, QCpt_width, NULL);
11342 in_width = XFASTINT (pt_width) / 72.0;
11343 img->width = in_width * FRAME_W32_DISPLAY_INFO (f)->resx;
11344 pt_height = image_spec_value (img->spec, QCpt_height, NULL);
11345 in_height = XFASTINT (pt_height) / 72.0;
11346 img->height = in_height * FRAME_W32_DISPLAY_INFO (f)->resy;
11348 /* Create the pixmap. */
11349 BLOCK_INPUT;
11350 xassert (img->pixmap == 0);
11351 img->pixmap = XCreatePixmap (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11352 img->width, img->height,
11353 DefaultDepthOfScreen (FRAME_X_SCREEN (f)));
11354 UNBLOCK_INPUT;
11356 if (!img->pixmap)
11358 image_error ("Unable to create pixmap for `%s'", img->spec, Qnil);
11359 return 0;
11362 /* Call the loader to fill the pixmap. It returns a process object
11363 if successful. We do not record_unwind_protect here because
11364 other places in redisplay like calling window scroll functions
11365 don't either. Let the Lisp loader use `unwind-protect' instead. */
11366 GCPRO2 (window_and_pixmap_id, pixel_colors);
11368 sprintf (buffer, "%lu %lu",
11369 (unsigned long) FRAME_W32_WINDOW (f),
11370 (unsigned long) img->pixmap);
11371 window_and_pixmap_id = build_string (buffer);
11373 sprintf (buffer, "%lu %lu",
11374 FRAME_FOREGROUND_PIXEL (f),
11375 FRAME_BACKGROUND_PIXEL (f));
11376 pixel_colors = build_string (buffer);
11378 XSETFRAME (frame, f);
11379 loader = image_spec_value (img->spec, QCloader, NULL);
11380 if (NILP (loader))
11381 loader = intern ("gs-load-image");
11383 img->data.lisp_val = call6 (loader, frame, img->spec,
11384 make_number (img->width),
11385 make_number (img->height),
11386 window_and_pixmap_id,
11387 pixel_colors);
11388 UNGCPRO;
11389 return PROCESSP (img->data.lisp_val);
11393 /* Kill the Ghostscript process that was started to fill PIXMAP on
11394 frame F. Called from XTread_socket when receiving an event
11395 telling Emacs that Ghostscript has finished drawing. */
11397 void
11398 x_kill_gs_process (pixmap, f)
11399 Pixmap pixmap;
11400 struct frame *f;
11402 struct image_cache *c = FRAME_X_IMAGE_CACHE (f);
11403 int class, i;
11404 struct image *img;
11406 /* Find the image containing PIXMAP. */
11407 for (i = 0; i < c->used; ++i)
11408 if (c->images[i]->pixmap == pixmap)
11409 break;
11411 /* Kill the GS process. We should have found PIXMAP in the image
11412 cache and its image should contain a process object. */
11413 xassert (i < c->used);
11414 img = c->images[i];
11415 xassert (PROCESSP (img->data.lisp_val));
11416 Fkill_process (img->data.lisp_val, Qnil);
11417 img->data.lisp_val = Qnil;
11419 /* On displays with a mutable colormap, figure out the colors
11420 allocated for the image by looking at the pixels of an XImage for
11421 img->pixmap. */
11422 class = FRAME_W32_DISPLAY_INFO (f)->visual->class;
11423 if (class != StaticColor && class != StaticGray && class != TrueColor)
11425 XImage *ximg;
11427 BLOCK_INPUT;
11429 /* Try to get an XImage for img->pixmep. */
11430 ximg = XGetImage (FRAME_W32_DISPLAY (f), img->pixmap,
11431 0, 0, img->width, img->height, ~0, ZPixmap);
11432 if (ximg)
11434 int x, y;
11436 /* Initialize the color table. */
11437 init_color_table ();
11439 /* For each pixel of the image, look its color up in the
11440 color table. After having done so, the color table will
11441 contain an entry for each color used by the image. */
11442 for (y = 0; y < img->height; ++y)
11443 for (x = 0; x < img->width; ++x)
11445 unsigned long pixel = XGetPixel (ximg, x, y);
11446 lookup_pixel_color (f, pixel);
11449 /* Record colors in the image. Free color table and XImage. */
11450 img->colors = colors_in_color_table (&img->ncolors);
11451 free_color_table ();
11452 XDestroyImage (ximg);
11454 #if 0 /* This doesn't seem to be the case. If we free the colors
11455 here, we get a BadAccess later in x_clear_image when
11456 freeing the colors. */
11457 /* We have allocated colors once, but Ghostscript has also
11458 allocated colors on behalf of us. So, to get the
11459 reference counts right, free them once. */
11460 if (img->ncolors)
11462 Colormap cmap = DefaultColormapOfScreen (FRAME_X_SCREEN (f));
11463 XFreeColors (FRAME_W32_DISPLAY (f), cmap,
11464 img->colors, img->ncolors, 0);
11466 #endif
11468 else
11469 image_error ("Cannot get X image of `%s'; colors will not be freed",
11470 img->spec, Qnil);
11472 UNBLOCK_INPUT;
11476 #endif /* HAVE_GHOSTSCRIPT */
11479 /***********************************************************************
11480 Window properties
11481 ***********************************************************************/
11483 DEFUN ("x-change-window-property", Fx_change_window_property,
11484 Sx_change_window_property, 2, 3, 0,
11485 "Change window property PROP to VALUE on the X window of FRAME.\n\
11486 PROP and VALUE must be strings. FRAME nil or omitted means use the\n\
11487 selected frame. Value is VALUE.")
11488 (prop, value, frame)
11489 Lisp_Object frame, prop, value;
11491 #if 0 /* NTEMACS_TODO : port window properties to W32 */
11492 struct frame *f = check_x_frame (frame);
11493 Atom prop_atom;
11495 CHECK_STRING (prop, 1);
11496 CHECK_STRING (value, 2);
11498 BLOCK_INPUT;
11499 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11500 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11501 prop_atom, XA_STRING, 8, PropModeReplace,
11502 XSTRING (value)->data, XSTRING (value)->size);
11504 /* Make sure the property is set when we return. */
11505 XFlush (FRAME_W32_DISPLAY (f));
11506 UNBLOCK_INPUT;
11508 #endif /* NTEMACS_TODO */
11510 return value;
11514 DEFUN ("x-delete-window-property", Fx_delete_window_property,
11515 Sx_delete_window_property, 1, 2, 0,
11516 "Remove window property PROP from X window of FRAME.\n\
11517 FRAME nil or omitted means use the selected frame. Value is PROP.")
11518 (prop, frame)
11519 Lisp_Object prop, frame;
11521 #if 0 /* NTEMACS_TODO : port window properties to W32 */
11523 struct frame *f = check_x_frame (frame);
11524 Atom prop_atom;
11526 CHECK_STRING (prop, 1);
11527 BLOCK_INPUT;
11528 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11529 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
11531 /* Make sure the property is removed when we return. */
11532 XFlush (FRAME_W32_DISPLAY (f));
11533 UNBLOCK_INPUT;
11534 #endif /* NTEMACS_TODO */
11536 return prop;
11540 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
11541 1, 2, 0,
11542 "Value is the value of window property PROP on FRAME.\n\
11543 If FRAME is nil or omitted, use the selected frame. Value is nil\n\
11544 if FRAME hasn't a property with name PROP or if PROP has no string\n\
11545 value.")
11546 (prop, frame)
11547 Lisp_Object prop, frame;
11549 #if 0 /* NTEMACS_TODO : port window properties to W32 */
11551 struct frame *f = check_x_frame (frame);
11552 Atom prop_atom;
11553 int rc;
11554 Lisp_Object prop_value = Qnil;
11555 char *tmp_data = NULL;
11556 Atom actual_type;
11557 int actual_format;
11558 unsigned long actual_size, bytes_remaining;
11560 CHECK_STRING (prop, 1);
11561 BLOCK_INPUT;
11562 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), XSTRING (prop)->data, False);
11563 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11564 prop_atom, 0, 0, False, XA_STRING,
11565 &actual_type, &actual_format, &actual_size,
11566 &bytes_remaining, (unsigned char **) &tmp_data);
11567 if (rc == Success)
11569 int size = bytes_remaining;
11571 XFree (tmp_data);
11572 tmp_data = NULL;
11574 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
11575 prop_atom, 0, bytes_remaining,
11576 False, XA_STRING,
11577 &actual_type, &actual_format,
11578 &actual_size, &bytes_remaining,
11579 (unsigned char **) &tmp_data);
11580 if (rc == Success)
11581 prop_value = make_string (tmp_data, size);
11583 XFree (tmp_data);
11586 UNBLOCK_INPUT;
11588 return prop_value;
11590 #endif /* NTEMACS_TODO */
11591 return Qnil;
11596 /***********************************************************************
11597 Busy cursor
11598 ***********************************************************************/
11600 /* The implementation partly follows a patch from
11601 F.Pierresteguy@frcl.bull.fr dated 1994. */
11603 /* Setting inhibit_busy_cursor to 2 inhibits busy-cursor display until
11604 the next X event is read and we enter XTread_socket again. Setting
11605 it to 1 inhibits busy-cursor display for direct commands. */
11607 int inhibit_busy_cursor;
11609 /* Incremented with each call to x-display-busy-cursor.
11610 Decremented in x-undisplay-busy-cursor. */
11612 static int busy_count;
11615 DEFUN ("x-show-busy-cursor", Fx_show_busy_cursor,
11616 Sx_show_busy_cursor, 0, 0, 0,
11617 "Show a busy cursor, if not already shown.\n\
11618 Each call to this function must be matched by a call to\n\
11619 x-undisplay-busy-cursor to make the busy pointer disappear again.")
11622 ++busy_count;
11623 if (busy_count == 1)
11625 Lisp_Object rest, frame;
11627 FOR_EACH_FRAME (rest, frame)
11628 if (FRAME_X_P (XFRAME (frame)))
11630 struct frame *f = XFRAME (frame);
11631 #if 0 /* NTEMACS_TODO : busy cursor */
11633 BLOCK_INPUT;
11634 f->output_data.w32->busy_p = 1;
11636 if (!f->output_data.w32->busy_window)
11638 unsigned long mask = CWCursor;
11639 XSetWindowAttributes attrs;
11641 attrs.cursor = f->output_data.w32->busy_cursor;
11642 f->output_data.w32->busy_window
11643 = XCreateWindow (FRAME_W32_DISPLAY (f),
11644 FRAME_OUTER_WINDOW (f),
11645 0, 0, 32000, 32000, 0, 0,
11646 InputOnly, CopyFromParent,
11647 mask, &attrs);
11650 XMapRaised (FRAME_W32_DISPLAY (f), f->output_data.w32->busy_window);
11651 UNBLOCK_INPUT;
11652 #endif
11656 return Qnil;
11660 DEFUN ("x-hide-busy-cursor", Fx_hide_busy_cursor,
11661 Sx_hide_busy_cursor, 0, 1, 0,
11662 "Hide a busy-cursor.\n\
11663 A busy-cursor will actually be undisplayed when a matching\n\
11664 `x-undisplay-busy-cursor' is called for each `x-display-busy-cursor'\n\
11665 issued. FORCE non-nil means undisplay the busy-cursor forcibly,\n\
11666 not counting calls.")
11667 (force)
11668 Lisp_Object force;
11670 Lisp_Object rest, frame;
11672 if (busy_count == 0)
11673 return Qnil;
11675 if (!NILP (force) && busy_count != 0)
11676 busy_count = 1;
11678 --busy_count;
11679 if (busy_count != 0)
11680 return Qnil;
11682 FOR_EACH_FRAME (rest, frame)
11684 struct frame *f = XFRAME (frame);
11686 if (FRAME_X_P (f)
11687 /* Watch out for newly created frames. */
11688 && f->output_data.w32->busy_window)
11690 #if 0 /* NTEMACS_TODO : busy cursor */
11691 BLOCK_INPUT;
11692 XUnmapWindow (FRAME_W32_DISPLAY (f), f->output_data.w32->busy_window);
11693 /* Sync here because XTread_socket looks at the busy_p flag
11694 that is reset to zero below. */
11695 XSync (FRAME_W32_DISPLAY (f), False);
11696 UNBLOCK_INPUT;
11697 f->output_data.w32->busy_p = 0;
11698 #endif
11702 return Qnil;
11707 /***********************************************************************
11708 Tool tips
11709 ***********************************************************************/
11711 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
11712 Lisp_Object));
11714 /* The frame of a currently visible tooltip, or null. */
11716 struct frame *tip_frame;
11718 /* If non-nil, a timer started that hides the last tooltip when it
11719 fires. */
11721 Lisp_Object tip_timer;
11722 Window tip_window;
11724 /* Create a frame for a tooltip on the display described by DPYINFO.
11725 PARMS is a list of frame parameters. Value is the frame. */
11727 static Lisp_Object
11728 x_create_tip_frame (dpyinfo, parms)
11729 struct w32_display_info *dpyinfo;
11730 Lisp_Object parms;
11732 #if 0 /* NTEMACS_TODO : w32 version */
11733 struct frame *f;
11734 Lisp_Object frame, tem;
11735 Lisp_Object name;
11736 long window_prompting = 0;
11737 int width, height;
11738 int count = specpdl_ptr - specpdl;
11739 struct gcpro gcpro1, gcpro2, gcpro3;
11740 struct kboard *kb;
11742 check_x ();
11744 /* Use this general default value to start with until we know if
11745 this frame has a specified name. */
11746 Vx_resource_name = Vinvocation_name;
11748 #ifdef MULTI_KBOARD
11749 kb = dpyinfo->kboard;
11750 #else
11751 kb = &the_only_kboard;
11752 #endif
11754 /* Get the name of the frame to use for resource lookup. */
11755 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
11756 if (!STRINGP (name)
11757 && !EQ (name, Qunbound)
11758 && !NILP (name))
11759 error ("Invalid frame name--not a string or nil");
11760 Vx_resource_name = name;
11762 frame = Qnil;
11763 GCPRO3 (parms, name, frame);
11764 tip_frame = f = make_frame (1);
11765 XSETFRAME (frame, f);
11766 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
11768 f->output_method = output_w32;
11769 f->output_data.w32 =
11770 (struct w32_output *) xmalloc (sizeof (struct w32_output));
11771 bzero (f->output_data.w32, sizeof (struct w32_output));
11772 #if 0
11773 f->output_data.w32->icon_bitmap = -1;
11774 #endif
11775 f->output_data.w32->fontset = -1;
11776 f->icon_name = Qnil;
11778 #ifdef MULTI_KBOARD
11779 FRAME_KBOARD (f) = kb;
11780 #endif
11781 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
11782 f->output_data.w32->explicit_parent = 0;
11784 /* Set the name; the functions to which we pass f expect the name to
11785 be set. */
11786 if (EQ (name, Qunbound) || NILP (name))
11788 f->name = build_string (dpyinfo->x_id_name);
11789 f->explicit_name = 0;
11791 else
11793 f->name = name;
11794 f->explicit_name = 1;
11795 /* use the frame's title when getting resources for this frame. */
11796 specbind (Qx_resource_name, name);
11799 /* Create fontsets from `global_fontset_alist' before handling fonts. */
11800 for (tem = Vglobal_fontset_alist; CONSP (tem); tem = XCDR (tem))
11801 fs_register_fontset (f, XCAR (tem));
11803 /* Extract the window parameters from the supplied values
11804 that are needed to determine window geometry. */
11806 Lisp_Object font;
11808 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
11810 BLOCK_INPUT;
11811 /* First, try whatever font the caller has specified. */
11812 if (STRINGP (font))
11814 tem = Fquery_fontset (font, Qnil);
11815 if (STRINGP (tem))
11816 font = x_new_fontset (f, XSTRING (tem)->data);
11817 else
11818 font = x_new_font (f, XSTRING (font)->data);
11821 /* Try out a font which we hope has bold and italic variations. */
11822 if (!STRINGP (font))
11823 font = x_new_font (f, "-adobe-courier-medium-r-*-*-*-120-*-*-*-*-iso8859-1");
11824 if (!STRINGP (font))
11825 font = x_new_font (f, "-misc-fixed-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
11826 if (! STRINGP (font))
11827 font = x_new_font (f, "-*-*-medium-r-normal-*-*-140-*-*-c-*-iso8859-1");
11828 if (! STRINGP (font))
11829 /* This was formerly the first thing tried, but it finds too many fonts
11830 and takes too long. */
11831 font = x_new_font (f, "-*-*-medium-r-*-*-*-*-*-*-c-*-iso8859-1");
11832 /* If those didn't work, look for something which will at least work. */
11833 if (! STRINGP (font))
11834 font = x_new_font (f, "-*-fixed-*-*-*-*-*-140-*-*-c-*-iso8859-1");
11835 UNBLOCK_INPUT;
11836 if (! STRINGP (font))
11837 font = build_string ("fixed");
11839 x_default_parameter (f, parms, Qfont, font,
11840 "font", "Font", RES_TYPE_STRING);
11843 x_default_parameter (f, parms, Qborder_width, make_number (2),
11844 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
11846 /* This defaults to 2 in order to match xterm. We recognize either
11847 internalBorderWidth or internalBorder (which is what xterm calls
11848 it). */
11849 if (NILP (Fassq (Qinternal_border_width, parms)))
11851 Lisp_Object value;
11853 value = w32_get_arg (parms, Qinternal_border_width,
11854 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
11855 if (! EQ (value, Qunbound))
11856 parms = Fcons (Fcons (Qinternal_border_width, value),
11857 parms);
11860 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
11861 "internalBorderWidth", "internalBorderWidth",
11862 RES_TYPE_NUMBER);
11864 /* Also do the stuff which must be set before the window exists. */
11865 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
11866 "foreground", "Foreground", RES_TYPE_STRING);
11867 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
11868 "background", "Background", RES_TYPE_STRING);
11869 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
11870 "pointerColor", "Foreground", RES_TYPE_STRING);
11871 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
11872 "cursorColor", "Foreground", RES_TYPE_STRING);
11873 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
11874 "borderColor", "BorderColor", RES_TYPE_STRING);
11876 /* Init faces before x_default_parameter is called for scroll-bar
11877 parameters because that function calls x_set_scroll_bar_width,
11878 which calls change_frame_size, which calls Fset_window_buffer,
11879 which runs hooks, which call Fvertical_motion. At the end, we
11880 end up in init_iterator with a null face cache, which should not
11881 happen. */
11882 init_frame_faces (f);
11884 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
11885 window_prompting = x_figure_window_size (f, parms);
11887 if (window_prompting & XNegative)
11889 if (window_prompting & YNegative)
11890 f->output_data.w32->win_gravity = SouthEastGravity;
11891 else
11892 f->output_data.w32->win_gravity = NorthEastGravity;
11894 else
11896 if (window_prompting & YNegative)
11897 f->output_data.w32->win_gravity = SouthWestGravity;
11898 else
11899 f->output_data.w32->win_gravity = NorthWestGravity;
11902 f->output_data.w32->size_hint_flags = window_prompting;
11904 XSetWindowAttributes attrs;
11905 unsigned long mask;
11907 BLOCK_INPUT;
11908 mask = CWBackPixel | CWOverrideRedirect | CWSaveUnder | CWEventMask;
11909 /* Window managers looks at the override-redirect flag to
11910 determine whether or net to give windows a decoration (Xlib
11911 3.2.8). */
11912 attrs.override_redirect = True;
11913 attrs.save_under = True;
11914 attrs.background_pixel = FRAME_BACKGROUND_PIXEL (f);
11915 /* Arrange for getting MapNotify and UnmapNotify events. */
11916 attrs.event_mask = StructureNotifyMask;
11917 tip_window
11918 = FRAME_W32_WINDOW (f)
11919 = XCreateWindow (FRAME_W32_DISPLAY (f),
11920 FRAME_W32_DISPLAY_INFO (f)->root_window,
11921 /* x, y, width, height */
11922 0, 0, 1, 1,
11923 /* Border. */
11925 CopyFromParent, InputOutput, CopyFromParent,
11926 mask, &attrs);
11927 UNBLOCK_INPUT;
11930 x_make_gc (f);
11932 x_default_parameter (f, parms, Qauto_raise, Qnil,
11933 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
11934 x_default_parameter (f, parms, Qauto_lower, Qnil,
11935 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
11936 x_default_parameter (f, parms, Qcursor_type, Qbox,
11937 "cursorType", "CursorType", RES_TYPE_SYMBOL);
11939 /* Dimensions, especially f->height, must be done via change_frame_size.
11940 Change will not be effected unless different from the current
11941 f->height. */
11942 width = f->width;
11943 height = f->height;
11944 f->height = 0;
11945 SET_FRAME_WIDTH (f, 0);
11946 change_frame_size (f, height, width, 1, 0, 0);
11948 f->no_split = 1;
11950 UNGCPRO;
11952 /* It is now ok to make the frame official even if we get an error
11953 below. And the frame needs to be on Vframe_list or making it
11954 visible won't work. */
11955 Vframe_list = Fcons (frame, Vframe_list);
11957 /* Now that the frame is official, it counts as a reference to
11958 its display. */
11959 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
11961 return unbind_to (count, frame);
11962 #endif /* NTEMACS_TODO */
11963 return Qnil;
11967 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 4, 0,
11968 "Show STRING in a \"tooltip\" window on frame FRAME.\n\
11969 A tooltip window is a small X window displaying STRING at\n\
11970 the current mouse position.\n\
11971 FRAME nil or omitted means use the selected frame.\n\
11972 PARMS is an optional list of frame parameters which can be\n\
11973 used to change the tooltip's appearance.\n\
11974 Automatically hide the tooltip after TIMEOUT seconds.\n\
11975 TIMEOUT nil means use the default timeout of 5 seconds.")
11976 (string, frame, parms, timeout)
11977 Lisp_Object string, frame, parms, timeout;
11979 struct frame *f;
11980 struct window *w;
11981 Window root, child;
11982 Lisp_Object buffer;
11983 struct buffer *old_buffer;
11984 struct text_pos pos;
11985 int i, width, height;
11986 int root_x, root_y, win_x, win_y;
11987 unsigned pmask;
11988 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
11989 int old_windows_or_buffers_changed = windows_or_buffers_changed;
11990 int count = specpdl_ptr - specpdl;
11992 specbind (Qinhibit_redisplay, Qt);
11994 GCPRO3 (string, parms, frame, timeout);
11996 CHECK_STRING (string, 0);
11997 f = check_x_frame (frame);
11998 if (NILP (timeout))
11999 timeout = make_number (5);
12000 else
12001 CHECK_NATNUM (timeout, 2);
12003 /* Hide a previous tip, if any. */
12004 Fx_hide_tip ();
12006 /* Add default values to frame parameters. */
12007 if (NILP (Fassq (Qname, parms)))
12008 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
12009 if (NILP (Fassq (Qinternal_border_width, parms)))
12010 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
12011 if (NILP (Fassq (Qborder_width, parms)))
12012 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
12013 if (NILP (Fassq (Qborder_color, parms)))
12014 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
12015 if (NILP (Fassq (Qbackground_color, parms)))
12016 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
12017 parms);
12019 /* Create a frame for the tooltip, and record it in the global
12020 variable tip_frame. */
12021 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms);
12022 tip_frame = f = XFRAME (frame);
12024 /* Set up the frame's root window. Currently we use a size of 80
12025 columns x 40 lines. If someone wants to show a larger tip, he
12026 will loose. I don't think this is a realistic case. */
12027 w = XWINDOW (FRAME_ROOT_WINDOW (f));
12028 w->left = w->top = make_number (0);
12029 w->width = 80;
12030 w->height = 40;
12031 adjust_glyphs (f);
12032 w->pseudo_window_p = 1;
12034 /* Display the tooltip text in a temporary buffer. */
12035 buffer = Fget_buffer_create (build_string (" *tip*"));
12036 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer);
12037 old_buffer = current_buffer;
12038 set_buffer_internal_1 (XBUFFER (buffer));
12039 Ferase_buffer ();
12040 Finsert (make_number (1), &string);
12041 clear_glyph_matrix (w->desired_matrix);
12042 clear_glyph_matrix (w->current_matrix);
12043 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
12044 try_window (FRAME_ROOT_WINDOW (f), pos);
12046 /* Compute width and height of the tooltip. */
12047 width = height = 0;
12048 for (i = 0; i < w->desired_matrix->nrows; ++i)
12050 struct glyph_row *row = &w->desired_matrix->rows[i];
12051 struct glyph *last;
12052 int row_width;
12054 /* Stop at the first empty row at the end. */
12055 if (!row->enabled_p || !row->displays_text_p)
12056 break;
12058 /* Let the row go over the full width of the frame. */
12059 row->full_width_p = 1;
12061 /* There's a glyph at the end of rows that is use to place
12062 the cursor there. Don't include the width of this glyph. */
12063 if (row->used[TEXT_AREA])
12065 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
12066 row_width = row->pixel_width - last->pixel_width;
12068 else
12069 row_width = row->pixel_width;
12071 height += row->height;
12072 width = max (width, row_width);
12075 /* Add the frame's internal border to the width and height the X
12076 window should have. */
12077 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12078 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
12080 /* Move the tooltip window where the mouse pointer is. Resize and
12081 show it. */
12082 #if 0 /* NTEMACS_TODO : W32 specifics */
12083 BLOCK_INPUT;
12084 XQueryPointer (FRAME_W32_DISPLAY (f), FRAME_W32_DISPLAY_INFO (f)->root_window,
12085 &root, &child, &root_x, &root_y, &win_x, &win_y, &pmask);
12086 XMoveResizeWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
12087 root_x + 5, root_y - height - 5, width, height);
12088 XMapRaised (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
12089 UNBLOCK_INPUT;
12090 #endif /* NTEMACS_TODO */
12092 /* Draw into the window. */
12093 w->must_be_updated_p = 1;
12094 update_single_window (w, 1);
12096 /* Restore original current buffer. */
12097 set_buffer_internal_1 (old_buffer);
12098 windows_or_buffers_changed = old_windows_or_buffers_changed;
12100 /* Let the tip disappear after timeout seconds. */
12101 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
12102 intern ("x-hide-tip"));
12103 UNGCPRO;
12105 return unbind_to (count, Qnil);
12109 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
12110 "Hide the current tooltip window, if there is any.\n\
12111 Value is t is tooltip was open, nil otherwise.")
12114 int count = specpdl_ptr - specpdl;
12115 int deleted_p = 0;
12117 specbind (Qinhibit_redisplay, Qt);
12119 if (!NILP (tip_timer))
12121 call1 (intern ("cancel-timer"), tip_timer);
12122 tip_timer = Qnil;
12125 if (tip_frame)
12127 Lisp_Object frame;
12129 XSETFRAME (frame, tip_frame);
12130 Fdelete_frame (frame, Qt);
12131 tip_frame = NULL;
12132 deleted_p = 1;
12135 return unbind_to (count, deleted_p ? Qt : Qnil);
12140 /***********************************************************************
12141 File selection dialog
12142 ***********************************************************************/
12144 extern Lisp_Object Qfile_name_history;
12146 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 4, 0,
12147 "Read file name, prompting with PROMPT in directory DIR.\n\
12148 Use a file selection dialog.\n\
12149 Select DEFAULT-FILENAME in the dialog's file selection box, if\n\
12150 specified. Don't let the user enter a file name in the file\n\
12151 selection dialog's entry field, if MUSTMATCH is non-nil.")
12152 (prompt, dir, default_filename, mustmatch)
12153 Lisp_Object prompt, dir, default_filename, mustmatch;
12155 struct frame *f = SELECTED_FRAME ();
12156 Lisp_Object file = Qnil;
12157 int count = specpdl_ptr - specpdl;
12158 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
12159 char filename[MAX_PATH + 1];
12160 char init_dir[MAX_PATH + 1];
12161 int use_dialog_p = 1;
12163 GCPRO5 (prompt, dir, default_filename, mustmatch, file);
12164 CHECK_STRING (prompt, 0);
12165 CHECK_STRING (dir, 1);
12167 /* Create the dialog with PROMPT as title, using DIR as initial
12168 directory and using "*" as pattern. */
12169 dir = Fexpand_file_name (dir, Qnil);
12170 strncpy (init_dir, XSTRING (dir)->data, MAX_PATH);
12171 init_dir[MAX_PATH] = '\0';
12172 unixtodos_filename (init_dir);
12174 if (STRINGP (default_filename))
12176 char *file_name_only;
12177 char *full_path_name = XSTRING (default_filename)->data;
12179 unixtodos_filename (full_path_name);
12181 file_name_only = strrchr (full_path_name, '\\');
12182 if (!file_name_only)
12183 file_name_only = full_path_name;
12184 else
12186 file_name_only++;
12188 /* If default_file_name is a directory, don't use the open
12189 file dialog, as it does not support selecting
12190 directories. */
12191 if (!(*file_name_only))
12192 use_dialog_p = 0;
12195 strncpy (filename, file_name_only, MAX_PATH);
12196 filename[MAX_PATH] = '\0';
12198 else
12199 filename[0] = '\0';
12201 if (use_dialog_p)
12203 OPENFILENAME file_details;
12204 char *filename_file;
12206 /* Prevent redisplay. */
12207 specbind (Qinhibit_redisplay, Qt);
12208 BLOCK_INPUT;
12210 bzero (&file_details, sizeof (file_details));
12211 file_details.lStructSize = sizeof (file_details);
12212 file_details.hwndOwner = FRAME_W32_WINDOW (f);
12213 file_details.lpstrFile = filename;
12214 file_details.nMaxFile = sizeof (filename);
12215 file_details.lpstrInitialDir = init_dir;
12216 file_details.lpstrTitle = XSTRING (prompt)->data;
12217 file_details.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR;
12219 if (!NILP (mustmatch))
12220 file_details.Flags |= OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
12222 if (GetOpenFileName (&file_details))
12224 dostounix_filename (filename);
12225 file = build_string (filename);
12227 else
12228 file = Qnil;
12230 UNBLOCK_INPUT;
12231 file = unbind_to (count, file);
12233 /* Open File dialog will not allow folders to be selected, so resort
12234 to minibuffer completing reads for directories. */
12235 else
12236 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
12237 dir, mustmatch, dir, Qfile_name_history,
12238 default_filename, Qnil);
12240 UNGCPRO;
12242 /* Make "Cancel" equivalent to C-g. */
12243 if (NILP (file))
12244 Fsignal (Qquit, Qnil);
12246 return file;
12251 /***********************************************************************
12252 Tests
12253 ***********************************************************************/
12255 #if GLYPH_DEBUG
12257 DEFUN ("imagep", Fimagep, Simagep, 1, 1, 0,
12258 "Value is non-nil if SPEC is a valid image specification.")
12259 (spec)
12260 Lisp_Object spec;
12262 return valid_image_p (spec) ? Qt : Qnil;
12266 DEFUN ("lookup-image", Flookup_image, Slookup_image, 1, 1, 0, "")
12267 (spec)
12268 Lisp_Object spec;
12270 int id = -1;
12272 if (valid_image_p (spec))
12273 id = lookup_image (SELECTED_FRAME (), spec);
12275 debug_print (spec);
12276 return make_number (id);
12279 #endif /* GLYPH_DEBUG != 0 */
12283 /***********************************************************************
12284 w32 specialized functions
12285 ***********************************************************************/
12287 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 1, 0,
12288 "This will display the W32 font dialog and return an X font string corresponding to the selection.")
12289 (frame)
12290 Lisp_Object frame;
12292 FRAME_PTR f = check_x_frame (frame);
12293 CHOOSEFONT cf;
12294 LOGFONT lf;
12295 TEXTMETRIC tm;
12296 HDC hdc;
12297 HANDLE oldobj;
12298 char buf[100];
12300 bzero (&cf, sizeof (cf));
12301 bzero (&lf, sizeof (lf));
12303 cf.lStructSize = sizeof (cf);
12304 cf.hwndOwner = FRAME_W32_WINDOW (f);
12305 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS;
12306 cf.lpLogFont = &lf;
12308 /* Initialize as much of the font details as we can from the current
12309 default font. */
12310 hdc = GetDC (FRAME_W32_WINDOW (f));
12311 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
12312 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
12313 if (GetTextMetrics (hdc, &tm))
12315 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
12316 lf.lfWeight = tm.tmWeight;
12317 lf.lfItalic = tm.tmItalic;
12318 lf.lfUnderline = tm.tmUnderlined;
12319 lf.lfStrikeOut = tm.tmStruckOut;
12320 lf.lfCharSet = tm.tmCharSet;
12321 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
12323 SelectObject (hdc, oldobj);
12324 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
12326 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100))
12327 return Qnil;
12329 return build_string (buf);
12332 DEFUN ("w32-send-sys-command", Fw32_send_sys_command, Sw32_send_sys_command, 1, 2, 0,
12333 "Send frame a Windows WM_SYSCOMMAND message of type COMMAND.\n\
12334 Some useful values for command are 0xf030 to maximise frame (0xf020\n\
12335 to minimize), 0xf120 to restore frame to original size, and 0xf100\n\
12336 to activate the menubar for keyboard access. 0xf140 activates the\n\
12337 screen saver if defined.\n\
12339 If optional parameter FRAME is not specified, use selected frame.")
12340 (command, frame)
12341 Lisp_Object command, frame;
12343 WPARAM code;
12344 FRAME_PTR f = check_x_frame (frame);
12346 CHECK_NUMBER (command, 0);
12348 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
12350 return Qnil;
12353 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
12354 "Get Windows to perform OPERATION on DOCUMENT.\n\
12355 This is a wrapper around the ShellExecute system function, which\n\
12356 invokes the application registered to handle OPERATION for DOCUMENT.\n\
12357 OPERATION is typically \"open\", \"print\" or \"explore\" (but can be\n\
12358 nil for the default action), and DOCUMENT is typically the name of a\n\
12359 document file or URL, but can also be a program executable to run or\n\
12360 a directory to open in the Windows Explorer.\n\
12362 If DOCUMENT is a program executable, PARAMETERS can be a string\n\
12363 containing command line parameters, but otherwise should be nil.\n\
12365 SHOW-FLAG can be used to control whether the invoked application is hidden\n\
12366 or minimized. If SHOW-FLAG is nil, the application is displayed normally,\n\
12367 otherwise it is an integer representing a ShowWindow flag:\n\
12369 0 - start hidden\n\
12370 1 - start normally\n\
12371 3 - start maximized\n\
12372 6 - start minimized")
12373 (operation, document, parameters, show_flag)
12374 Lisp_Object operation, document, parameters, show_flag;
12376 Lisp_Object current_dir;
12378 CHECK_STRING (document, 0);
12380 /* Encode filename and current directory. */
12381 current_dir = ENCODE_FILE (current_buffer->directory);
12382 document = ENCODE_FILE (document);
12383 if ((int) ShellExecute (NULL,
12384 (STRINGP (operation) ?
12385 XSTRING (operation)->data : NULL),
12386 XSTRING (document)->data,
12387 (STRINGP (parameters) ?
12388 XSTRING (parameters)->data : NULL),
12389 XSTRING (current_dir)->data,
12390 (INTEGERP (show_flag) ?
12391 XINT (show_flag) : SW_SHOWDEFAULT))
12392 > 32)
12393 return Qt;
12394 error ("ShellExecute failed");
12397 /* Lookup virtual keycode from string representing the name of a
12398 non-ascii keystroke into the corresponding virtual key, using
12399 lispy_function_keys. */
12400 static int
12401 lookup_vk_code (char *key)
12403 int i;
12405 for (i = 0; i < 256; i++)
12406 if (lispy_function_keys[i] != 0
12407 && strcmp (lispy_function_keys[i], key) == 0)
12408 return i;
12410 return -1;
12413 /* Convert a one-element vector style key sequence to a hot key
12414 definition. */
12415 static int
12416 w32_parse_hot_key (key)
12417 Lisp_Object key;
12419 /* Copied from Fdefine_key and store_in_keymap. */
12420 register Lisp_Object c;
12421 int vk_code;
12422 int lisp_modifiers;
12423 int w32_modifiers;
12424 struct gcpro gcpro1;
12426 CHECK_VECTOR (key, 0);
12428 if (XFASTINT (Flength (key)) != 1)
12429 return Qnil;
12431 GCPRO1 (key);
12433 c = Faref (key, make_number (0));
12435 if (CONSP (c) && lucid_event_type_list_p (c))
12436 c = Fevent_convert_list (c);
12438 UNGCPRO;
12440 if (! INTEGERP (c) && ! SYMBOLP (c))
12441 error ("Key definition is invalid");
12443 /* Work out the base key and the modifiers. */
12444 if (SYMBOLP (c))
12446 c = parse_modifiers (c);
12447 lisp_modifiers = Fcar (Fcdr (c));
12448 c = Fcar (c);
12449 if (!SYMBOLP (c))
12450 abort ();
12451 vk_code = lookup_vk_code (XSYMBOL (c)->name->data);
12453 else if (INTEGERP (c))
12455 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
12456 /* Many ascii characters are their own virtual key code. */
12457 vk_code = XINT (c) & CHARACTERBITS;
12460 if (vk_code < 0 || vk_code > 255)
12461 return Qnil;
12463 if ((lisp_modifiers & meta_modifier) != 0
12464 && !NILP (Vw32_alt_is_meta))
12465 lisp_modifiers |= alt_modifier;
12467 /* Convert lisp modifiers to Windows hot-key form. */
12468 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
12469 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
12470 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
12471 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
12473 return HOTKEY (vk_code, w32_modifiers);
12476 DEFUN ("w32-register-hot-key", Fw32_register_hot_key, Sw32_register_hot_key, 1, 1, 0,
12477 "Register KEY as a hot-key combination.\n\
12478 Certain key combinations like Alt-Tab are reserved for system use on\n\
12479 Windows, and therefore are normally intercepted by the system. However,\n\
12480 most of these key combinations can be received by registering them as\n\
12481 hot-keys, overriding their special meaning.\n\
12483 KEY must be a one element key definition in vector form that would be\n\
12484 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta\n\
12485 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper\n\
12486 is always interpreted as the Windows modifier keys.\n\
12488 The return value is the hotkey-id if registered, otherwise nil.")
12489 (key)
12490 Lisp_Object key;
12492 key = w32_parse_hot_key (key);
12494 if (NILP (Fmemq (key, w32_grabbed_keys)))
12496 /* Reuse an empty slot if possible. */
12497 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
12499 /* Safe to add new key to list, even if we have focus. */
12500 if (NILP (item))
12501 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
12502 else
12503 XCAR (item) = key;
12505 /* Notify input thread about new hot-key definition, so that it
12506 takes effect without needing to switch focus. */
12507 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
12508 (WPARAM) key, 0);
12511 return key;
12514 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key, Sw32_unregister_hot_key, 1, 1, 0,
12515 "Unregister HOTKEY as a hot-key combination.")
12516 (key)
12517 Lisp_Object key;
12519 Lisp_Object item;
12521 if (!INTEGERP (key))
12522 key = w32_parse_hot_key (key);
12524 item = Fmemq (key, w32_grabbed_keys);
12526 if (!NILP (item))
12528 /* Notify input thread about hot-key definition being removed, so
12529 that it takes effect without needing focus switch. */
12530 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
12531 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
12533 MSG msg;
12534 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
12536 return Qt;
12538 return Qnil;
12541 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys, Sw32_registered_hot_keys, 0, 0, 0,
12542 "Return list of registered hot-key IDs.")
12545 return Fcopy_sequence (w32_grabbed_keys);
12548 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key, Sw32_reconstruct_hot_key, 1, 1, 0,
12549 "Convert hot-key ID to a lisp key combination.")
12550 (hotkeyid)
12551 Lisp_Object hotkeyid;
12553 int vk_code, w32_modifiers;
12554 Lisp_Object key;
12556 CHECK_NUMBER (hotkeyid, 0);
12558 vk_code = HOTKEY_VK_CODE (hotkeyid);
12559 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
12561 if (lispy_function_keys[vk_code])
12562 key = intern (lispy_function_keys[vk_code]);
12563 else
12564 key = make_number (vk_code);
12566 key = Fcons (key, Qnil);
12567 if (w32_modifiers & MOD_SHIFT)
12568 key = Fcons (Qshift, key);
12569 if (w32_modifiers & MOD_CONTROL)
12570 key = Fcons (Qctrl, key);
12571 if (w32_modifiers & MOD_ALT)
12572 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
12573 if (w32_modifiers & MOD_WIN)
12574 key = Fcons (Qhyper, key);
12576 return key;
12579 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key, Sw32_toggle_lock_key, 1, 2, 0,
12580 "Toggle the state of the lock key KEY.\n\
12581 KEY can be `capslock', `kp-numlock', or `scroll'.\n\
12582 If the optional parameter NEW-STATE is a number, then the state of KEY\n\
12583 is set to off if the low bit of NEW-STATE is zero, otherwise on.")
12584 (key, new_state)
12585 Lisp_Object key, new_state;
12587 int vk_code;
12588 int cur_state;
12590 if (EQ (key, intern ("capslock")))
12591 vk_code = VK_CAPITAL;
12592 else if (EQ (key, intern ("kp-numlock")))
12593 vk_code = VK_NUMLOCK;
12594 else if (EQ (key, intern ("scroll")))
12595 vk_code = VK_SCROLL;
12596 else
12597 return Qnil;
12599 if (!dwWindowsThreadId)
12600 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
12602 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
12603 (WPARAM) vk_code, (LPARAM) new_state))
12605 MSG msg;
12606 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
12607 return make_number (msg.wParam);
12609 return Qnil;
12612 syms_of_w32fns ()
12614 /* This is zero if not using MS-Windows. */
12615 w32_in_use = 0;
12617 /* The section below is built by the lisp expression at the top of the file,
12618 just above where these variables are declared. */
12619 /*&&& init symbols here &&&*/
12620 Qauto_raise = intern ("auto-raise");
12621 staticpro (&Qauto_raise);
12622 Qauto_lower = intern ("auto-lower");
12623 staticpro (&Qauto_lower);
12624 Qbar = intern ("bar");
12625 staticpro (&Qbar);
12626 Qborder_color = intern ("border-color");
12627 staticpro (&Qborder_color);
12628 Qborder_width = intern ("border-width");
12629 staticpro (&Qborder_width);
12630 Qbox = intern ("box");
12631 staticpro (&Qbox);
12632 Qcursor_color = intern ("cursor-color");
12633 staticpro (&Qcursor_color);
12634 Qcursor_type = intern ("cursor-type");
12635 staticpro (&Qcursor_type);
12636 Qgeometry = intern ("geometry");
12637 staticpro (&Qgeometry);
12638 Qicon_left = intern ("icon-left");
12639 staticpro (&Qicon_left);
12640 Qicon_top = intern ("icon-top");
12641 staticpro (&Qicon_top);
12642 Qicon_type = intern ("icon-type");
12643 staticpro (&Qicon_type);
12644 Qicon_name = intern ("icon-name");
12645 staticpro (&Qicon_name);
12646 Qinternal_border_width = intern ("internal-border-width");
12647 staticpro (&Qinternal_border_width);
12648 Qleft = intern ("left");
12649 staticpro (&Qleft);
12650 Qright = intern ("right");
12651 staticpro (&Qright);
12652 Qmouse_color = intern ("mouse-color");
12653 staticpro (&Qmouse_color);
12654 Qnone = intern ("none");
12655 staticpro (&Qnone);
12656 Qparent_id = intern ("parent-id");
12657 staticpro (&Qparent_id);
12658 Qscroll_bar_width = intern ("scroll-bar-width");
12659 staticpro (&Qscroll_bar_width);
12660 Qsuppress_icon = intern ("suppress-icon");
12661 staticpro (&Qsuppress_icon);
12662 Qundefined_color = intern ("undefined-color");
12663 staticpro (&Qundefined_color);
12664 Qvertical_scroll_bars = intern ("vertical-scroll-bars");
12665 staticpro (&Qvertical_scroll_bars);
12666 Qvisibility = intern ("visibility");
12667 staticpro (&Qvisibility);
12668 Qwindow_id = intern ("window-id");
12669 staticpro (&Qwindow_id);
12670 Qx_frame_parameter = intern ("x-frame-parameter");
12671 staticpro (&Qx_frame_parameter);
12672 Qx_resource_name = intern ("x-resource-name");
12673 staticpro (&Qx_resource_name);
12674 Quser_position = intern ("user-position");
12675 staticpro (&Quser_position);
12676 Quser_size = intern ("user-size");
12677 staticpro (&Quser_size);
12678 #if 0 /* Duplicate initialization in xdisp.c */
12679 Qdisplay = intern ("display");
12680 staticpro (&Qdisplay);
12681 #endif
12682 Qscreen_gamma = intern ("screen-gamma");
12683 staticpro (&Qscreen_gamma);
12684 /* This is the end of symbol initialization. */
12686 Qhyper = intern ("hyper");
12687 staticpro (&Qhyper);
12688 Qsuper = intern ("super");
12689 staticpro (&Qsuper);
12690 Qmeta = intern ("meta");
12691 staticpro (&Qmeta);
12692 Qalt = intern ("alt");
12693 staticpro (&Qalt);
12694 Qctrl = intern ("ctrl");
12695 staticpro (&Qctrl);
12696 Qcontrol = intern ("control");
12697 staticpro (&Qcontrol);
12698 Qshift = intern ("shift");
12699 staticpro (&Qshift);
12701 /* Text property `display' should be nonsticky by default. */
12702 Vtext_property_default_nonsticky
12703 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
12706 Qlaplace = intern ("laplace");
12707 staticpro (&Qlaplace);
12709 Qface_set_after_frame_default = intern ("face-set-after-frame-default");
12710 staticpro (&Qface_set_after_frame_default);
12712 Fput (Qundefined_color, Qerror_conditions,
12713 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
12714 Fput (Qundefined_color, Qerror_message,
12715 build_string ("Undefined color"));
12717 staticpro (&w32_grabbed_keys);
12718 w32_grabbed_keys = Qnil;
12720 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
12721 "An array of color name mappings for windows.");
12722 Vw32_color_map = Qnil;
12724 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
12725 "Non-nil if alt key presses are passed on to Windows.\n\
12726 When non-nil, for example, alt pressed and released and then space will\n\
12727 open the System menu. When nil, Emacs silently swallows alt key events.");
12728 Vw32_pass_alt_to_system = Qnil;
12730 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
12731 "Non-nil if the alt key is to be considered the same as the meta key.\n\
12732 When nil, Emacs will translate the alt key to the Alt modifier, and not Meta.");
12733 Vw32_alt_is_meta = Qt;
12735 DEFVAR_INT ("w32-quit-key", &Vw32_quit_key,
12736 "If non-zero, the virtual key code for an alternative quit key.");
12737 XSETINT (Vw32_quit_key, 0);
12739 DEFVAR_LISP ("w32-pass-lwindow-to-system",
12740 &Vw32_pass_lwindow_to_system,
12741 "Non-nil if the left \"Windows\" key is passed on to Windows.\n\
12742 When non-nil, the Start menu is opened by tapping the key.");
12743 Vw32_pass_lwindow_to_system = Qt;
12745 DEFVAR_LISP ("w32-pass-rwindow-to-system",
12746 &Vw32_pass_rwindow_to_system,
12747 "Non-nil if the right \"Windows\" key is passed on to Windows.\n\
12748 When non-nil, the Start menu is opened by tapping the key.");
12749 Vw32_pass_rwindow_to_system = Qt;
12751 DEFVAR_INT ("w32-phantom-key-code",
12752 &Vw32_phantom_key_code,
12753 "Virtual key code used to generate \"phantom\" key presses.\n\
12754 Value is a number between 0 and 255.\n\
12756 Phantom key presses are generated in order to stop the system from\n\
12757 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or\n\
12758 `w32-pass-rwindow-to-system' is nil.");
12759 /* Although 255 is technically not a valid key code, it works and
12760 means that this hack won't interfere with any real key code. */
12761 Vw32_phantom_key_code = 255;
12763 DEFVAR_LISP ("w32-enable-num-lock",
12764 &Vw32_enable_num_lock,
12765 "Non-nil if Num Lock should act normally.\n\
12766 Set to nil to see Num Lock as the key `kp-numlock'.");
12767 Vw32_enable_num_lock = Qt;
12769 DEFVAR_LISP ("w32-enable-caps-lock",
12770 &Vw32_enable_caps_lock,
12771 "Non-nil if Caps Lock should act normally.\n\
12772 Set to nil to see Caps Lock as the key `capslock'.");
12773 Vw32_enable_caps_lock = Qt;
12775 DEFVAR_LISP ("w32-scroll-lock-modifier",
12776 &Vw32_scroll_lock_modifier,
12777 "Modifier to use for the Scroll Lock on state.\n\
12778 The value can be hyper, super, meta, alt, control or shift for the\n\
12779 respective modifier, or nil to see Scroll Lock as the key `scroll'.\n\
12780 Any other value will cause the key to be ignored.");
12781 Vw32_scroll_lock_modifier = Qt;
12783 DEFVAR_LISP ("w32-lwindow-modifier",
12784 &Vw32_lwindow_modifier,
12785 "Modifier to use for the left \"Windows\" key.\n\
12786 The value can be hyper, super, meta, alt, control or shift for the\n\
12787 respective modifier, or nil to appear as the key `lwindow'.\n\
12788 Any other value will cause the key to be ignored.");
12789 Vw32_lwindow_modifier = Qnil;
12791 DEFVAR_LISP ("w32-rwindow-modifier",
12792 &Vw32_rwindow_modifier,
12793 "Modifier to use for the right \"Windows\" key.\n\
12794 The value can be hyper, super, meta, alt, control or shift for the\n\
12795 respective modifier, or nil to appear as the key `rwindow'.\n\
12796 Any other value will cause the key to be ignored.");
12797 Vw32_rwindow_modifier = Qnil;
12799 DEFVAR_LISP ("w32-apps-modifier",
12800 &Vw32_apps_modifier,
12801 "Modifier to use for the \"Apps\" key.\n\
12802 The value can be hyper, super, meta, alt, control or shift for the\n\
12803 respective modifier, or nil to appear as the key `apps'.\n\
12804 Any other value will cause the key to be ignored.");
12805 Vw32_apps_modifier = Qnil;
12807 DEFVAR_LISP ("w32-enable-synthesized_fonts", &Vw32_enable_synthesized_fonts,
12808 "Non-nil enables selection of artificially italicized and bold fonts.");
12809 Vw32_enable_synthesized_fonts = Qnil;
12811 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
12812 "Non-nil enables Windows palette management to map colors exactly.");
12813 Vw32_enable_palette = Qt;
12815 DEFVAR_INT ("w32-mouse-button-tolerance",
12816 &Vw32_mouse_button_tolerance,
12817 "Analogue of double click interval for faking middle mouse events.\n\
12818 The value is the minimum time in milliseconds that must elapse between\n\
12819 left/right button down events before they are considered distinct events.\n\
12820 If both mouse buttons are depressed within this interval, a middle mouse\n\
12821 button down event is generated instead.");
12822 XSETINT (Vw32_mouse_button_tolerance, GetDoubleClickTime () / 2);
12824 DEFVAR_INT ("w32-mouse-move-interval",
12825 &Vw32_mouse_move_interval,
12826 "Minimum interval between mouse move events.\n\
12827 The value is the minimum time in milliseconds that must elapse between\n\
12828 successive mouse move (or scroll bar drag) events before they are\n\
12829 reported as lisp events.");
12830 XSETINT (Vw32_mouse_move_interval, 0);
12832 init_x_parm_symbols ();
12834 DEFVAR_LISP ("x-bitmap-file-path", &Vx_bitmap_file_path,
12835 "List of directories to search for bitmap files for w32.");
12836 Vx_bitmap_file_path = decode_env_path ((char *) 0, "PATH");
12838 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
12839 "The shape of the pointer when over text.\n\
12840 Changing the value does not affect existing frames\n\
12841 unless you set the mouse color.");
12842 Vx_pointer_shape = Qnil;
12844 DEFVAR_LISP ("x-resource-name", &Vx_resource_name,
12845 "The name Emacs uses to look up resources; for internal use only.\n\
12846 `x-get-resource' uses this as the first component of the instance name\n\
12847 when requesting resource values.\n\
12848 Emacs initially sets `x-resource-name' to the name under which Emacs\n\
12849 was invoked, or to the value specified with the `-name' or `-rn'\n\
12850 switches, if present.");
12851 Vx_resource_name = Qnil;
12853 Vx_nontext_pointer_shape = Qnil;
12855 Vx_mode_pointer_shape = Qnil;
12857 DEFVAR_LISP ("x-busy-pointer-shape", &Vx_busy_pointer_shape,
12858 "The shape of the pointer when Emacs is busy.\n\
12859 This variable takes effect when you create a new frame\n\
12860 or when you set the mouse color.");
12861 Vx_busy_pointer_shape = Qnil;
12863 DEFVAR_BOOL ("display-busy-cursor", &display_busy_cursor_p,
12864 "Non-zero means Emacs displays a busy cursor on window systems.");
12865 display_busy_cursor_p = 1;
12867 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
12868 &Vx_sensitive_text_pointer_shape,
12869 "The shape of the pointer when over mouse-sensitive text.\n\
12870 This variable takes effect when you create a new frame\n\
12871 or when you set the mouse color.");
12872 Vx_sensitive_text_pointer_shape = Qnil;
12874 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
12875 "A string indicating the foreground color of the cursor box.");
12876 Vx_cursor_fore_pixel = Qnil;
12878 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
12879 "Non-nil if no window manager is in use.\n\
12880 Emacs doesn't try to figure this out; this is always nil\n\
12881 unless you set it to something else.");
12882 /* We don't have any way to find this out, so set it to nil
12883 and maybe the user would like to set it to t. */
12884 Vx_no_window_manager = Qnil;
12886 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
12887 &Vx_pixel_size_width_font_regexp,
12888 "Regexp matching a font name whose width is the same as `PIXEL_SIZE'.\n\
12890 Since Emacs gets width of a font matching with this regexp from\n\
12891 PIXEL_SIZE field of the name, font finding mechanism gets faster for\n\
12892 such a font. This is especially effective for such large fonts as\n\
12893 Chinese, Japanese, and Korean.");
12894 Vx_pixel_size_width_font_regexp = Qnil;
12896 DEFVAR_LISP ("image-cache-eviction-delay", &Vimage_cache_eviction_delay,
12897 "Time after which cached images are removed from the cache.\n\
12898 When an image has not been displayed this many seconds, remove it\n\
12899 from the image cache. Value must be an integer or nil with nil\n\
12900 meaning don't clear the cache.");
12901 Vimage_cache_eviction_delay = make_number (30 * 60);
12903 DEFVAR_LISP ("image-types", &Vimage_types,
12904 "List of supported image types.\n\
12905 Each element of the list is a symbol for a supported image type.");
12906 Vimage_types = Qnil;
12908 DEFVAR_LISP ("w32-bdf-filename-alist",
12909 &Vw32_bdf_filename_alist,
12910 "List of bdf fonts and their corresponding filenames.");
12911 Vw32_bdf_filename_alist = Qnil;
12913 DEFVAR_BOOL ("w32-strict-fontnames",
12914 &w32_strict_fontnames,
12915 "Non-nil means only use fonts that are exact matches for those requested.\n\
12916 Default is nil, which allows old fontnames that are not XLFD compliant,\n\
12917 and allows third-party CJK display to work by specifying false charset\n\
12918 fields to trick Emacs into translating to Big5, SJIS etc.\n\
12919 Setting this to t will prevent wrong fonts being selected when\n\
12920 fontsets are automatically created.");
12921 w32_strict_fontnames = 0;
12923 DEFVAR_BOOL ("w32-strict-painting",
12924 &w32_strict_painting,
12925 "Non-nil means use strict rules for repainting frames.\n\
12926 Set this to nil to get the old behaviour for repainting; this should\n\
12927 only be necessary if the default setting causes problems.");
12928 w32_strict_painting = 1;
12930 DEFVAR_LISP ("w32-system-coding-system",
12931 &Vw32_system_coding_system,
12932 "Coding system used by Windows system functions, such as for font names.");
12933 Vw32_system_coding_system = Qnil;
12935 defsubr (&Sx_get_resource);
12936 #if 0 /* NTEMACS_TODO: Port to W32 */
12937 defsubr (&Sx_change_window_property);
12938 defsubr (&Sx_delete_window_property);
12939 defsubr (&Sx_window_property);
12940 #endif
12941 defsubr (&Sxw_display_color_p);
12942 defsubr (&Sx_display_grayscale_p);
12943 defsubr (&Sxw_color_defined_p);
12944 defsubr (&Sxw_color_values);
12945 defsubr (&Sx_server_max_request_size);
12946 defsubr (&Sx_server_vendor);
12947 defsubr (&Sx_server_version);
12948 defsubr (&Sx_display_pixel_width);
12949 defsubr (&Sx_display_pixel_height);
12950 defsubr (&Sx_display_mm_width);
12951 defsubr (&Sx_display_mm_height);
12952 defsubr (&Sx_display_screens);
12953 defsubr (&Sx_display_planes);
12954 defsubr (&Sx_display_color_cells);
12955 defsubr (&Sx_display_visual_class);
12956 defsubr (&Sx_display_backing_store);
12957 defsubr (&Sx_display_save_under);
12958 defsubr (&Sx_parse_geometry);
12959 defsubr (&Sx_create_frame);
12960 defsubr (&Sx_open_connection);
12961 defsubr (&Sx_close_connection);
12962 defsubr (&Sx_display_list);
12963 defsubr (&Sx_synchronize);
12965 /* W32 specific functions */
12967 defsubr (&Sw32_focus_frame);
12968 defsubr (&Sw32_select_font);
12969 defsubr (&Sw32_define_rgb_color);
12970 defsubr (&Sw32_default_color_map);
12971 defsubr (&Sw32_load_color_file);
12972 defsubr (&Sw32_send_sys_command);
12973 defsubr (&Sw32_shell_execute);
12974 defsubr (&Sw32_register_hot_key);
12975 defsubr (&Sw32_unregister_hot_key);
12976 defsubr (&Sw32_registered_hot_keys);
12977 defsubr (&Sw32_reconstruct_hot_key);
12978 defsubr (&Sw32_toggle_lock_key);
12979 defsubr (&Sw32_find_bdf_fonts);
12981 /* Setting callback functions for fontset handler. */
12982 get_font_info_func = w32_get_font_info;
12984 #if 0 /* This function pointer doesn't seem to be used anywhere.
12985 And the pointer assigned has the wrong type, anyway. */
12986 list_fonts_func = w32_list_fonts;
12987 #endif
12989 load_font_func = w32_load_font;
12990 find_ccl_program_func = w32_find_ccl_program;
12991 query_font_func = w32_query_font;
12992 set_frame_fontset_func = x_set_font;
12993 check_window_system_func = check_w32;
12995 #if 0 /* NTEMACS_TODO Image support for W32 */
12996 /* Images. */
12997 Qxbm = intern ("xbm");
12998 staticpro (&Qxbm);
12999 QCtype = intern (":type");
13000 staticpro (&QCtype);
13001 QCalgorithm = intern (":algorithm");
13002 staticpro (&QCalgorithm);
13003 QCheuristic_mask = intern (":heuristic-mask");
13004 staticpro (&QCheuristic_mask);
13005 QCcolor_symbols = intern (":color-symbols");
13006 staticpro (&QCcolor_symbols);
13007 QCdata = intern (":data");
13008 staticpro (&QCdata);
13009 QCascent = intern (":ascent");
13010 staticpro (&QCascent);
13011 QCmargin = intern (":margin");
13012 staticpro (&QCmargin);
13013 QCrelief = intern (":relief");
13014 staticpro (&QCrelief);
13015 Qpostscript = intern ("postscript");
13016 staticpro (&Qpostscript);
13017 QCloader = intern (":loader");
13018 staticpro (&QCloader);
13019 QCbounding_box = intern (":bounding-box");
13020 staticpro (&QCbounding_box);
13021 QCpt_width = intern (":pt-width");
13022 staticpro (&QCpt_width);
13023 QCpt_height = intern (":pt-height");
13024 staticpro (&QCpt_height);
13025 QCindex = intern (":index");
13026 staticpro (&QCindex);
13027 Qpbm = intern ("pbm");
13028 staticpro (&Qpbm);
13030 #if HAVE_XPM
13031 Qxpm = intern ("xpm");
13032 staticpro (&Qxpm);
13033 #endif
13035 #if HAVE_JPEG
13036 Qjpeg = intern ("jpeg");
13037 staticpro (&Qjpeg);
13038 #endif
13040 #if HAVE_TIFF
13041 Qtiff = intern ("tiff");
13042 staticpro (&Qtiff);
13043 #endif
13045 #if HAVE_GIF
13046 Qgif = intern ("gif");
13047 staticpro (&Qgif);
13048 #endif
13050 #if HAVE_PNG
13051 Qpng = intern ("png");
13052 staticpro (&Qpng);
13053 #endif
13055 defsubr (&Sclear_image_cache);
13057 #if GLYPH_DEBUG
13058 defsubr (&Simagep);
13059 defsubr (&Slookup_image);
13060 #endif
13061 #endif /* NTEMACS_TODO */
13063 /* Busy-cursor. */
13064 defsubr (&Sx_show_busy_cursor);
13065 defsubr (&Sx_hide_busy_cursor);
13066 busy_count = 0;
13067 inhibit_busy_cursor = 0;
13069 defsubr (&Sx_show_tip);
13070 defsubr (&Sx_hide_tip);
13071 staticpro (&tip_timer);
13072 tip_timer = Qnil;
13074 defsubr (&Sx_file_dialog);
13078 void
13079 init_xfns ()
13081 image_types = NULL;
13082 Vimage_types = Qnil;
13084 #if 0 /* NTEMACS_TODO : Image support for W32 */
13085 define_image_type (&xbm_type);
13086 define_image_type (&gs_type);
13087 define_image_type (&pbm_type);
13089 #if HAVE_XPM
13090 define_image_type (&xpm_type);
13091 #endif
13093 #if HAVE_JPEG
13094 define_image_type (&jpeg_type);
13095 #endif
13097 #if HAVE_TIFF
13098 define_image_type (&tiff_type);
13099 #endif
13101 #if HAVE_GIF
13102 define_image_type (&gif_type);
13103 #endif
13105 #if HAVE_PNG
13106 define_image_type (&png_type);
13107 #endif
13108 #endif /* NTEMACS_TODO */
13111 #undef abort
13113 void
13114 w32_abort()
13116 int button;
13117 button = MessageBox (NULL,
13118 "A fatal error has occurred!\n\n"
13119 "Select Abort to exit, Retry to debug, Ignore to continue",
13120 "Emacs Abort Dialog",
13121 MB_ICONEXCLAMATION | MB_TASKMODAL
13122 | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE);
13123 switch (button)
13125 case IDRETRY:
13126 DebugBreak ();
13127 break;
13128 case IDIGNORE:
13129 break;
13130 case IDABORT:
13131 default:
13132 abort ();
13133 break;
13137 /* For convenience when debugging. */
13139 w32_last_error()
13141 return GetLastError ();