Don't require `cl'.
[emacs.git] / src / w32fns.c
blobbe3570231dcc2745d24094a081d19d9a42f75765
1 /* Graphical user interface functions for the Microsoft W32 API.
2 Copyright (C) 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3 2001, 2002, 2003, 2004, 2005, 2006, 2007 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 3, 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., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, 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 "dispextern.h"
34 #include "w32term.h"
35 #include "keyboard.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "buffer.h"
39 #include "fontset.h"
40 #include "intervals.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>
54 #include <winspool.h>
55 #include <objbase.h>
57 #include <dlgs.h>
58 #define FILE_NAME_TEXT_FIELD edt1
60 void syms_of_w32fns ();
61 void globals_of_w32fns ();
63 extern void free_frame_menubar ();
64 extern double atof ();
65 extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
66 extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
67 extern void w32_free_menu_strings P_ ((HWND));
68 extern XCharStruct *w32_per_char_metric P_ ((XFontStruct *, wchar_t *, int));
70 extern int quit_char;
72 extern char *lispy_function_keys[];
74 /* The gray bitmap `bitmaps/gray'. This is done because w32term.c uses
75 it, and including `bitmaps/gray' more than once is a problem when
76 config.h defines `static' as an empty replacement string. */
78 int gray_bitmap_width = gray_width;
79 int gray_bitmap_height = gray_height;
80 unsigned char *gray_bitmap_bits = gray_bits;
82 /* The colormap for converting color names to RGB values */
83 Lisp_Object Vw32_color_map;
85 /* Non nil if alt key presses are passed on to Windows. */
86 Lisp_Object Vw32_pass_alt_to_system;
88 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
89 to alt_modifier. */
90 Lisp_Object Vw32_alt_is_meta;
92 /* If non-zero, the windows virtual key code for an alternative quit key. */
93 int w32_quit_key;
95 /* Non nil if left window key events are passed on to Windows (this only
96 affects whether "tapping" the key opens the Start menu). */
97 Lisp_Object Vw32_pass_lwindow_to_system;
99 /* Non nil if right window key events are passed on to Windows (this
100 only affects whether "tapping" the key opens the Start menu). */
101 Lisp_Object Vw32_pass_rwindow_to_system;
103 /* Virtual key code used to generate "phantom" key presses in order
104 to stop system from acting on Windows key events. */
105 Lisp_Object Vw32_phantom_key_code;
107 /* Modifier associated with the left "Windows" key, or nil to act as a
108 normal key. */
109 Lisp_Object Vw32_lwindow_modifier;
111 /* Modifier associated with the right "Windows" key, or nil to act as a
112 normal key. */
113 Lisp_Object Vw32_rwindow_modifier;
115 /* Modifier associated with the "Apps" key, or nil to act as a normal
116 key. */
117 Lisp_Object Vw32_apps_modifier;
119 /* Value is nil if Num Lock acts as a function key. */
120 Lisp_Object Vw32_enable_num_lock;
122 /* Value is nil if Caps Lock acts as a function key. */
123 Lisp_Object Vw32_enable_caps_lock;
125 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
126 Lisp_Object Vw32_scroll_lock_modifier;
128 /* Switch to control whether we inhibit requests for synthesized bold
129 and italic versions of fonts. */
130 int w32_enable_synthesized_fonts;
132 /* Enable palette management. */
133 Lisp_Object Vw32_enable_palette;
135 /* Control how close left/right button down events must be to
136 be converted to a middle button down event. */
137 int w32_mouse_button_tolerance;
139 /* Minimum interval between mouse movement (and scroll bar drag)
140 events that are passed on to the event loop. */
141 int w32_mouse_move_interval;
143 /* Flag to indicate if XBUTTON events should be passed on to Windows. */
144 int w32_pass_extra_mouse_buttons_to_system;
146 /* Non nil if no window manager is in use. */
147 Lisp_Object Vx_no_window_manager;
149 /* Non-zero means we're allowed to display a hourglass pointer. */
151 int display_hourglass_p;
153 /* The background and shape of the mouse pointer, and shape when not
154 over text or in the modeline. */
156 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
157 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
159 /* The shape when over mouse-sensitive text. */
161 Lisp_Object Vx_sensitive_text_pointer_shape;
163 #ifndef IDC_HAND
164 #define IDC_HAND MAKEINTRESOURCE(32649)
165 #endif
167 /* Color of chars displayed in cursor box. */
169 Lisp_Object Vx_cursor_fore_pixel;
171 /* Nonzero if using Windows. */
173 static int w32_in_use;
175 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
177 Lisp_Object Vx_pixel_size_width_font_regexp;
179 /* Alist of bdf fonts and the files that define them. */
180 Lisp_Object Vw32_bdf_filename_alist;
182 /* A flag to control whether fonts are matched strictly or not. */
183 int w32_strict_fontnames;
185 /* A flag to control whether we should only repaint if GetUpdateRect
186 indicates there is an update region. */
187 int w32_strict_painting;
189 /* Associative list linking character set strings to Windows codepages. */
190 Lisp_Object Vw32_charset_info_alist;
192 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
193 #ifndef VIETNAMESE_CHARSET
194 #define VIETNAMESE_CHARSET 163
195 #endif
197 Lisp_Object Qnone;
198 Lisp_Object Qsuppress_icon;
199 Lisp_Object Qundefined_color;
200 Lisp_Object Qcancel_timer;
201 Lisp_Object Qhyper;
202 Lisp_Object Qsuper;
203 Lisp_Object Qmeta;
204 Lisp_Object Qalt;
205 Lisp_Object Qctrl;
206 Lisp_Object Qcontrol;
207 Lisp_Object Qshift;
209 Lisp_Object Qw32_charset_ansi;
210 Lisp_Object Qw32_charset_default;
211 Lisp_Object Qw32_charset_symbol;
212 Lisp_Object Qw32_charset_shiftjis;
213 Lisp_Object Qw32_charset_hangeul;
214 Lisp_Object Qw32_charset_gb2312;
215 Lisp_Object Qw32_charset_chinesebig5;
216 Lisp_Object Qw32_charset_oem;
218 #ifndef JOHAB_CHARSET
219 #define JOHAB_CHARSET 130
220 #endif
221 #ifdef JOHAB_CHARSET
222 Lisp_Object Qw32_charset_easteurope;
223 Lisp_Object Qw32_charset_turkish;
224 Lisp_Object Qw32_charset_baltic;
225 Lisp_Object Qw32_charset_russian;
226 Lisp_Object Qw32_charset_arabic;
227 Lisp_Object Qw32_charset_greek;
228 Lisp_Object Qw32_charset_hebrew;
229 Lisp_Object Qw32_charset_vietnamese;
230 Lisp_Object Qw32_charset_thai;
231 Lisp_Object Qw32_charset_johab;
232 Lisp_Object Qw32_charset_mac;
233 #endif
235 #ifdef UNICODE_CHARSET
236 Lisp_Object Qw32_charset_unicode;
237 #endif
239 /* The ANSI codepage. */
240 int w32_ansi_code_page;
242 /* Prefix for system colors. */
243 #define SYSTEM_COLOR_PREFIX "System"
244 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
246 /* State variables for emulating a three button mouse. */
247 #define LMOUSE 1
248 #define MMOUSE 2
249 #define RMOUSE 4
251 static int button_state = 0;
252 static W32Msg saved_mouse_button_msg;
253 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
254 static W32Msg saved_mouse_move_msg;
255 static unsigned mouse_move_timer = 0;
257 /* Window that is tracking the mouse. */
258 static HWND track_mouse_window;
260 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
261 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
263 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
264 ClipboardSequence_Proc clipboard_sequence_fn = NULL;
265 extern AppendMenuW_Proc unicode_append_menu;
267 /* W95 mousewheel handler */
268 unsigned int msh_mousewheel = 0;
270 /* Timers */
271 #define MOUSE_BUTTON_ID 1
272 #define MOUSE_MOVE_ID 2
273 #define MENU_FREE_ID 3
274 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
275 is received. */
276 #define MENU_FREE_DELAY 1000
277 static unsigned menu_free_timer = 0;
279 /* The below are defined in frame.c. */
281 extern Lisp_Object Vwindow_system_version;
283 #ifdef GLYPH_DEBUG
284 int image_cache_refcount, dpyinfo_refcount;
285 #endif
288 /* From w32term.c. */
289 extern int w32_num_mouse_buttons;
290 extern Lisp_Object Vw32_recognize_altgr;
292 extern HWND w32_system_caret_hwnd;
294 extern int w32_system_caret_height;
295 extern int w32_system_caret_x;
296 extern int w32_system_caret_y;
297 extern int w32_use_visible_system_caret;
299 static HWND w32_visible_system_caret_hwnd;
301 /* From w32menu.c */
302 extern HMENU current_popup_menu;
303 static int menubar_in_use = 0;
306 /* Error if we are not connected to MS-Windows. */
307 void
308 check_w32 ()
310 if (! w32_in_use)
311 error ("MS-Windows not in use or not initialized");
314 /* Nonzero if we can use mouse menus.
315 You should not call this unless HAVE_MENUS is defined. */
318 have_menus_p ()
320 return w32_in_use;
323 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
324 and checking validity for W32. */
326 FRAME_PTR
327 check_x_frame (frame)
328 Lisp_Object frame;
330 FRAME_PTR f;
332 if (NILP (frame))
333 frame = selected_frame;
334 CHECK_LIVE_FRAME (frame);
335 f = XFRAME (frame);
336 if (! FRAME_W32_P (f))
337 error ("Non-W32 frame used");
338 return f;
341 /* Let the user specify a display with a frame.
342 nil stands for the selected frame--or, if that is not a w32 frame,
343 the first display on the list. */
345 struct w32_display_info *
346 check_x_display_info (frame)
347 Lisp_Object frame;
349 if (NILP (frame))
351 struct frame *sf = XFRAME (selected_frame);
353 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
354 return FRAME_W32_DISPLAY_INFO (sf);
355 else
356 return &one_w32_display_info;
358 else if (STRINGP (frame))
359 return x_display_info_for_name (frame);
360 else
362 FRAME_PTR f;
364 CHECK_LIVE_FRAME (frame);
365 f = XFRAME (frame);
366 if (! FRAME_W32_P (f))
367 error ("Non-W32 frame used");
368 return FRAME_W32_DISPLAY_INFO (f);
372 /* Return the Emacs frame-object corresponding to an w32 window.
373 It could be the frame's main window or an icon window. */
375 /* This function can be called during GC, so use GC_xxx type test macros. */
377 struct frame *
378 x_window_to_frame (dpyinfo, wdesc)
379 struct w32_display_info *dpyinfo;
380 HWND wdesc;
382 Lisp_Object tail, frame;
383 struct frame *f;
385 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
387 frame = XCAR (tail);
388 if (!GC_FRAMEP (frame))
389 continue;
390 f = XFRAME (frame);
391 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
392 continue;
393 if (f->output_data.w32->hourglass_window == wdesc)
394 return f;
396 if (FRAME_W32_WINDOW (f) == wdesc)
397 return f;
399 return 0;
403 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
404 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
405 static void my_create_window P_ ((struct frame *));
406 static void my_create_tip_window P_ ((struct frame *));
408 /* TODO: Native Input Method support; see x_create_im. */
409 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
410 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
411 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
412 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
413 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
414 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
415 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
416 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
417 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
418 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
419 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
420 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
421 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
422 Lisp_Object));
427 /* Store the screen positions of frame F into XPTR and YPTR.
428 These are the positions of the containing window manager window,
429 not Emacs's own window. */
431 void
432 x_real_positions (f, xptr, yptr)
433 FRAME_PTR f;
434 int *xptr, *yptr;
436 POINT pt;
437 RECT rect;
439 /* Get the bounds of the WM window. */
440 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
442 pt.x = 0;
443 pt.y = 0;
445 /* Convert (0, 0) in the client area to screen co-ordinates. */
446 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
448 /* Remember x_pixels_diff and y_pixels_diff. */
449 f->x_pixels_diff = pt.x - rect.left;
450 f->y_pixels_diff = pt.y - rect.top;
452 *xptr = rect.left;
453 *yptr = rect.top;
458 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
459 Sw32_define_rgb_color, 4, 4, 0,
460 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
461 This adds or updates a named color to w32-color-map, making it
462 available for use. The original entry's RGB ref is returned, or nil
463 if the entry is new. */)
464 (red, green, blue, name)
465 Lisp_Object red, green, blue, name;
467 Lisp_Object rgb;
468 Lisp_Object oldrgb = Qnil;
469 Lisp_Object entry;
471 CHECK_NUMBER (red);
472 CHECK_NUMBER (green);
473 CHECK_NUMBER (blue);
474 CHECK_STRING (name);
476 XSETINT (rgb, RGB(XUINT (red), XUINT (green), XUINT (blue)));
478 BLOCK_INPUT;
480 /* replace existing entry in w32-color-map or add new entry. */
481 entry = Fassoc (name, Vw32_color_map);
482 if (NILP (entry))
484 entry = Fcons (name, rgb);
485 Vw32_color_map = Fcons (entry, Vw32_color_map);
487 else
489 oldrgb = Fcdr (entry);
490 Fsetcdr (entry, rgb);
493 UNBLOCK_INPUT;
495 return (oldrgb);
498 DEFUN ("w32-load-color-file", Fw32_load_color_file,
499 Sw32_load_color_file, 1, 1, 0,
500 doc: /* Create an alist of color entries from an external file.
501 Assign this value to w32-color-map to replace the existing color map.
503 The file should define one named RGB color per line like so:
504 R G B name
505 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
506 (filename)
507 Lisp_Object filename;
509 FILE *fp;
510 Lisp_Object cmap = Qnil;
511 Lisp_Object abspath;
513 CHECK_STRING (filename);
514 abspath = Fexpand_file_name (filename, Qnil);
516 fp = fopen (SDATA (filename), "rt");
517 if (fp)
519 char buf[512];
520 int red, green, blue;
521 int num;
523 BLOCK_INPUT;
525 while (fgets (buf, sizeof (buf), fp) != NULL) {
526 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
528 char *name = buf + num;
529 num = strlen (name) - 1;
530 if (name[num] == '\n')
531 name[num] = 0;
532 cmap = Fcons (Fcons (build_string (name),
533 make_number (RGB (red, green, blue))),
534 cmap);
537 fclose (fp);
539 UNBLOCK_INPUT;
542 return cmap;
545 /* The default colors for the w32 color map */
546 typedef struct colormap_t
548 char *name;
549 COLORREF colorref;
550 } colormap_t;
552 colormap_t w32_color_map[] =
554 {"snow" , PALETTERGB (255,250,250)},
555 {"ghost white" , PALETTERGB (248,248,255)},
556 {"GhostWhite" , PALETTERGB (248,248,255)},
557 {"white smoke" , PALETTERGB (245,245,245)},
558 {"WhiteSmoke" , PALETTERGB (245,245,245)},
559 {"gainsboro" , PALETTERGB (220,220,220)},
560 {"floral white" , PALETTERGB (255,250,240)},
561 {"FloralWhite" , PALETTERGB (255,250,240)},
562 {"old lace" , PALETTERGB (253,245,230)},
563 {"OldLace" , PALETTERGB (253,245,230)},
564 {"linen" , PALETTERGB (250,240,230)},
565 {"antique white" , PALETTERGB (250,235,215)},
566 {"AntiqueWhite" , PALETTERGB (250,235,215)},
567 {"papaya whip" , PALETTERGB (255,239,213)},
568 {"PapayaWhip" , PALETTERGB (255,239,213)},
569 {"blanched almond" , PALETTERGB (255,235,205)},
570 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
571 {"bisque" , PALETTERGB (255,228,196)},
572 {"peach puff" , PALETTERGB (255,218,185)},
573 {"PeachPuff" , PALETTERGB (255,218,185)},
574 {"navajo white" , PALETTERGB (255,222,173)},
575 {"NavajoWhite" , PALETTERGB (255,222,173)},
576 {"moccasin" , PALETTERGB (255,228,181)},
577 {"cornsilk" , PALETTERGB (255,248,220)},
578 {"ivory" , PALETTERGB (255,255,240)},
579 {"lemon chiffon" , PALETTERGB (255,250,205)},
580 {"LemonChiffon" , PALETTERGB (255,250,205)},
581 {"seashell" , PALETTERGB (255,245,238)},
582 {"honeydew" , PALETTERGB (240,255,240)},
583 {"mint cream" , PALETTERGB (245,255,250)},
584 {"MintCream" , PALETTERGB (245,255,250)},
585 {"azure" , PALETTERGB (240,255,255)},
586 {"alice blue" , PALETTERGB (240,248,255)},
587 {"AliceBlue" , PALETTERGB (240,248,255)},
588 {"lavender" , PALETTERGB (230,230,250)},
589 {"lavender blush" , PALETTERGB (255,240,245)},
590 {"LavenderBlush" , PALETTERGB (255,240,245)},
591 {"misty rose" , PALETTERGB (255,228,225)},
592 {"MistyRose" , PALETTERGB (255,228,225)},
593 {"white" , PALETTERGB (255,255,255)},
594 {"black" , PALETTERGB ( 0, 0, 0)},
595 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
596 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
597 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
598 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
599 {"dim gray" , PALETTERGB (105,105,105)},
600 {"DimGray" , PALETTERGB (105,105,105)},
601 {"dim grey" , PALETTERGB (105,105,105)},
602 {"DimGrey" , PALETTERGB (105,105,105)},
603 {"slate gray" , PALETTERGB (112,128,144)},
604 {"SlateGray" , PALETTERGB (112,128,144)},
605 {"slate grey" , PALETTERGB (112,128,144)},
606 {"SlateGrey" , PALETTERGB (112,128,144)},
607 {"light slate gray" , PALETTERGB (119,136,153)},
608 {"LightSlateGray" , PALETTERGB (119,136,153)},
609 {"light slate grey" , PALETTERGB (119,136,153)},
610 {"LightSlateGrey" , PALETTERGB (119,136,153)},
611 {"gray" , PALETTERGB (190,190,190)},
612 {"grey" , PALETTERGB (190,190,190)},
613 {"light grey" , PALETTERGB (211,211,211)},
614 {"LightGrey" , PALETTERGB (211,211,211)},
615 {"light gray" , PALETTERGB (211,211,211)},
616 {"LightGray" , PALETTERGB (211,211,211)},
617 {"midnight blue" , PALETTERGB ( 25, 25,112)},
618 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
619 {"navy" , PALETTERGB ( 0, 0,128)},
620 {"navy blue" , PALETTERGB ( 0, 0,128)},
621 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
622 {"cornflower blue" , PALETTERGB (100,149,237)},
623 {"CornflowerBlue" , PALETTERGB (100,149,237)},
624 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
625 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
626 {"slate blue" , PALETTERGB (106, 90,205)},
627 {"SlateBlue" , PALETTERGB (106, 90,205)},
628 {"medium slate blue" , PALETTERGB (123,104,238)},
629 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
630 {"light slate blue" , PALETTERGB (132,112,255)},
631 {"LightSlateBlue" , PALETTERGB (132,112,255)},
632 {"medium blue" , PALETTERGB ( 0, 0,205)},
633 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
634 {"royal blue" , PALETTERGB ( 65,105,225)},
635 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
636 {"blue" , PALETTERGB ( 0, 0,255)},
637 {"dodger blue" , PALETTERGB ( 30,144,255)},
638 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
639 {"deep sky blue" , PALETTERGB ( 0,191,255)},
640 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
641 {"sky blue" , PALETTERGB (135,206,235)},
642 {"SkyBlue" , PALETTERGB (135,206,235)},
643 {"light sky blue" , PALETTERGB (135,206,250)},
644 {"LightSkyBlue" , PALETTERGB (135,206,250)},
645 {"steel blue" , PALETTERGB ( 70,130,180)},
646 {"SteelBlue" , PALETTERGB ( 70,130,180)},
647 {"light steel blue" , PALETTERGB (176,196,222)},
648 {"LightSteelBlue" , PALETTERGB (176,196,222)},
649 {"light blue" , PALETTERGB (173,216,230)},
650 {"LightBlue" , PALETTERGB (173,216,230)},
651 {"powder blue" , PALETTERGB (176,224,230)},
652 {"PowderBlue" , PALETTERGB (176,224,230)},
653 {"pale turquoise" , PALETTERGB (175,238,238)},
654 {"PaleTurquoise" , PALETTERGB (175,238,238)},
655 {"dark turquoise" , PALETTERGB ( 0,206,209)},
656 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
657 {"medium turquoise" , PALETTERGB ( 72,209,204)},
658 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
659 {"turquoise" , PALETTERGB ( 64,224,208)},
660 {"cyan" , PALETTERGB ( 0,255,255)},
661 {"light cyan" , PALETTERGB (224,255,255)},
662 {"LightCyan" , PALETTERGB (224,255,255)},
663 {"cadet blue" , PALETTERGB ( 95,158,160)},
664 {"CadetBlue" , PALETTERGB ( 95,158,160)},
665 {"medium aquamarine" , PALETTERGB (102,205,170)},
666 {"MediumAquamarine" , PALETTERGB (102,205,170)},
667 {"aquamarine" , PALETTERGB (127,255,212)},
668 {"dark green" , PALETTERGB ( 0,100, 0)},
669 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
670 {"dark olive green" , PALETTERGB ( 85,107, 47)},
671 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
672 {"dark sea green" , PALETTERGB (143,188,143)},
673 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
674 {"sea green" , PALETTERGB ( 46,139, 87)},
675 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
676 {"medium sea green" , PALETTERGB ( 60,179,113)},
677 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
678 {"light sea green" , PALETTERGB ( 32,178,170)},
679 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
680 {"pale green" , PALETTERGB (152,251,152)},
681 {"PaleGreen" , PALETTERGB (152,251,152)},
682 {"spring green" , PALETTERGB ( 0,255,127)},
683 {"SpringGreen" , PALETTERGB ( 0,255,127)},
684 {"lawn green" , PALETTERGB (124,252, 0)},
685 {"LawnGreen" , PALETTERGB (124,252, 0)},
686 {"green" , PALETTERGB ( 0,255, 0)},
687 {"chartreuse" , PALETTERGB (127,255, 0)},
688 {"medium spring green" , PALETTERGB ( 0,250,154)},
689 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
690 {"green yellow" , PALETTERGB (173,255, 47)},
691 {"GreenYellow" , PALETTERGB (173,255, 47)},
692 {"lime green" , PALETTERGB ( 50,205, 50)},
693 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
694 {"yellow green" , PALETTERGB (154,205, 50)},
695 {"YellowGreen" , PALETTERGB (154,205, 50)},
696 {"forest green" , PALETTERGB ( 34,139, 34)},
697 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
698 {"olive drab" , PALETTERGB (107,142, 35)},
699 {"OliveDrab" , PALETTERGB (107,142, 35)},
700 {"dark khaki" , PALETTERGB (189,183,107)},
701 {"DarkKhaki" , PALETTERGB (189,183,107)},
702 {"khaki" , PALETTERGB (240,230,140)},
703 {"pale goldenrod" , PALETTERGB (238,232,170)},
704 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
705 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
706 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
707 {"light yellow" , PALETTERGB (255,255,224)},
708 {"LightYellow" , PALETTERGB (255,255,224)},
709 {"yellow" , PALETTERGB (255,255, 0)},
710 {"gold" , PALETTERGB (255,215, 0)},
711 {"light goldenrod" , PALETTERGB (238,221,130)},
712 {"LightGoldenrod" , PALETTERGB (238,221,130)},
713 {"goldenrod" , PALETTERGB (218,165, 32)},
714 {"dark goldenrod" , PALETTERGB (184,134, 11)},
715 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
716 {"rosy brown" , PALETTERGB (188,143,143)},
717 {"RosyBrown" , PALETTERGB (188,143,143)},
718 {"indian red" , PALETTERGB (205, 92, 92)},
719 {"IndianRed" , PALETTERGB (205, 92, 92)},
720 {"saddle brown" , PALETTERGB (139, 69, 19)},
721 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
722 {"sienna" , PALETTERGB (160, 82, 45)},
723 {"peru" , PALETTERGB (205,133, 63)},
724 {"burlywood" , PALETTERGB (222,184,135)},
725 {"beige" , PALETTERGB (245,245,220)},
726 {"wheat" , PALETTERGB (245,222,179)},
727 {"sandy brown" , PALETTERGB (244,164, 96)},
728 {"SandyBrown" , PALETTERGB (244,164, 96)},
729 {"tan" , PALETTERGB (210,180,140)},
730 {"chocolate" , PALETTERGB (210,105, 30)},
731 {"firebrick" , PALETTERGB (178,34, 34)},
732 {"brown" , PALETTERGB (165,42, 42)},
733 {"dark salmon" , PALETTERGB (233,150,122)},
734 {"DarkSalmon" , PALETTERGB (233,150,122)},
735 {"salmon" , PALETTERGB (250,128,114)},
736 {"light salmon" , PALETTERGB (255,160,122)},
737 {"LightSalmon" , PALETTERGB (255,160,122)},
738 {"orange" , PALETTERGB (255,165, 0)},
739 {"dark orange" , PALETTERGB (255,140, 0)},
740 {"DarkOrange" , PALETTERGB (255,140, 0)},
741 {"coral" , PALETTERGB (255,127, 80)},
742 {"light coral" , PALETTERGB (240,128,128)},
743 {"LightCoral" , PALETTERGB (240,128,128)},
744 {"tomato" , PALETTERGB (255, 99, 71)},
745 {"orange red" , PALETTERGB (255, 69, 0)},
746 {"OrangeRed" , PALETTERGB (255, 69, 0)},
747 {"red" , PALETTERGB (255, 0, 0)},
748 {"hot pink" , PALETTERGB (255,105,180)},
749 {"HotPink" , PALETTERGB (255,105,180)},
750 {"deep pink" , PALETTERGB (255, 20,147)},
751 {"DeepPink" , PALETTERGB (255, 20,147)},
752 {"pink" , PALETTERGB (255,192,203)},
753 {"light pink" , PALETTERGB (255,182,193)},
754 {"LightPink" , PALETTERGB (255,182,193)},
755 {"pale violet red" , PALETTERGB (219,112,147)},
756 {"PaleVioletRed" , PALETTERGB (219,112,147)},
757 {"maroon" , PALETTERGB (176, 48, 96)},
758 {"medium violet red" , PALETTERGB (199, 21,133)},
759 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
760 {"violet red" , PALETTERGB (208, 32,144)},
761 {"VioletRed" , PALETTERGB (208, 32,144)},
762 {"magenta" , PALETTERGB (255, 0,255)},
763 {"violet" , PALETTERGB (238,130,238)},
764 {"plum" , PALETTERGB (221,160,221)},
765 {"orchid" , PALETTERGB (218,112,214)},
766 {"medium orchid" , PALETTERGB (186, 85,211)},
767 {"MediumOrchid" , PALETTERGB (186, 85,211)},
768 {"dark orchid" , PALETTERGB (153, 50,204)},
769 {"DarkOrchid" , PALETTERGB (153, 50,204)},
770 {"dark violet" , PALETTERGB (148, 0,211)},
771 {"DarkViolet" , PALETTERGB (148, 0,211)},
772 {"blue violet" , PALETTERGB (138, 43,226)},
773 {"BlueViolet" , PALETTERGB (138, 43,226)},
774 {"purple" , PALETTERGB (160, 32,240)},
775 {"medium purple" , PALETTERGB (147,112,219)},
776 {"MediumPurple" , PALETTERGB (147,112,219)},
777 {"thistle" , PALETTERGB (216,191,216)},
778 {"gray0" , PALETTERGB ( 0, 0, 0)},
779 {"grey0" , PALETTERGB ( 0, 0, 0)},
780 {"dark grey" , PALETTERGB (169,169,169)},
781 {"DarkGrey" , PALETTERGB (169,169,169)},
782 {"dark gray" , PALETTERGB (169,169,169)},
783 {"DarkGray" , PALETTERGB (169,169,169)},
784 {"dark blue" , PALETTERGB ( 0, 0,139)},
785 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
786 {"dark cyan" , PALETTERGB ( 0,139,139)},
787 {"DarkCyan" , PALETTERGB ( 0,139,139)},
788 {"dark magenta" , PALETTERGB (139, 0,139)},
789 {"DarkMagenta" , PALETTERGB (139, 0,139)},
790 {"dark red" , PALETTERGB (139, 0, 0)},
791 {"DarkRed" , PALETTERGB (139, 0, 0)},
792 {"light green" , PALETTERGB (144,238,144)},
793 {"LightGreen" , PALETTERGB (144,238,144)},
796 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
797 0, 0, 0, doc: /* Return the default color map. */)
800 int i;
801 colormap_t *pc = w32_color_map;
802 Lisp_Object cmap;
804 BLOCK_INPUT;
806 cmap = Qnil;
808 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
809 pc++, i++)
810 cmap = Fcons (Fcons (build_string (pc->name),
811 make_number (pc->colorref)),
812 cmap);
814 UNBLOCK_INPUT;
816 return (cmap);
819 Lisp_Object
820 w32_to_x_color (rgb)
821 Lisp_Object rgb;
823 Lisp_Object color;
825 CHECK_NUMBER (rgb);
827 BLOCK_INPUT;
829 color = Frassq (rgb, Vw32_color_map);
831 UNBLOCK_INPUT;
833 if (!NILP (color))
834 return (Fcar (color));
835 else
836 return Qnil;
839 static Lisp_Object
840 w32_color_map_lookup (colorname)
841 char *colorname;
843 Lisp_Object tail, ret = Qnil;
845 BLOCK_INPUT;
847 for (tail = Vw32_color_map; !NILP (tail); tail = Fcdr (tail))
849 register Lisp_Object elt, tem;
851 elt = Fcar (tail);
852 if (!CONSP (elt)) continue;
854 tem = Fcar (elt);
856 if (lstrcmpi (SDATA (tem), colorname) == 0)
858 ret = Fcdr (elt);
859 break;
862 QUIT;
866 UNBLOCK_INPUT;
868 return ret;
872 static void
873 add_system_logical_colors_to_map (system_colors)
874 Lisp_Object *system_colors;
876 HKEY colors_key;
878 /* Other registry operations are done with input blocked. */
879 BLOCK_INPUT;
881 /* Look for "Control Panel/Colors" under User and Machine registry
882 settings. */
883 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
884 KEY_READ, &colors_key) == ERROR_SUCCESS
885 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
886 KEY_READ, &colors_key) == ERROR_SUCCESS)
888 /* List all keys. */
889 char color_buffer[64];
890 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
891 int index = 0;
892 DWORD name_size, color_size;
893 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
895 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
896 color_size = sizeof (color_buffer);
898 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
900 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
901 NULL, NULL, color_buffer, &color_size)
902 == ERROR_SUCCESS)
904 int r, g, b;
905 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
906 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
907 make_number (RGB (r, g, b))),
908 *system_colors);
910 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
911 color_size = sizeof (color_buffer);
912 index++;
914 RegCloseKey (colors_key);
917 UNBLOCK_INPUT;
921 static Lisp_Object
922 x_to_w32_color (colorname)
923 char * colorname;
925 register Lisp_Object ret = Qnil;
927 BLOCK_INPUT;
929 if (colorname[0] == '#')
931 /* Could be an old-style RGB Device specification. */
932 char *color;
933 int size;
934 color = colorname + 1;
936 size = strlen(color);
937 if (size == 3 || size == 6 || size == 9 || size == 12)
939 UINT colorval;
940 int i, pos;
941 pos = 0;
942 size /= 3;
943 colorval = 0;
945 for (i = 0; i < 3; i++)
947 char *end;
948 char t;
949 unsigned long value;
951 /* The check for 'x' in the following conditional takes into
952 account the fact that strtol allows a "0x" in front of
953 our numbers, and we don't. */
954 if (!isxdigit(color[0]) || color[1] == 'x')
955 break;
956 t = color[size];
957 color[size] = '\0';
958 value = strtoul(color, &end, 16);
959 color[size] = t;
960 if (errno == ERANGE || end - color != size)
961 break;
962 switch (size)
964 case 1:
965 value = value * 0x10;
966 break;
967 case 2:
968 break;
969 case 3:
970 value /= 0x10;
971 break;
972 case 4:
973 value /= 0x100;
974 break;
976 colorval |= (value << pos);
977 pos += 0x8;
978 if (i == 2)
980 UNBLOCK_INPUT;
981 XSETINT (ret, colorval);
982 return ret;
984 color = end;
988 else if (strnicmp(colorname, "rgb:", 4) == 0)
990 char *color;
991 UINT colorval;
992 int i, pos;
993 pos = 0;
995 colorval = 0;
996 color = colorname + 4;
997 for (i = 0; i < 3; i++)
999 char *end;
1000 unsigned long value;
1002 /* The check for 'x' in the following conditional takes into
1003 account the fact that strtol allows a "0x" in front of
1004 our numbers, and we don't. */
1005 if (!isxdigit(color[0]) || color[1] == 'x')
1006 break;
1007 value = strtoul(color, &end, 16);
1008 if (errno == ERANGE)
1009 break;
1010 switch (end - color)
1012 case 1:
1013 value = value * 0x10 + value;
1014 break;
1015 case 2:
1016 break;
1017 case 3:
1018 value /= 0x10;
1019 break;
1020 case 4:
1021 value /= 0x100;
1022 break;
1023 default:
1024 value = ULONG_MAX;
1026 if (value == ULONG_MAX)
1027 break;
1028 colorval |= (value << pos);
1029 pos += 0x8;
1030 if (i == 2)
1032 if (*end != '\0')
1033 break;
1034 UNBLOCK_INPUT;
1035 XSETINT (ret, colorval);
1036 return ret;
1038 if (*end != '/')
1039 break;
1040 color = end + 1;
1043 else if (strnicmp(colorname, "rgbi:", 5) == 0)
1045 /* This is an RGB Intensity specification. */
1046 char *color;
1047 UINT colorval;
1048 int i, pos;
1049 pos = 0;
1051 colorval = 0;
1052 color = colorname + 5;
1053 for (i = 0; i < 3; i++)
1055 char *end;
1056 double value;
1057 UINT val;
1059 value = strtod(color, &end);
1060 if (errno == ERANGE)
1061 break;
1062 if (value < 0.0 || value > 1.0)
1063 break;
1064 val = (UINT)(0x100 * value);
1065 /* We used 0x100 instead of 0xFF to give a continuous
1066 range between 0.0 and 1.0 inclusive. The next statement
1067 fixes the 1.0 case. */
1068 if (val == 0x100)
1069 val = 0xFF;
1070 colorval |= (val << pos);
1071 pos += 0x8;
1072 if (i == 2)
1074 if (*end != '\0')
1075 break;
1076 UNBLOCK_INPUT;
1077 XSETINT (ret, colorval);
1078 return ret;
1080 if (*end != '/')
1081 break;
1082 color = end + 1;
1085 /* I am not going to attempt to handle any of the CIE color schemes
1086 or TekHVC, since I don't know the algorithms for conversion to
1087 RGB. */
1089 /* If we fail to lookup the color name in w32_color_map, then check the
1090 colorname to see if it can be crudely approximated: If the X color
1091 ends in a number (e.g., "darkseagreen2"), strip the number and
1092 return the result of looking up the base color name. */
1093 ret = w32_color_map_lookup (colorname);
1094 if (NILP (ret))
1096 int len = strlen (colorname);
1098 if (isdigit (colorname[len - 1]))
1100 char *ptr, *approx = alloca (len + 1);
1102 strcpy (approx, colorname);
1103 ptr = &approx[len - 1];
1104 while (ptr > approx && isdigit (*ptr))
1105 *ptr-- = '\0';
1107 ret = w32_color_map_lookup (approx);
1111 UNBLOCK_INPUT;
1112 return ret;
1115 void
1116 w32_regenerate_palette (FRAME_PTR f)
1118 struct w32_palette_entry * list;
1119 LOGPALETTE * log_palette;
1120 HPALETTE new_palette;
1121 int i;
1123 /* don't bother trying to create palette if not supported */
1124 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1125 return;
1127 log_palette = (LOGPALETTE *)
1128 alloca (sizeof (LOGPALETTE) +
1129 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1130 log_palette->palVersion = 0x300;
1131 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1133 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1134 for (i = 0;
1135 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1136 i++, list = list->next)
1137 log_palette->palPalEntry[i] = list->entry;
1139 new_palette = CreatePalette (log_palette);
1141 enter_crit ();
1143 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1144 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1145 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1147 /* Realize display palette and garbage all frames. */
1148 release_frame_dc (f, get_frame_dc (f));
1150 leave_crit ();
1153 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1154 #define SET_W32_COLOR(pe, color) \
1155 do \
1157 pe.peRed = GetRValue (color); \
1158 pe.peGreen = GetGValue (color); \
1159 pe.peBlue = GetBValue (color); \
1160 pe.peFlags = 0; \
1161 } while (0)
1163 #if 0
1164 /* Keep these around in case we ever want to track color usage. */
1165 void
1166 w32_map_color (FRAME_PTR f, COLORREF color)
1168 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1170 if (NILP (Vw32_enable_palette))
1171 return;
1173 /* check if color is already mapped */
1174 while (list)
1176 if (W32_COLOR (list->entry) == color)
1178 ++list->refcount;
1179 return;
1181 list = list->next;
1184 /* not already mapped, so add to list and recreate Windows palette */
1185 list = (struct w32_palette_entry *)
1186 xmalloc (sizeof (struct w32_palette_entry));
1187 SET_W32_COLOR (list->entry, color);
1188 list->refcount = 1;
1189 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1190 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1191 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1193 /* set flag that palette must be regenerated */
1194 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1197 void
1198 w32_unmap_color (FRAME_PTR f, COLORREF color)
1200 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1201 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1203 if (NILP (Vw32_enable_palette))
1204 return;
1206 /* check if color is already mapped */
1207 while (list)
1209 if (W32_COLOR (list->entry) == color)
1211 if (--list->refcount == 0)
1213 *prev = list->next;
1214 xfree (list);
1215 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1216 break;
1218 else
1219 return;
1221 prev = &list->next;
1222 list = list->next;
1225 /* set flag that palette must be regenerated */
1226 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1228 #endif
1231 /* Gamma-correct COLOR on frame F. */
1233 void
1234 gamma_correct (f, color)
1235 struct frame *f;
1236 COLORREF *color;
1238 if (f->gamma)
1240 *color = PALETTERGB (
1241 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1242 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1243 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1248 /* Decide if color named COLOR is valid for the display associated with
1249 the selected frame; if so, return the rgb values in COLOR_DEF.
1250 If ALLOC is nonzero, allocate a new colormap cell. */
1253 w32_defined_color (f, color, color_def, alloc)
1254 FRAME_PTR f;
1255 char *color;
1256 XColor *color_def;
1257 int alloc;
1259 register Lisp_Object tem;
1260 COLORREF w32_color_ref;
1262 tem = x_to_w32_color (color);
1264 if (!NILP (tem))
1266 if (f)
1268 /* Apply gamma correction. */
1269 w32_color_ref = XUINT (tem);
1270 gamma_correct (f, &w32_color_ref);
1271 XSETINT (tem, w32_color_ref);
1274 /* Map this color to the palette if it is enabled. */
1275 if (!NILP (Vw32_enable_palette))
1277 struct w32_palette_entry * entry =
1278 one_w32_display_info.color_list;
1279 struct w32_palette_entry ** prev =
1280 &one_w32_display_info.color_list;
1282 /* check if color is already mapped */
1283 while (entry)
1285 if (W32_COLOR (entry->entry) == XUINT (tem))
1286 break;
1287 prev = &entry->next;
1288 entry = entry->next;
1291 if (entry == NULL && alloc)
1293 /* not already mapped, so add to list */
1294 entry = (struct w32_palette_entry *)
1295 xmalloc (sizeof (struct w32_palette_entry));
1296 SET_W32_COLOR (entry->entry, XUINT (tem));
1297 entry->next = NULL;
1298 *prev = entry;
1299 one_w32_display_info.num_colors++;
1301 /* set flag that palette must be regenerated */
1302 one_w32_display_info.regen_palette = TRUE;
1305 /* Ensure COLORREF value is snapped to nearest color in (default)
1306 palette by simulating the PALETTERGB macro. This works whether
1307 or not the display device has a palette. */
1308 w32_color_ref = XUINT (tem) | 0x2000000;
1310 color_def->pixel = w32_color_ref;
1311 color_def->red = GetRValue (w32_color_ref) * 256;
1312 color_def->green = GetGValue (w32_color_ref) * 256;
1313 color_def->blue = GetBValue (w32_color_ref) * 256;
1315 return 1;
1317 else
1319 return 0;
1323 /* Given a string ARG naming a color, compute a pixel value from it
1324 suitable for screen F.
1325 If F is not a color screen, return DEF (default) regardless of what
1326 ARG says. */
1329 x_decode_color (f, arg, def)
1330 FRAME_PTR f;
1331 Lisp_Object arg;
1332 int def;
1334 XColor cdef;
1336 CHECK_STRING (arg);
1338 if (strcmp (SDATA (arg), "black") == 0)
1339 return BLACK_PIX_DEFAULT (f);
1340 else if (strcmp (SDATA (arg), "white") == 0)
1341 return WHITE_PIX_DEFAULT (f);
1343 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1344 return def;
1346 /* w32_defined_color is responsible for coping with failures
1347 by looking for a near-miss. */
1348 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1349 return cdef.pixel;
1351 /* defined_color failed; return an ultimate default. */
1352 return def;
1357 /* Functions called only from `x_set_frame_param'
1358 to set individual parameters.
1360 If FRAME_W32_WINDOW (f) is 0,
1361 the frame is being created and its window does not exist yet.
1362 In that case, just record the parameter's new value
1363 in the standard place; do not attempt to change the window. */
1365 void
1366 x_set_foreground_color (f, arg, oldval)
1367 struct frame *f;
1368 Lisp_Object arg, oldval;
1370 struct w32_output *x = f->output_data.w32;
1371 PIX_TYPE fg, old_fg;
1373 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1374 old_fg = FRAME_FOREGROUND_PIXEL (f);
1375 FRAME_FOREGROUND_PIXEL (f) = fg;
1377 if (FRAME_W32_WINDOW (f) != 0)
1379 if (x->cursor_pixel == old_fg)
1380 x->cursor_pixel = fg;
1382 update_face_from_frame_parameter (f, Qforeground_color, arg);
1383 if (FRAME_VISIBLE_P (f))
1384 redraw_frame (f);
1388 void
1389 x_set_background_color (f, arg, oldval)
1390 struct frame *f;
1391 Lisp_Object arg, oldval;
1393 FRAME_BACKGROUND_PIXEL (f)
1394 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1396 if (FRAME_W32_WINDOW (f) != 0)
1398 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1399 FRAME_BACKGROUND_PIXEL (f));
1401 update_face_from_frame_parameter (f, Qbackground_color, arg);
1403 if (FRAME_VISIBLE_P (f))
1404 redraw_frame (f);
1408 void
1409 x_set_mouse_color (f, arg, oldval)
1410 struct frame *f;
1411 Lisp_Object arg, oldval;
1413 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1414 int count;
1415 int mask_color;
1417 if (!EQ (Qnil, arg))
1418 f->output_data.w32->mouse_pixel
1419 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1420 mask_color = FRAME_BACKGROUND_PIXEL (f);
1422 /* Don't let pointers be invisible. */
1423 if (mask_color == f->output_data.w32->mouse_pixel
1424 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1425 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1427 #if 0 /* TODO : cursor changes */
1428 BLOCK_INPUT;
1430 /* It's not okay to crash if the user selects a screwy cursor. */
1431 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1433 if (!EQ (Qnil, Vx_pointer_shape))
1435 CHECK_NUMBER (Vx_pointer_shape);
1436 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1438 else
1439 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1440 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1442 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1444 CHECK_NUMBER (Vx_nontext_pointer_shape);
1445 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1446 XINT (Vx_nontext_pointer_shape));
1448 else
1449 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1450 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1452 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1454 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1455 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1456 XINT (Vx_hourglass_pointer_shape));
1458 else
1459 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1460 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1462 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1463 if (!EQ (Qnil, Vx_mode_pointer_shape))
1465 CHECK_NUMBER (Vx_mode_pointer_shape);
1466 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1467 XINT (Vx_mode_pointer_shape));
1469 else
1470 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1471 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1473 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1475 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1476 hand_cursor
1477 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1478 XINT (Vx_sensitive_text_pointer_shape));
1480 else
1481 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1483 if (!NILP (Vx_window_horizontal_drag_shape))
1485 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1486 horizontal_drag_cursor
1487 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1488 XINT (Vx_window_horizontal_drag_shape));
1490 else
1491 horizontal_drag_cursor
1492 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1494 /* Check and report errors with the above calls. */
1495 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1496 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1499 XColor fore_color, back_color;
1501 fore_color.pixel = f->output_data.w32->mouse_pixel;
1502 back_color.pixel = mask_color;
1503 XQueryColor (FRAME_W32_DISPLAY (f),
1504 DefaultColormap (FRAME_W32_DISPLAY (f),
1505 DefaultScreen (FRAME_W32_DISPLAY (f))),
1506 &fore_color);
1507 XQueryColor (FRAME_W32_DISPLAY (f),
1508 DefaultColormap (FRAME_W32_DISPLAY (f),
1509 DefaultScreen (FRAME_W32_DISPLAY (f))),
1510 &back_color);
1511 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1512 &fore_color, &back_color);
1513 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1514 &fore_color, &back_color);
1515 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1516 &fore_color, &back_color);
1517 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1518 &fore_color, &back_color);
1519 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1520 &fore_color, &back_color);
1523 if (FRAME_W32_WINDOW (f) != 0)
1524 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1526 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1527 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1528 f->output_data.w32->text_cursor = cursor;
1530 if (nontext_cursor != f->output_data.w32->nontext_cursor
1531 && f->output_data.w32->nontext_cursor != 0)
1532 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1533 f->output_data.w32->nontext_cursor = nontext_cursor;
1535 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1536 && f->output_data.w32->hourglass_cursor != 0)
1537 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1538 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1540 if (mode_cursor != f->output_data.w32->modeline_cursor
1541 && f->output_data.w32->modeline_cursor != 0)
1542 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1543 f->output_data.w32->modeline_cursor = mode_cursor;
1545 if (hand_cursor != f->output_data.w32->hand_cursor
1546 && f->output_data.w32->hand_cursor != 0)
1547 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1548 f->output_data.w32->hand_cursor = hand_cursor;
1550 XFlush (FRAME_W32_DISPLAY (f));
1551 UNBLOCK_INPUT;
1553 update_face_from_frame_parameter (f, Qmouse_color, arg);
1554 #endif /* TODO */
1557 /* Defined in w32term.c. */
1558 void
1559 x_set_cursor_color (f, arg, oldval)
1560 struct frame *f;
1561 Lisp_Object arg, oldval;
1563 unsigned long fore_pixel, pixel;
1565 if (!NILP (Vx_cursor_fore_pixel))
1566 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1567 WHITE_PIX_DEFAULT (f));
1568 else
1569 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1571 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1573 /* Make sure that the cursor color differs from the background color. */
1574 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1576 pixel = f->output_data.w32->mouse_pixel;
1577 if (pixel == fore_pixel)
1578 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1581 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1582 f->output_data.w32->cursor_pixel = pixel;
1584 if (FRAME_W32_WINDOW (f) != 0)
1586 BLOCK_INPUT;
1587 /* Update frame's cursor_gc. */
1588 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1589 f->output_data.w32->cursor_gc->background = pixel;
1591 UNBLOCK_INPUT;
1593 if (FRAME_VISIBLE_P (f))
1595 x_update_cursor (f, 0);
1596 x_update_cursor (f, 1);
1600 update_face_from_frame_parameter (f, Qcursor_color, arg);
1603 /* Set the border-color of frame F to pixel value PIX.
1604 Note that this does not fully take effect if done before
1605 F has a window. */
1607 void
1608 x_set_border_pixel (f, pix)
1609 struct frame *f;
1610 int pix;
1613 f->output_data.w32->border_pixel = pix;
1615 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1617 if (FRAME_VISIBLE_P (f))
1618 redraw_frame (f);
1622 /* Set the border-color of frame F to value described by ARG.
1623 ARG can be a string naming a color.
1624 The border-color is used for the border that is drawn by the server.
1625 Note that this does not fully take effect if done before
1626 F has a window; it must be redone when the window is created. */
1628 void
1629 x_set_border_color (f, arg, oldval)
1630 struct frame *f;
1631 Lisp_Object arg, oldval;
1633 int pix;
1635 CHECK_STRING (arg);
1636 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1637 x_set_border_pixel (f, pix);
1638 update_face_from_frame_parameter (f, Qborder_color, arg);
1642 void
1643 x_set_cursor_type (f, arg, oldval)
1644 FRAME_PTR f;
1645 Lisp_Object arg, oldval;
1647 set_frame_cursor_types (f, arg);
1649 /* Make sure the cursor gets redrawn. */
1650 cursor_type_changed = 1;
1653 void
1654 x_set_icon_type (f, arg, oldval)
1655 struct frame *f;
1656 Lisp_Object arg, oldval;
1658 int result;
1660 if (NILP (arg) && NILP (oldval))
1661 return;
1663 if (STRINGP (arg) && STRINGP (oldval)
1664 && EQ (Fstring_equal (oldval, arg), Qt))
1665 return;
1667 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1668 return;
1670 BLOCK_INPUT;
1672 result = x_bitmap_icon (f, arg);
1673 if (result)
1675 UNBLOCK_INPUT;
1676 error ("No icon window available");
1679 UNBLOCK_INPUT;
1682 void
1683 x_set_icon_name (f, arg, oldval)
1684 struct frame *f;
1685 Lisp_Object arg, oldval;
1687 if (STRINGP (arg))
1689 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1690 return;
1692 else if (!NILP (arg) || NILP (oldval))
1693 return;
1695 f->icon_name = arg;
1697 #if 0
1698 if (f->output_data.w32->icon_bitmap != 0)
1699 return;
1701 BLOCK_INPUT;
1703 result = x_text_icon (f,
1704 (char *) SDATA ((!NILP (f->icon_name)
1705 ? f->icon_name
1706 : !NILP (f->title)
1707 ? f->title
1708 : f->name)));
1710 if (result)
1712 UNBLOCK_INPUT;
1713 error ("No icon window available");
1716 /* If the window was unmapped (and its icon was mapped),
1717 the new icon is not mapped, so map the window in its stead. */
1718 if (FRAME_VISIBLE_P (f))
1720 #ifdef USE_X_TOOLKIT
1721 XtPopup (f->output_data.w32->widget, XtGrabNone);
1722 #endif
1723 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1726 XFlush (FRAME_W32_DISPLAY (f));
1727 UNBLOCK_INPUT;
1728 #endif
1732 void
1733 x_set_menu_bar_lines (f, value, oldval)
1734 struct frame *f;
1735 Lisp_Object value, oldval;
1737 int nlines;
1738 int olines = FRAME_MENU_BAR_LINES (f);
1740 /* Right now, menu bars don't work properly in minibuf-only frames;
1741 most of the commands try to apply themselves to the minibuffer
1742 frame itself, and get an error because you can't switch buffers
1743 in or split the minibuffer window. */
1744 if (FRAME_MINIBUF_ONLY_P (f))
1745 return;
1747 if (INTEGERP (value))
1748 nlines = XINT (value);
1749 else
1750 nlines = 0;
1752 FRAME_MENU_BAR_LINES (f) = 0;
1753 if (nlines)
1754 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1755 else
1757 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1758 free_frame_menubar (f);
1759 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1761 /* Adjust the frame size so that the client (text) dimensions
1762 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1763 set correctly. */
1764 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
1765 do_pending_window_change (0);
1767 adjust_glyphs (f);
1771 /* Set the number of lines used for the tool bar of frame F to VALUE.
1772 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
1773 is the old number of tool bar lines. This function changes the
1774 height of all windows on frame F to match the new tool bar height.
1775 The frame's height doesn't change. */
1777 void
1778 x_set_tool_bar_lines (f, value, oldval)
1779 struct frame *f;
1780 Lisp_Object value, oldval;
1782 int delta, nlines, root_height;
1783 Lisp_Object root_window;
1785 /* Treat tool bars like menu bars. */
1786 if (FRAME_MINIBUF_ONLY_P (f))
1787 return;
1789 /* Use VALUE only if an integer >= 0. */
1790 if (INTEGERP (value) && XINT (value) >= 0)
1791 nlines = XFASTINT (value);
1792 else
1793 nlines = 0;
1795 /* Make sure we redisplay all windows in this frame. */
1796 ++windows_or_buffers_changed;
1798 delta = nlines - FRAME_TOOL_BAR_LINES (f);
1800 /* Don't resize the tool-bar to more than we have room for. */
1801 root_window = FRAME_ROOT_WINDOW (f);
1802 root_height = WINDOW_TOTAL_LINES (XWINDOW (root_window));
1803 if (root_height - delta < 1)
1805 delta = root_height - 1;
1806 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
1809 FRAME_TOOL_BAR_LINES (f) = nlines;
1810 change_window_heights (root_window, delta);
1811 adjust_glyphs (f);
1813 /* We also have to make sure that the internal border at the top of
1814 the frame, below the menu bar or tool bar, is redrawn when the
1815 tool bar disappears. This is so because the internal border is
1816 below the tool bar if one is displayed, but is below the menu bar
1817 if there isn't a tool bar. The tool bar draws into the area
1818 below the menu bar. */
1819 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
1821 updating_frame = f;
1822 clear_frame ();
1823 clear_current_matrices (f);
1824 updating_frame = NULL;
1827 /* If the tool bar gets smaller, the internal border below it
1828 has to be cleared. It was formerly part of the display
1829 of the larger tool bar, and updating windows won't clear it. */
1830 if (delta < 0)
1832 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1833 int width = FRAME_PIXEL_WIDTH (f);
1834 int y = nlines * FRAME_LINE_HEIGHT (f);
1836 BLOCK_INPUT;
1838 HDC hdc = get_frame_dc (f);
1839 w32_clear_area (f, hdc, 0, y, width, height);
1840 release_frame_dc (f, hdc);
1842 UNBLOCK_INPUT;
1844 if (WINDOWP (f->tool_bar_window))
1845 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1850 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1851 w32_id_name.
1853 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1854 name; if NAME is a string, set F's name to NAME and set
1855 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1857 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1858 suggesting a new name, which lisp code should override; if
1859 F->explicit_name is set, ignore the new name; otherwise, set it. */
1861 void
1862 x_set_name (f, name, explicit)
1863 struct frame *f;
1864 Lisp_Object name;
1865 int explicit;
1867 /* Make sure that requests from lisp code override requests from
1868 Emacs redisplay code. */
1869 if (explicit)
1871 /* If we're switching from explicit to implicit, we had better
1872 update the mode lines and thereby update the title. */
1873 if (f->explicit_name && NILP (name))
1874 update_mode_lines = 1;
1876 f->explicit_name = ! NILP (name);
1878 else if (f->explicit_name)
1879 return;
1881 /* If NAME is nil, set the name to the w32_id_name. */
1882 if (NILP (name))
1884 /* Check for no change needed in this very common case
1885 before we do any consing. */
1886 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
1887 SDATA (f->name)))
1888 return;
1889 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
1891 else
1892 CHECK_STRING (name);
1894 /* Don't change the name if it's already NAME. */
1895 if (! NILP (Fstring_equal (name, f->name)))
1896 return;
1898 f->name = name;
1900 /* For setting the frame title, the title parameter should override
1901 the name parameter. */
1902 if (! NILP (f->title))
1903 name = f->title;
1905 if (FRAME_W32_WINDOW (f))
1907 if (STRING_MULTIBYTE (name))
1908 name = ENCODE_SYSTEM (name);
1910 BLOCK_INPUT;
1911 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
1912 UNBLOCK_INPUT;
1916 /* This function should be called when the user's lisp code has
1917 specified a name for the frame; the name will override any set by the
1918 redisplay code. */
1919 void
1920 x_explicitly_set_name (f, arg, oldval)
1921 FRAME_PTR f;
1922 Lisp_Object arg, oldval;
1924 x_set_name (f, arg, 1);
1927 /* This function should be called by Emacs redisplay code to set the
1928 name; names set this way will never override names set by the user's
1929 lisp code. */
1930 void
1931 x_implicitly_set_name (f, arg, oldval)
1932 FRAME_PTR f;
1933 Lisp_Object arg, oldval;
1935 x_set_name (f, arg, 0);
1938 /* Change the title of frame F to NAME.
1939 If NAME is nil, use the frame name as the title.
1941 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1942 name; if NAME is a string, set F's name to NAME and set
1943 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1945 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1946 suggesting a new name, which lisp code should override; if
1947 F->explicit_name is set, ignore the new name; otherwise, set it. */
1949 void
1950 x_set_title (f, name, old_name)
1951 struct frame *f;
1952 Lisp_Object name, old_name;
1954 /* Don't change the title if it's already NAME. */
1955 if (EQ (name, f->title))
1956 return;
1958 update_mode_lines = 1;
1960 f->title = name;
1962 if (NILP (name))
1963 name = f->name;
1965 if (FRAME_W32_WINDOW (f))
1967 if (STRING_MULTIBYTE (name))
1968 name = ENCODE_SYSTEM (name);
1970 BLOCK_INPUT;
1971 SetWindowText(FRAME_W32_WINDOW (f), SDATA (name));
1972 UNBLOCK_INPUT;
1977 void x_set_scroll_bar_default_width (f)
1978 struct frame *f;
1980 int wid = FRAME_COLUMN_WIDTH (f);
1982 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1983 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
1984 wid - 1) / wid;
1988 /* Subroutines of creating a frame. */
1991 /* Return the value of parameter PARAM.
1993 First search ALIST, then Vdefault_frame_alist, then the X defaults
1994 database, using ATTRIBUTE as the attribute name and CLASS as its class.
1996 Convert the resource to the type specified by desired_type.
1998 If no default is specified, return Qunbound. If you call
1999 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
2000 and don't let it get stored in any Lisp-visible variables! */
2002 static Lisp_Object
2003 w32_get_arg (alist, param, attribute, class, type)
2004 Lisp_Object alist, param;
2005 char *attribute;
2006 char *class;
2007 enum resource_types type;
2009 return x_get_arg (check_x_display_info (Qnil),
2010 alist, param, attribute, class, type);
2014 Cursor
2015 w32_load_cursor (LPCTSTR name)
2017 /* Try first to load cursor from application resource. */
2018 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle(NULL),
2019 name, IMAGE_CURSOR, 0, 0,
2020 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2021 if (!cursor)
2023 /* Then try to load a shared predefined cursor. */
2024 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
2025 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2027 return cursor;
2030 extern LRESULT CALLBACK w32_wnd_proc ();
2032 BOOL
2033 w32_init_class (hinst)
2034 HINSTANCE hinst;
2036 WNDCLASS wc;
2038 wc.style = CS_HREDRAW | CS_VREDRAW;
2039 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
2040 wc.cbClsExtra = 0;
2041 wc.cbWndExtra = WND_EXTRA_BYTES;
2042 wc.hInstance = hinst;
2043 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
2044 wc.hCursor = w32_load_cursor (IDC_ARROW);
2045 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
2046 wc.lpszMenuName = NULL;
2047 wc.lpszClassName = EMACS_CLASS;
2049 return (RegisterClass (&wc));
2052 HWND
2053 w32_createscrollbar (f, bar)
2054 struct frame *f;
2055 struct scroll_bar * bar;
2057 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2058 /* Position and size of scroll bar. */
2059 XINT(bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
2060 XINT(bar->top),
2061 XINT(bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
2062 XINT(bar->height),
2063 FRAME_W32_WINDOW (f),
2064 NULL,
2065 hinst,
2066 NULL));
2069 void
2070 w32_createwindow (f)
2071 struct frame *f;
2073 HWND hwnd;
2074 RECT rect;
2075 Lisp_Object top = Qunbound;
2076 Lisp_Object left = Qunbound;
2078 rect.left = rect.top = 0;
2079 rect.right = FRAME_PIXEL_WIDTH (f);
2080 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2082 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2083 FRAME_EXTERNAL_MENU_BAR (f));
2085 /* Do first time app init */
2087 if (!hprevinst)
2089 w32_init_class (hinst);
2092 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2094 XSETINT (left, f->left_pos);
2095 XSETINT (top, f->top_pos);
2097 else if (EQ (left, Qunbound) && EQ (top, Qunbound))
2099 /* When called with RES_TYPE_NUMBER, w32_get_arg will return zero
2100 for anything that is not a number and is not Qunbound. */
2101 left = w32_get_arg (Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
2102 top = w32_get_arg (Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
2105 FRAME_W32_WINDOW (f) = hwnd
2106 = CreateWindow (EMACS_CLASS,
2107 f->namebuf,
2108 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2109 EQ (left, Qunbound) ? CW_USEDEFAULT : XINT (left),
2110 EQ (top, Qunbound) ? CW_USEDEFAULT : XINT (top),
2111 rect.right - rect.left,
2112 rect.bottom - rect.top,
2113 NULL,
2114 NULL,
2115 hinst,
2116 NULL);
2118 if (hwnd)
2120 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2121 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2122 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2123 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->scroll_bar_actual_width);
2124 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2126 /* Enable drag-n-drop. */
2127 DragAcceptFiles (hwnd, TRUE);
2129 /* Do this to discard the default setting specified by our parent. */
2130 ShowWindow (hwnd, SW_HIDE);
2132 /* Update frame positions. */
2133 GetWindowRect (hwnd, &rect);
2134 f->left_pos = rect.left;
2135 f->top_pos = rect.top;
2139 void
2140 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
2141 W32Msg * wmsg;
2142 HWND hwnd;
2143 UINT msg;
2144 WPARAM wParam;
2145 LPARAM lParam;
2147 wmsg->msg.hwnd = hwnd;
2148 wmsg->msg.message = msg;
2149 wmsg->msg.wParam = wParam;
2150 wmsg->msg.lParam = lParam;
2151 wmsg->msg.time = GetMessageTime ();
2153 post_msg (wmsg);
2156 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2157 between left and right keys as advertised. We test for this
2158 support dynamically, and set a flag when the support is absent. If
2159 absent, we keep track of the left and right control and alt keys
2160 ourselves. This is particularly necessary on keyboards that rely
2161 upon the AltGr key, which is represented as having the left control
2162 and right alt keys pressed. For these keyboards, we need to know
2163 when the left alt key has been pressed in addition to the AltGr key
2164 so that we can properly support M-AltGr-key sequences (such as M-@
2165 on Swedish keyboards). */
2167 #define EMACS_LCONTROL 0
2168 #define EMACS_RCONTROL 1
2169 #define EMACS_LMENU 2
2170 #define EMACS_RMENU 3
2172 static int modifiers[4];
2173 static int modifiers_recorded;
2174 static int modifier_key_support_tested;
2176 static void
2177 test_modifier_support (unsigned int wparam)
2179 unsigned int l, r;
2181 if (wparam != VK_CONTROL && wparam != VK_MENU)
2182 return;
2183 if (wparam == VK_CONTROL)
2185 l = VK_LCONTROL;
2186 r = VK_RCONTROL;
2188 else
2190 l = VK_LMENU;
2191 r = VK_RMENU;
2193 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2194 modifiers_recorded = 1;
2195 else
2196 modifiers_recorded = 0;
2197 modifier_key_support_tested = 1;
2200 static void
2201 record_keydown (unsigned int wparam, unsigned int lparam)
2203 int i;
2205 if (!modifier_key_support_tested)
2206 test_modifier_support (wparam);
2208 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2209 return;
2211 if (wparam == VK_CONTROL)
2212 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2213 else
2214 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2216 modifiers[i] = 1;
2219 static void
2220 record_keyup (unsigned int wparam, unsigned int lparam)
2222 int i;
2224 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2225 return;
2227 if (wparam == VK_CONTROL)
2228 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2229 else
2230 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2232 modifiers[i] = 0;
2235 /* Emacs can lose focus while a modifier key has been pressed. When
2236 it regains focus, be conservative and clear all modifiers since
2237 we cannot reconstruct the left and right modifier state. */
2238 static void
2239 reset_modifiers ()
2241 SHORT ctrl, alt;
2243 if (GetFocus () == NULL)
2244 /* Emacs doesn't have keyboard focus. Do nothing. */
2245 return;
2247 ctrl = GetAsyncKeyState (VK_CONTROL);
2248 alt = GetAsyncKeyState (VK_MENU);
2250 if (!(ctrl & 0x08000))
2251 /* Clear any recorded control modifier state. */
2252 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2254 if (!(alt & 0x08000))
2255 /* Clear any recorded alt modifier state. */
2256 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2258 /* Update the state of all modifier keys, because modifiers used in
2259 hot-key combinations can get stuck on if Emacs loses focus as a
2260 result of a hot-key being pressed. */
2262 BYTE keystate[256];
2264 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2266 GetKeyboardState (keystate);
2267 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2268 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2269 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2270 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2271 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2272 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2273 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2274 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2275 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2276 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2277 SetKeyboardState (keystate);
2281 /* Synchronize modifier state with what is reported with the current
2282 keystroke. Even if we cannot distinguish between left and right
2283 modifier keys, we know that, if no modifiers are set, then neither
2284 the left or right modifier should be set. */
2285 static void
2286 sync_modifiers ()
2288 if (!modifiers_recorded)
2289 return;
2291 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2292 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2294 if (!(GetKeyState (VK_MENU) & 0x8000))
2295 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2298 static int
2299 modifier_set (int vkey)
2301 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
2302 return (GetKeyState (vkey) & 0x1);
2303 if (!modifiers_recorded)
2304 return (GetKeyState (vkey) & 0x8000);
2306 switch (vkey)
2308 case VK_LCONTROL:
2309 return modifiers[EMACS_LCONTROL];
2310 case VK_RCONTROL:
2311 return modifiers[EMACS_RCONTROL];
2312 case VK_LMENU:
2313 return modifiers[EMACS_LMENU];
2314 case VK_RMENU:
2315 return modifiers[EMACS_RMENU];
2317 return (GetKeyState (vkey) & 0x8000);
2320 /* Convert between the modifier bits W32 uses and the modifier bits
2321 Emacs uses. */
2323 unsigned int
2324 w32_key_to_modifier (int key)
2326 Lisp_Object key_mapping;
2328 switch (key)
2330 case VK_LWIN:
2331 key_mapping = Vw32_lwindow_modifier;
2332 break;
2333 case VK_RWIN:
2334 key_mapping = Vw32_rwindow_modifier;
2335 break;
2336 case VK_APPS:
2337 key_mapping = Vw32_apps_modifier;
2338 break;
2339 case VK_SCROLL:
2340 key_mapping = Vw32_scroll_lock_modifier;
2341 break;
2342 default:
2343 key_mapping = Qnil;
2346 /* NB. This code runs in the input thread, asychronously to the lisp
2347 thread, so we must be careful to ensure access to lisp data is
2348 thread-safe. The following code is safe because the modifier
2349 variable values are updated atomically from lisp and symbols are
2350 not relocated by GC. Also, we don't have to worry about seeing GC
2351 markbits here. */
2352 if (EQ (key_mapping, Qhyper))
2353 return hyper_modifier;
2354 if (EQ (key_mapping, Qsuper))
2355 return super_modifier;
2356 if (EQ (key_mapping, Qmeta))
2357 return meta_modifier;
2358 if (EQ (key_mapping, Qalt))
2359 return alt_modifier;
2360 if (EQ (key_mapping, Qctrl))
2361 return ctrl_modifier;
2362 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2363 return ctrl_modifier;
2364 if (EQ (key_mapping, Qshift))
2365 return shift_modifier;
2367 /* Don't generate any modifier if not explicitly requested. */
2368 return 0;
2371 unsigned int
2372 w32_get_modifiers ()
2374 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2375 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2376 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2377 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2378 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2379 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2380 (modifier_set (VK_MENU) ?
2381 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2384 /* We map the VK_* modifiers into console modifier constants
2385 so that we can use the same routines to handle both console
2386 and window input. */
2388 static int
2389 construct_console_modifiers ()
2391 int mods;
2393 mods = 0;
2394 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2395 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2396 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2397 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2398 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2399 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2400 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2401 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2402 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2403 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2404 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2406 return mods;
2409 static int
2410 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2412 int mods;
2414 /* Convert to emacs modifiers. */
2415 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2417 return mods;
2420 unsigned int
2421 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2423 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2424 return virt_key;
2426 if (virt_key == VK_RETURN)
2427 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2429 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2430 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2432 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2433 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2435 if (virt_key == VK_CLEAR)
2436 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2438 return virt_key;
2441 /* List of special key combinations which w32 would normally capture,
2442 but emacs should grab instead. Not directly visible to lisp, to
2443 simplify synchronization. Each item is an integer encoding a virtual
2444 key code and modifier combination to capture. */
2445 Lisp_Object w32_grabbed_keys;
2447 #define HOTKEY(vk,mods) make_number (((vk) & 255) | ((mods) << 8))
2448 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2449 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2450 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2452 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2453 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2454 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2456 /* Register hot-keys for reserved key combinations when Emacs has
2457 keyboard focus, since this is the only way Emacs can receive key
2458 combinations like Alt-Tab which are used by the system. */
2460 static void
2461 register_hot_keys (hwnd)
2462 HWND hwnd;
2464 Lisp_Object keylist;
2466 /* Use GC_CONSP, since we are called asynchronously. */
2467 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2469 Lisp_Object key = XCAR (keylist);
2471 /* Deleted entries get set to nil. */
2472 if (!INTEGERP (key))
2473 continue;
2475 RegisterHotKey (hwnd, HOTKEY_ID (key),
2476 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2480 static void
2481 unregister_hot_keys (hwnd)
2482 HWND hwnd;
2484 Lisp_Object keylist;
2486 /* Use GC_CONSP, since we are called asynchronously. */
2487 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2489 Lisp_Object key = XCAR (keylist);
2491 if (!INTEGERP (key))
2492 continue;
2494 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2498 /* Main message dispatch loop. */
2500 static void
2501 w32_msg_pump (deferred_msg * msg_buf)
2503 MSG msg;
2504 int result;
2505 HWND focus_window;
2507 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2509 while (GetMessage (&msg, NULL, 0, 0))
2511 if (msg.hwnd == NULL)
2513 switch (msg.message)
2515 case WM_NULL:
2516 /* Produced by complete_deferred_msg; just ignore. */
2517 break;
2518 case WM_EMACS_CREATEWINDOW:
2519 /* Initialize COM for this window. Even though we don't use it,
2520 some third party shell extensions can cause it to be used in
2521 system dialogs, which causes a crash if it is not initialized.
2522 This is a known bug in Windows, which was fixed long ago, but
2523 the patch for XP is not publically available until XP SP3,
2524 and older versions will never be patched. */
2525 CoInitialize (NULL);
2526 w32_createwindow ((struct frame *) msg.wParam);
2527 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2528 abort ();
2529 break;
2530 case WM_EMACS_SETLOCALE:
2531 SetThreadLocale (msg.wParam);
2532 /* Reply is not expected. */
2533 break;
2534 case WM_EMACS_SETKEYBOARDLAYOUT:
2535 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2536 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2537 result, 0))
2538 abort ();
2539 break;
2540 case WM_EMACS_REGISTER_HOT_KEY:
2541 focus_window = GetFocus ();
2542 if (focus_window != NULL)
2543 RegisterHotKey (focus_window,
2544 RAW_HOTKEY_ID (msg.wParam),
2545 RAW_HOTKEY_MODIFIERS (msg.wParam),
2546 RAW_HOTKEY_VK_CODE (msg.wParam));
2547 /* Reply is not expected. */
2548 break;
2549 case WM_EMACS_UNREGISTER_HOT_KEY:
2550 focus_window = GetFocus ();
2551 if (focus_window != NULL)
2552 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2553 /* Mark item as erased. NB: this code must be
2554 thread-safe. The next line is okay because the cons
2555 cell is never made into garbage and is not relocated by
2556 GC. */
2557 XSETCAR ((Lisp_Object) ((EMACS_INT) msg.lParam), Qnil);
2558 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2559 abort ();
2560 break;
2561 case WM_EMACS_TOGGLE_LOCK_KEY:
2563 int vk_code = (int) msg.wParam;
2564 int cur_state = (GetKeyState (vk_code) & 1);
2565 Lisp_Object new_state = (Lisp_Object) ((EMACS_INT) msg.lParam);
2567 /* NB: This code must be thread-safe. It is safe to
2568 call NILP because symbols are not relocated by GC,
2569 and pointer here is not touched by GC (so the markbit
2570 can't be set). Numbers are safe because they are
2571 immediate values. */
2572 if (NILP (new_state)
2573 || (NUMBERP (new_state)
2574 && ((XUINT (new_state)) & 1) != cur_state))
2576 one_w32_display_info.faked_key = vk_code;
2578 keybd_event ((BYTE) vk_code,
2579 (BYTE) MapVirtualKey (vk_code, 0),
2580 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2581 keybd_event ((BYTE) vk_code,
2582 (BYTE) MapVirtualKey (vk_code, 0),
2583 KEYEVENTF_EXTENDEDKEY | 0, 0);
2584 keybd_event ((BYTE) vk_code,
2585 (BYTE) MapVirtualKey (vk_code, 0),
2586 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2587 cur_state = !cur_state;
2589 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2590 cur_state, 0))
2591 abort ();
2593 break;
2594 default:
2595 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2598 else
2600 DispatchMessage (&msg);
2603 /* Exit nested loop when our deferred message has completed. */
2604 if (msg_buf->completed)
2605 break;
2609 deferred_msg * deferred_msg_head;
2611 static deferred_msg *
2612 find_deferred_msg (HWND hwnd, UINT msg)
2614 deferred_msg * item;
2616 /* Don't actually need synchronization for read access, since
2617 modification of single pointer is always atomic. */
2618 /* enter_crit (); */
2620 for (item = deferred_msg_head; item != NULL; item = item->next)
2621 if (item->w32msg.msg.hwnd == hwnd
2622 && item->w32msg.msg.message == msg)
2623 break;
2625 /* leave_crit (); */
2627 return item;
2630 static LRESULT
2631 send_deferred_msg (deferred_msg * msg_buf,
2632 HWND hwnd,
2633 UINT msg,
2634 WPARAM wParam,
2635 LPARAM lParam)
2637 /* Only input thread can send deferred messages. */
2638 if (GetCurrentThreadId () != dwWindowsThreadId)
2639 abort ();
2641 /* It is an error to send a message that is already deferred. */
2642 if (find_deferred_msg (hwnd, msg) != NULL)
2643 abort ();
2645 /* Enforced synchronization is not needed because this is the only
2646 function that alters deferred_msg_head, and the following critical
2647 section is guaranteed to only be serially reentered (since only the
2648 input thread can call us). */
2650 /* enter_crit (); */
2652 msg_buf->completed = 0;
2653 msg_buf->next = deferred_msg_head;
2654 deferred_msg_head = msg_buf;
2655 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2657 /* leave_crit (); */
2659 /* Start a new nested message loop to process other messages until
2660 this one is completed. */
2661 w32_msg_pump (msg_buf);
2663 deferred_msg_head = msg_buf->next;
2665 return msg_buf->result;
2668 void
2669 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2671 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2673 if (msg_buf == NULL)
2674 /* Message may have been cancelled, so don't abort(). */
2675 return;
2677 msg_buf->result = result;
2678 msg_buf->completed = 1;
2680 /* Ensure input thread is woken so it notices the completion. */
2681 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2684 void
2685 cancel_all_deferred_msgs ()
2687 deferred_msg * item;
2689 /* Don't actually need synchronization for read access, since
2690 modification of single pointer is always atomic. */
2691 /* enter_crit (); */
2693 for (item = deferred_msg_head; item != NULL; item = item->next)
2695 item->result = 0;
2696 item->completed = 1;
2699 /* leave_crit (); */
2701 /* Ensure input thread is woken so it notices the completion. */
2702 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2705 DWORD WINAPI
2706 w32_msg_worker (void *arg)
2708 MSG msg;
2709 deferred_msg dummy_buf;
2711 /* Ensure our message queue is created */
2713 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2715 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2716 abort ();
2718 memset (&dummy_buf, 0, sizeof (dummy_buf));
2719 dummy_buf.w32msg.msg.hwnd = NULL;
2720 dummy_buf.w32msg.msg.message = WM_NULL;
2722 /* This is the inital message loop which should only exit when the
2723 application quits. */
2724 w32_msg_pump (&dummy_buf);
2726 return 0;
2729 static void
2730 signal_user_input ()
2732 /* Interrupt any lisp that wants to be interrupted by input. */
2733 if (!NILP (Vthrow_on_input))
2735 Vquit_flag = Vthrow_on_input;
2736 /* If we're inside a function that wants immediate quits,
2737 do it now. */
2738 if (immediate_quit && NILP (Vinhibit_quit))
2740 immediate_quit = 0;
2741 QUIT;
2747 static void
2748 post_character_message (hwnd, msg, wParam, lParam, modifiers)
2749 HWND hwnd;
2750 UINT msg;
2751 WPARAM wParam;
2752 LPARAM lParam;
2753 DWORD modifiers;
2756 W32Msg wmsg;
2758 wmsg.dwModifiers = modifiers;
2760 /* Detect quit_char and set quit-flag directly. Note that we
2761 still need to post a message to ensure the main thread will be
2762 woken up if blocked in sys_select(), but we do NOT want to post
2763 the quit_char message itself (because it will usually be as if
2764 the user had typed quit_char twice). Instead, we post a dummy
2765 message that has no particular effect. */
2767 int c = wParam;
2768 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2769 c = make_ctrl_char (c) & 0377;
2770 if (c == quit_char
2771 || (wmsg.dwModifiers == 0 &&
2772 w32_quit_key && wParam == w32_quit_key))
2774 Vquit_flag = Qt;
2776 /* The choice of message is somewhat arbitrary, as long as
2777 the main thread handler just ignores it. */
2778 msg = WM_NULL;
2780 /* Interrupt any blocking system calls. */
2781 signal_quit ();
2783 /* As a safety precaution, forcibly complete any deferred
2784 messages. This is a kludge, but I don't see any particularly
2785 clean way to handle the situation where a deferred message is
2786 "dropped" in the lisp thread, and will thus never be
2787 completed, eg. by the user trying to activate the menubar
2788 when the lisp thread is busy, and then typing C-g when the
2789 menubar doesn't open promptly (with the result that the
2790 menubar never responds at all because the deferred
2791 WM_INITMENU message is never completed). Another problem
2792 situation is when the lisp thread calls SendMessage (to send
2793 a window manager command) when a message has been deferred;
2794 the lisp thread gets blocked indefinitely waiting for the
2795 deferred message to be completed, which itself is waiting for
2796 the lisp thread to respond.
2798 Note that we don't want to block the input thread waiting for
2799 a reponse from the lisp thread (although that would at least
2800 solve the deadlock problem above), because we want to be able
2801 to receive C-g to interrupt the lisp thread. */
2802 cancel_all_deferred_msgs ();
2804 else
2805 signal_user_input ();
2808 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2811 /* Main window procedure */
2813 LRESULT CALLBACK
2814 w32_wnd_proc (hwnd, msg, wParam, lParam)
2815 HWND hwnd;
2816 UINT msg;
2817 WPARAM wParam;
2818 LPARAM lParam;
2820 struct frame *f;
2821 struct w32_display_info *dpyinfo = &one_w32_display_info;
2822 W32Msg wmsg;
2823 int windows_translate;
2824 int key;
2826 /* Note that it is okay to call x_window_to_frame, even though we are
2827 not running in the main lisp thread, because frame deletion
2828 requires the lisp thread to synchronize with this thread. Thus, if
2829 a frame struct is returned, it can be used without concern that the
2830 lisp thread might make it disappear while we are using it.
2832 NB. Walking the frame list in this thread is safe (as long as
2833 writes of Lisp_Object slots are atomic, which they are on Windows).
2834 Although delete-frame can destructively modify the frame list while
2835 we are walking it, a garbage collection cannot occur until after
2836 delete-frame has synchronized with this thread.
2838 It is also safe to use functions that make GDI calls, such as
2839 w32_clear_rect, because these functions must obtain a DC handle
2840 from the frame struct using get_frame_dc which is thread-aware. */
2842 switch (msg)
2844 case WM_ERASEBKGND:
2845 f = x_window_to_frame (dpyinfo, hwnd);
2846 if (f)
2848 HDC hdc = get_frame_dc (f);
2849 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2850 w32_clear_rect (f, hdc, &wmsg.rect);
2851 release_frame_dc (f, hdc);
2853 #if defined (W32_DEBUG_DISPLAY)
2854 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2856 wmsg.rect.left, wmsg.rect.top,
2857 wmsg.rect.right, wmsg.rect.bottom));
2858 #endif /* W32_DEBUG_DISPLAY */
2860 return 1;
2861 case WM_PALETTECHANGED:
2862 /* ignore our own changes */
2863 if ((HWND)wParam != hwnd)
2865 f = x_window_to_frame (dpyinfo, hwnd);
2866 if (f)
2867 /* get_frame_dc will realize our palette and force all
2868 frames to be redrawn if needed. */
2869 release_frame_dc (f, get_frame_dc (f));
2871 return 0;
2872 case WM_PAINT:
2874 PAINTSTRUCT paintStruct;
2875 RECT update_rect;
2876 bzero (&update_rect, sizeof (update_rect));
2878 f = x_window_to_frame (dpyinfo, hwnd);
2879 if (f == 0)
2881 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2882 return 0;
2885 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2886 fails. Apparently this can happen under some
2887 circumstances. */
2888 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2890 enter_crit ();
2891 BeginPaint (hwnd, &paintStruct);
2893 /* The rectangles returned by GetUpdateRect and BeginPaint
2894 do not always match. Play it safe by assuming both areas
2895 are invalid. */
2896 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2898 #if defined (W32_DEBUG_DISPLAY)
2899 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2901 wmsg.rect.left, wmsg.rect.top,
2902 wmsg.rect.right, wmsg.rect.bottom));
2903 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2904 update_rect.left, update_rect.top,
2905 update_rect.right, update_rect.bottom));
2906 #endif
2907 EndPaint (hwnd, &paintStruct);
2908 leave_crit ();
2910 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2912 return 0;
2915 /* If GetUpdateRect returns 0 (meaning there is no update
2916 region), assume the whole window needs to be repainted. */
2917 GetClientRect(hwnd, &wmsg.rect);
2918 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2919 return 0;
2922 case WM_INPUTLANGCHANGE:
2923 /* Inform lisp thread of keyboard layout changes. */
2924 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2926 /* Clear dead keys in the keyboard state; for simplicity only
2927 preserve modifier key states. */
2929 int i;
2930 BYTE keystate[256];
2932 GetKeyboardState (keystate);
2933 for (i = 0; i < 256; i++)
2934 if (1
2935 && i != VK_SHIFT
2936 && i != VK_LSHIFT
2937 && i != VK_RSHIFT
2938 && i != VK_CAPITAL
2939 && i != VK_NUMLOCK
2940 && i != VK_SCROLL
2941 && i != VK_CONTROL
2942 && i != VK_LCONTROL
2943 && i != VK_RCONTROL
2944 && i != VK_MENU
2945 && i != VK_LMENU
2946 && i != VK_RMENU
2947 && i != VK_LWIN
2948 && i != VK_RWIN)
2949 keystate[i] = 0;
2950 SetKeyboardState (keystate);
2952 goto dflt;
2954 case WM_HOTKEY:
2955 /* Synchronize hot keys with normal input. */
2956 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2957 return (0);
2959 case WM_KEYUP:
2960 case WM_SYSKEYUP:
2961 record_keyup (wParam, lParam);
2962 goto dflt;
2964 case WM_KEYDOWN:
2965 case WM_SYSKEYDOWN:
2966 /* Ignore keystrokes we fake ourself; see below. */
2967 if (dpyinfo->faked_key == wParam)
2969 dpyinfo->faked_key = 0;
2970 /* Make sure TranslateMessage sees them though (as long as
2971 they don't produce WM_CHAR messages). This ensures that
2972 indicator lights are toggled promptly on Windows 9x, for
2973 example. */
2974 if (lispy_function_keys[wParam] != 0)
2976 windows_translate = 1;
2977 goto translate;
2979 return 0;
2982 /* Synchronize modifiers with current keystroke. */
2983 sync_modifiers ();
2984 record_keydown (wParam, lParam);
2985 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2987 windows_translate = 0;
2989 switch (wParam)
2991 case VK_LWIN:
2992 if (NILP (Vw32_pass_lwindow_to_system))
2994 /* Prevent system from acting on keyup (which opens the
2995 Start menu if no other key was pressed) by simulating a
2996 press of Space which we will ignore. */
2997 if (GetAsyncKeyState (wParam) & 1)
2999 if (NUMBERP (Vw32_phantom_key_code))
3000 key = XUINT (Vw32_phantom_key_code) & 255;
3001 else
3002 key = VK_SPACE;
3003 dpyinfo->faked_key = key;
3004 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3007 if (!NILP (Vw32_lwindow_modifier))
3008 return 0;
3009 break;
3010 case VK_RWIN:
3011 if (NILP (Vw32_pass_rwindow_to_system))
3013 if (GetAsyncKeyState (wParam) & 1)
3015 if (NUMBERP (Vw32_phantom_key_code))
3016 key = XUINT (Vw32_phantom_key_code) & 255;
3017 else
3018 key = VK_SPACE;
3019 dpyinfo->faked_key = key;
3020 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3023 if (!NILP (Vw32_rwindow_modifier))
3024 return 0;
3025 break;
3026 case VK_APPS:
3027 if (!NILP (Vw32_apps_modifier))
3028 return 0;
3029 break;
3030 case VK_MENU:
3031 if (NILP (Vw32_pass_alt_to_system))
3032 /* Prevent DefWindowProc from activating the menu bar if an
3033 Alt key is pressed and released by itself. */
3034 return 0;
3035 windows_translate = 1;
3036 break;
3037 case VK_CAPITAL:
3038 /* Decide whether to treat as modifier or function key. */
3039 if (NILP (Vw32_enable_caps_lock))
3040 goto disable_lock_key;
3041 windows_translate = 1;
3042 break;
3043 case VK_NUMLOCK:
3044 /* Decide whether to treat as modifier or function key. */
3045 if (NILP (Vw32_enable_num_lock))
3046 goto disable_lock_key;
3047 windows_translate = 1;
3048 break;
3049 case VK_SCROLL:
3050 /* Decide whether to treat as modifier or function key. */
3051 if (NILP (Vw32_scroll_lock_modifier))
3052 goto disable_lock_key;
3053 windows_translate = 1;
3054 break;
3055 disable_lock_key:
3056 /* Ensure the appropriate lock key state (and indicator light)
3057 remains in the same state. We do this by faking another
3058 press of the relevant key. Apparently, this really is the
3059 only way to toggle the state of the indicator lights. */
3060 dpyinfo->faked_key = wParam;
3061 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3062 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3063 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3064 KEYEVENTF_EXTENDEDKEY | 0, 0);
3065 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3066 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3067 /* Ensure indicator lights are updated promptly on Windows 9x
3068 (TranslateMessage apparently does this), after forwarding
3069 input event. */
3070 post_character_message (hwnd, msg, wParam, lParam,
3071 w32_get_key_modifiers (wParam, lParam));
3072 windows_translate = 1;
3073 break;
3074 case VK_CONTROL:
3075 case VK_SHIFT:
3076 case VK_PROCESSKEY: /* Generated by IME. */
3077 windows_translate = 1;
3078 break;
3079 case VK_CANCEL:
3080 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3081 which is confusing for purposes of key binding; convert
3082 VK_CANCEL events into VK_PAUSE events. */
3083 wParam = VK_PAUSE;
3084 break;
3085 case VK_PAUSE:
3086 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3087 for purposes of key binding; convert these back into
3088 VK_NUMLOCK events, at least when we want to see NumLock key
3089 presses. (Note that there is never any possibility that
3090 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3091 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3092 wParam = VK_NUMLOCK;
3093 break;
3094 default:
3095 /* If not defined as a function key, change it to a WM_CHAR message. */
3096 if (lispy_function_keys[wParam] == 0)
3098 DWORD modifiers = construct_console_modifiers ();
3100 if (!NILP (Vw32_recognize_altgr)
3101 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3103 /* Always let TranslateMessage handle AltGr key chords;
3104 for some reason, ToAscii doesn't always process AltGr
3105 chords correctly. */
3106 windows_translate = 1;
3108 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3110 /* Handle key chords including any modifiers other
3111 than shift directly, in order to preserve as much
3112 modifier information as possible. */
3113 if ('A' <= wParam && wParam <= 'Z')
3115 /* Don't translate modified alphabetic keystrokes,
3116 so the user doesn't need to constantly switch
3117 layout to type control or meta keystrokes when
3118 the normal layout translates alphabetic
3119 characters to non-ascii characters. */
3120 if (!modifier_set (VK_SHIFT))
3121 wParam += ('a' - 'A');
3122 msg = WM_CHAR;
3124 else
3126 /* Try to handle other keystrokes by determining the
3127 base character (ie. translating the base key plus
3128 shift modifier). */
3129 int add;
3130 int isdead = 0;
3131 KEY_EVENT_RECORD key;
3133 key.bKeyDown = TRUE;
3134 key.wRepeatCount = 1;
3135 key.wVirtualKeyCode = wParam;
3136 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3137 key.uChar.AsciiChar = 0;
3138 key.dwControlKeyState = modifiers;
3140 add = w32_kbd_patch_key (&key);
3141 /* 0 means an unrecognised keycode, negative means
3142 dead key. Ignore both. */
3143 while (--add >= 0)
3145 /* Forward asciified character sequence. */
3146 post_character_message
3147 (hwnd, WM_CHAR, key.uChar.AsciiChar, lParam,
3148 w32_get_key_modifiers (wParam, lParam));
3149 w32_kbd_patch_key (&key);
3151 return 0;
3154 else
3156 /* Let TranslateMessage handle everything else. */
3157 windows_translate = 1;
3162 translate:
3163 if (windows_translate)
3165 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3167 windows_msg.time = GetMessageTime ();
3168 TranslateMessage (&windows_msg);
3169 goto dflt;
3172 /* Fall through */
3174 case WM_SYSCHAR:
3175 case WM_CHAR:
3176 post_character_message (hwnd, msg, wParam, lParam,
3177 w32_get_key_modifiers (wParam, lParam));
3178 break;
3180 /* Simulate middle mouse button events when left and right buttons
3181 are used together, but only if user has two button mouse. */
3182 case WM_LBUTTONDOWN:
3183 case WM_RBUTTONDOWN:
3184 if (w32_num_mouse_buttons > 2)
3185 goto handle_plain_button;
3188 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3189 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3191 if (button_state & this)
3192 return 0;
3194 if (button_state == 0)
3195 SetCapture (hwnd);
3197 button_state |= this;
3199 if (button_state & other)
3201 if (mouse_button_timer)
3203 KillTimer (hwnd, mouse_button_timer);
3204 mouse_button_timer = 0;
3206 /* Generate middle mouse event instead. */
3207 msg = WM_MBUTTONDOWN;
3208 button_state |= MMOUSE;
3210 else if (button_state & MMOUSE)
3212 /* Ignore button event if we've already generated a
3213 middle mouse down event. This happens if the
3214 user releases and press one of the two buttons
3215 after we've faked a middle mouse event. */
3216 return 0;
3218 else
3220 /* Flush out saved message. */
3221 post_msg (&saved_mouse_button_msg);
3223 wmsg.dwModifiers = w32_get_modifiers ();
3224 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3225 signal_user_input ();
3227 /* Clear message buffer. */
3228 saved_mouse_button_msg.msg.hwnd = 0;
3230 else
3232 /* Hold onto message for now. */
3233 mouse_button_timer =
3234 SetTimer (hwnd, MOUSE_BUTTON_ID,
3235 w32_mouse_button_tolerance, NULL);
3236 saved_mouse_button_msg.msg.hwnd = hwnd;
3237 saved_mouse_button_msg.msg.message = msg;
3238 saved_mouse_button_msg.msg.wParam = wParam;
3239 saved_mouse_button_msg.msg.lParam = lParam;
3240 saved_mouse_button_msg.msg.time = GetMessageTime ();
3241 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3244 return 0;
3246 case WM_LBUTTONUP:
3247 case WM_RBUTTONUP:
3248 if (w32_num_mouse_buttons > 2)
3249 goto handle_plain_button;
3252 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3253 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3255 if ((button_state & this) == 0)
3256 return 0;
3258 button_state &= ~this;
3260 if (button_state & MMOUSE)
3262 /* Only generate event when second button is released. */
3263 if ((button_state & other) == 0)
3265 msg = WM_MBUTTONUP;
3266 button_state &= ~MMOUSE;
3268 if (button_state) abort ();
3270 else
3271 return 0;
3273 else
3275 /* Flush out saved message if necessary. */
3276 if (saved_mouse_button_msg.msg.hwnd)
3278 post_msg (&saved_mouse_button_msg);
3281 wmsg.dwModifiers = w32_get_modifiers ();
3282 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3283 signal_user_input ();
3285 /* Always clear message buffer and cancel timer. */
3286 saved_mouse_button_msg.msg.hwnd = 0;
3287 KillTimer (hwnd, mouse_button_timer);
3288 mouse_button_timer = 0;
3290 if (button_state == 0)
3291 ReleaseCapture ();
3293 return 0;
3295 case WM_XBUTTONDOWN:
3296 case WM_XBUTTONUP:
3297 if (w32_pass_extra_mouse_buttons_to_system)
3298 goto dflt;
3299 /* else fall through and process them. */
3300 case WM_MBUTTONDOWN:
3301 case WM_MBUTTONUP:
3302 handle_plain_button:
3304 BOOL up;
3305 int button;
3307 /* Ignore middle and extra buttons as long as the menu is active. */
3308 f = x_window_to_frame (dpyinfo, hwnd);
3309 if (f && f->output_data.w32->menubar_active)
3310 return 0;
3312 if (parse_button (msg, HIWORD (wParam), &button, &up))
3314 if (up) ReleaseCapture ();
3315 else SetCapture (hwnd);
3316 button = (button == 0) ? LMOUSE :
3317 ((button == 1) ? MMOUSE : RMOUSE);
3318 if (up)
3319 button_state &= ~button;
3320 else
3321 button_state |= button;
3325 wmsg.dwModifiers = w32_get_modifiers ();
3326 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3327 signal_user_input ();
3329 /* Need to return true for XBUTTON messages, false for others,
3330 to indicate that we processed the message. */
3331 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3333 case WM_MOUSEMOVE:
3334 /* Ignore mouse movements as long as the menu is active. These
3335 movements are processed by the window manager anyway, and
3336 it's wrong to handle them as if they happened on the
3337 underlying frame. */
3338 f = x_window_to_frame (dpyinfo, hwnd);
3339 if (f && f->output_data.w32->menubar_active)
3340 return 0;
3342 /* If the mouse has just moved into the frame, start tracking
3343 it, so we will be notified when it leaves the frame. Mouse
3344 tracking only works under W98 and NT4 and later. On earlier
3345 versions, there is no way of telling when the mouse leaves the
3346 frame, so we just have to put up with help-echo and mouse
3347 highlighting remaining while the frame is not active. */
3348 if (track_mouse_event_fn && !track_mouse_window)
3350 TRACKMOUSEEVENT tme;
3351 tme.cbSize = sizeof (tme);
3352 tme.dwFlags = TME_LEAVE;
3353 tme.hwndTrack = hwnd;
3355 track_mouse_event_fn (&tme);
3356 track_mouse_window = hwnd;
3358 case WM_VSCROLL:
3359 if (w32_mouse_move_interval <= 0
3360 || (msg == WM_MOUSEMOVE && button_state == 0))
3362 wmsg.dwModifiers = w32_get_modifiers ();
3363 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3364 return 0;
3367 /* Hang onto mouse move and scroll messages for a bit, to avoid
3368 sending such events to Emacs faster than it can process them.
3369 If we get more events before the timer from the first message
3370 expires, we just replace the first message. */
3372 if (saved_mouse_move_msg.msg.hwnd == 0)
3373 mouse_move_timer =
3374 SetTimer (hwnd, MOUSE_MOVE_ID,
3375 w32_mouse_move_interval, NULL);
3377 /* Hold onto message for now. */
3378 saved_mouse_move_msg.msg.hwnd = hwnd;
3379 saved_mouse_move_msg.msg.message = msg;
3380 saved_mouse_move_msg.msg.wParam = wParam;
3381 saved_mouse_move_msg.msg.lParam = lParam;
3382 saved_mouse_move_msg.msg.time = GetMessageTime ();
3383 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3385 return 0;
3387 case WM_MOUSEWHEEL:
3388 wmsg.dwModifiers = w32_get_modifiers ();
3389 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3390 signal_user_input ();
3391 return 0;
3393 case WM_DROPFILES:
3394 wmsg.dwModifiers = w32_get_modifiers ();
3395 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3396 signal_user_input ();
3397 return 0;
3399 case WM_TIMER:
3400 /* Flush out saved messages if necessary. */
3401 if (wParam == mouse_button_timer)
3403 if (saved_mouse_button_msg.msg.hwnd)
3405 post_msg (&saved_mouse_button_msg);
3406 signal_user_input ();
3407 saved_mouse_button_msg.msg.hwnd = 0;
3409 KillTimer (hwnd, mouse_button_timer);
3410 mouse_button_timer = 0;
3412 else if (wParam == mouse_move_timer)
3414 if (saved_mouse_move_msg.msg.hwnd)
3416 post_msg (&saved_mouse_move_msg);
3417 saved_mouse_move_msg.msg.hwnd = 0;
3419 KillTimer (hwnd, mouse_move_timer);
3420 mouse_move_timer = 0;
3422 else if (wParam == menu_free_timer)
3424 KillTimer (hwnd, menu_free_timer);
3425 menu_free_timer = 0;
3426 f = x_window_to_frame (dpyinfo, hwnd);
3427 /* If a popup menu is active, don't wipe its strings. */
3428 if (menubar_in_use
3429 && current_popup_menu == NULL)
3431 /* Free memory used by owner-drawn and help-echo strings. */
3432 w32_free_menu_strings (hwnd);
3433 f->output_data.w32->menubar_active = 0;
3434 menubar_in_use = 0;
3437 return 0;
3439 case WM_NCACTIVATE:
3440 /* Windows doesn't send us focus messages when putting up and
3441 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3442 The only indication we get that something happened is receiving
3443 this message afterwards. So this is a good time to reset our
3444 keyboard modifiers' state. */
3445 reset_modifiers ();
3446 goto dflt;
3448 case WM_INITMENU:
3449 button_state = 0;
3450 ReleaseCapture ();
3451 /* We must ensure menu bar is fully constructed and up to date
3452 before allowing user interaction with it. To achieve this
3453 we send this message to the lisp thread and wait for a
3454 reply (whose value is not actually needed) to indicate that
3455 the menu bar is now ready for use, so we can now return.
3457 To remain responsive in the meantime, we enter a nested message
3458 loop that can process all other messages.
3460 However, we skip all this if the message results from calling
3461 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3462 thread a message because it is blocked on us at this point. We
3463 set menubar_active before calling TrackPopupMenu to indicate
3464 this (there is no possibility of confusion with real menubar
3465 being active). */
3467 f = x_window_to_frame (dpyinfo, hwnd);
3468 if (f
3469 && (f->output_data.w32->menubar_active
3470 /* We can receive this message even in the absence of a
3471 menubar (ie. when the system menu is activated) - in this
3472 case we do NOT want to forward the message, otherwise it
3473 will cause the menubar to suddenly appear when the user
3474 had requested it to be turned off! */
3475 || f->output_data.w32->menubar_widget == NULL))
3476 return 0;
3479 deferred_msg msg_buf;
3481 /* Detect if message has already been deferred; in this case
3482 we cannot return any sensible value to ignore this. */
3483 if (find_deferred_msg (hwnd, msg) != NULL)
3484 abort ();
3486 menubar_in_use = 1;
3488 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3491 case WM_EXITMENULOOP:
3492 f = x_window_to_frame (dpyinfo, hwnd);
3494 /* If a menu is still active, check again after a short delay,
3495 since Windows often (always?) sends the WM_EXITMENULOOP
3496 before the corresponding WM_COMMAND message.
3497 Don't do this if a popup menu is active, since it is only
3498 menubar menus that require cleaning up in this way.
3500 if (f && menubar_in_use && current_popup_menu == NULL)
3501 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3502 goto dflt;
3504 case WM_MENUSELECT:
3505 /* Direct handling of help_echo in menus. Should be safe now
3506 that we generate the help_echo by placing a help event in the
3507 keyboard buffer. */
3509 HMENU menu = (HMENU) lParam;
3510 UINT menu_item = (UINT) LOWORD (wParam);
3511 UINT flags = (UINT) HIWORD (wParam);
3513 w32_menu_display_help (hwnd, menu, menu_item, flags);
3515 return 0;
3517 case WM_MEASUREITEM:
3518 f = x_window_to_frame (dpyinfo, hwnd);
3519 if (f)
3521 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3523 if (pMis->CtlType == ODT_MENU)
3525 /* Work out dimensions for popup menu titles. */
3526 char * title = (char *) pMis->itemData;
3527 HDC hdc = GetDC (hwnd);
3528 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3529 LOGFONT menu_logfont;
3530 HFONT old_font;
3531 SIZE size;
3533 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3534 menu_logfont.lfWeight = FW_BOLD;
3535 menu_font = CreateFontIndirect (&menu_logfont);
3536 old_font = SelectObject (hdc, menu_font);
3538 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3539 if (title)
3541 if (unicode_append_menu)
3542 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3543 wcslen ((WCHAR *) title),
3544 &size);
3545 else
3546 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3548 pMis->itemWidth = size.cx;
3549 if (pMis->itemHeight < size.cy)
3550 pMis->itemHeight = size.cy;
3552 else
3553 pMis->itemWidth = 0;
3555 SelectObject (hdc, old_font);
3556 DeleteObject (menu_font);
3557 ReleaseDC (hwnd, hdc);
3558 return TRUE;
3561 return 0;
3563 case WM_DRAWITEM:
3564 f = x_window_to_frame (dpyinfo, hwnd);
3565 if (f)
3567 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3569 if (pDis->CtlType == ODT_MENU)
3571 /* Draw popup menu title. */
3572 char * title = (char *) pDis->itemData;
3573 if (title)
3575 HDC hdc = pDis->hDC;
3576 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3577 LOGFONT menu_logfont;
3578 HFONT old_font;
3580 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3581 menu_logfont.lfWeight = FW_BOLD;
3582 menu_font = CreateFontIndirect (&menu_logfont);
3583 old_font = SelectObject (hdc, menu_font);
3585 /* Always draw title as if not selected. */
3586 if (unicode_append_menu)
3587 ExtTextOutW (hdc,
3588 pDis->rcItem.left
3589 + GetSystemMetrics (SM_CXMENUCHECK),
3590 pDis->rcItem.top,
3591 ETO_OPAQUE, &pDis->rcItem,
3592 (WCHAR *) title,
3593 wcslen ((WCHAR *) title), NULL);
3594 else
3595 ExtTextOut (hdc,
3596 pDis->rcItem.left
3597 + GetSystemMetrics (SM_CXMENUCHECK),
3598 pDis->rcItem.top,
3599 ETO_OPAQUE, &pDis->rcItem,
3600 title, strlen (title), NULL);
3602 SelectObject (hdc, old_font);
3603 DeleteObject (menu_font);
3605 return TRUE;
3608 return 0;
3610 #if 0
3611 /* Still not right - can't distinguish between clicks in the
3612 client area of the frame from clicks forwarded from the scroll
3613 bars - may have to hook WM_NCHITTEST to remember the mouse
3614 position and then check if it is in the client area ourselves. */
3615 case WM_MOUSEACTIVATE:
3616 /* Discard the mouse click that activates a frame, allowing the
3617 user to click anywhere without changing point (or worse!).
3618 Don't eat mouse clicks on scrollbars though!! */
3619 if (LOWORD (lParam) == HTCLIENT )
3620 return MA_ACTIVATEANDEAT;
3621 goto dflt;
3622 #endif
3624 case WM_MOUSELEAVE:
3625 /* No longer tracking mouse. */
3626 track_mouse_window = NULL;
3628 case WM_ACTIVATEAPP:
3629 case WM_ACTIVATE:
3630 case WM_WINDOWPOSCHANGED:
3631 case WM_SHOWWINDOW:
3632 /* Inform lisp thread that a frame might have just been obscured
3633 or exposed, so should recheck visibility of all frames. */
3634 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3635 goto dflt;
3637 case WM_SETFOCUS:
3638 dpyinfo->faked_key = 0;
3639 reset_modifiers ();
3640 register_hot_keys (hwnd);
3641 goto command;
3642 case WM_KILLFOCUS:
3643 unregister_hot_keys (hwnd);
3644 button_state = 0;
3645 ReleaseCapture ();
3646 /* Relinquish the system caret. */
3647 if (w32_system_caret_hwnd)
3649 w32_visible_system_caret_hwnd = NULL;
3650 w32_system_caret_hwnd = NULL;
3651 DestroyCaret ();
3653 goto command;
3654 case WM_COMMAND:
3655 menubar_in_use = 0;
3656 f = x_window_to_frame (dpyinfo, hwnd);
3657 if (f && HIWORD (wParam) == 0)
3659 if (menu_free_timer)
3661 KillTimer (hwnd, menu_free_timer);
3662 menu_free_timer = 0;
3665 case WM_MOVE:
3666 case WM_SIZE:
3667 command:
3668 wmsg.dwModifiers = w32_get_modifiers ();
3669 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3670 goto dflt;
3672 case WM_DESTROY:
3673 CoUninitialize ();
3674 return 0;
3676 case WM_CLOSE:
3677 wmsg.dwModifiers = w32_get_modifiers ();
3678 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3679 return 0;
3681 case WM_WINDOWPOSCHANGING:
3682 /* Don't restrict the sizing of tip frames. */
3683 if (hwnd == tip_window)
3684 return 0;
3686 WINDOWPLACEMENT wp;
3687 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3689 wp.length = sizeof (WINDOWPLACEMENT);
3690 GetWindowPlacement (hwnd, &wp);
3692 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
3694 RECT rect;
3695 int wdiff;
3696 int hdiff;
3697 DWORD font_width;
3698 DWORD line_height;
3699 DWORD internal_border;
3700 DWORD scrollbar_extra;
3701 RECT wr;
3703 wp.length = sizeof(wp);
3704 GetWindowRect (hwnd, &wr);
3706 enter_crit ();
3708 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3709 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3710 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3711 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3713 leave_crit ();
3715 memset (&rect, 0, sizeof (rect));
3716 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3717 GetMenu (hwnd) != NULL);
3719 /* Force width and height of client area to be exact
3720 multiples of the character cell dimensions. */
3721 wdiff = (lppos->cx - (rect.right - rect.left)
3722 - 2 * internal_border - scrollbar_extra)
3723 % font_width;
3724 hdiff = (lppos->cy - (rect.bottom - rect.top)
3725 - 2 * internal_border)
3726 % line_height;
3728 if (wdiff || hdiff)
3730 /* For right/bottom sizing we can just fix the sizes.
3731 However for top/left sizing we will need to fix the X
3732 and Y positions as well. */
3734 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3735 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3737 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3738 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3740 if (wp.showCmd != SW_SHOWMAXIMIZED
3741 && (lppos->flags & SWP_NOMOVE) == 0)
3743 if (lppos->x != wr.left || lppos->y != wr.top)
3745 lppos->x += wdiff;
3746 lppos->y += hdiff;
3748 else
3750 lppos->flags |= SWP_NOMOVE;
3754 return 0;
3759 goto dflt;
3761 case WM_GETMINMAXINFO:
3762 /* Hack to allow resizing the Emacs frame above the screen size.
3763 Note that Windows 9x limits coordinates to 16-bits. */
3764 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3765 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3766 return 0;
3768 case WM_SETCURSOR:
3769 if (LOWORD (lParam) == HTCLIENT)
3770 return 0;
3772 goto dflt;
3774 case WM_EMACS_SETCURSOR:
3776 Cursor cursor = (Cursor) wParam;
3777 if (cursor)
3778 SetCursor (cursor);
3779 return 0;
3782 case WM_EMACS_CREATESCROLLBAR:
3783 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3784 (struct scroll_bar *) lParam);
3786 case WM_EMACS_SHOWWINDOW:
3787 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3789 case WM_EMACS_SETFOREGROUND:
3791 HWND foreground_window;
3792 DWORD foreground_thread, retval;
3794 /* On NT 5.0, and apparently Windows 98, it is necessary to
3795 attach to the thread that currently has focus in order to
3796 pull the focus away from it. */
3797 foreground_window = GetForegroundWindow ();
3798 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3799 if (!foreground_window
3800 || foreground_thread == GetCurrentThreadId ()
3801 || !AttachThreadInput (GetCurrentThreadId (),
3802 foreground_thread, TRUE))
3803 foreground_thread = 0;
3805 retval = SetForegroundWindow ((HWND) wParam);
3807 /* Detach from the previous foreground thread. */
3808 if (foreground_thread)
3809 AttachThreadInput (GetCurrentThreadId (),
3810 foreground_thread, FALSE);
3812 return retval;
3815 case WM_EMACS_SETWINDOWPOS:
3817 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3818 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3819 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3822 case WM_EMACS_DESTROYWINDOW:
3823 DragAcceptFiles ((HWND) wParam, FALSE);
3824 return DestroyWindow ((HWND) wParam);
3826 case WM_EMACS_HIDE_CARET:
3827 return HideCaret (hwnd);
3829 case WM_EMACS_SHOW_CARET:
3830 return ShowCaret (hwnd);
3832 case WM_EMACS_DESTROY_CARET:
3833 w32_system_caret_hwnd = NULL;
3834 w32_visible_system_caret_hwnd = NULL;
3835 return DestroyCaret ();
3837 case WM_EMACS_TRACK_CARET:
3838 /* If there is currently no system caret, create one. */
3839 if (w32_system_caret_hwnd == NULL)
3841 /* Use the default caret width, and avoid changing it
3842 unneccesarily, as it confuses screen reader software. */
3843 w32_system_caret_hwnd = hwnd;
3844 CreateCaret (hwnd, NULL, 0,
3845 w32_system_caret_height);
3848 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3849 return 0;
3850 /* Ensure visible caret gets turned on when requested. */
3851 else if (w32_use_visible_system_caret
3852 && w32_visible_system_caret_hwnd != hwnd)
3854 w32_visible_system_caret_hwnd = hwnd;
3855 return ShowCaret (hwnd);
3857 /* Ensure visible caret gets turned off when requested. */
3858 else if (!w32_use_visible_system_caret
3859 && w32_visible_system_caret_hwnd)
3861 w32_visible_system_caret_hwnd = NULL;
3862 return HideCaret (hwnd);
3864 else
3865 return 1;
3867 case WM_EMACS_TRACKPOPUPMENU:
3869 UINT flags;
3870 POINT *pos;
3871 int retval;
3872 pos = (POINT *)lParam;
3873 flags = TPM_CENTERALIGN;
3874 if (button_state & LMOUSE)
3875 flags |= TPM_LEFTBUTTON;
3876 else if (button_state & RMOUSE)
3877 flags |= TPM_RIGHTBUTTON;
3879 /* Remember we did a SetCapture on the initial mouse down event,
3880 so for safety, we make sure the capture is cancelled now. */
3881 ReleaseCapture ();
3882 button_state = 0;
3884 /* Use menubar_active to indicate that WM_INITMENU is from
3885 TrackPopupMenu below, and should be ignored. */
3886 f = x_window_to_frame (dpyinfo, hwnd);
3887 if (f)
3888 f->output_data.w32->menubar_active = 1;
3890 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
3891 0, hwnd, NULL))
3893 MSG amsg;
3894 /* Eat any mouse messages during popupmenu */
3895 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
3896 PM_REMOVE));
3897 /* Get the menu selection, if any */
3898 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
3900 retval = LOWORD (amsg.wParam);
3902 else
3904 retval = 0;
3907 else
3909 retval = -1;
3912 return retval;
3915 default:
3916 /* Check for messages registered at runtime. */
3917 if (msg == msh_mousewheel)
3919 wmsg.dwModifiers = w32_get_modifiers ();
3920 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3921 signal_user_input ();
3922 return 0;
3925 dflt:
3926 return DefWindowProc (hwnd, msg, wParam, lParam);
3930 /* The most common default return code for handled messages is 0. */
3931 return 0;
3934 static void
3935 my_create_window (f)
3936 struct frame * f;
3938 MSG msg;
3940 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
3941 abort ();
3942 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
3946 /* Create a tooltip window. Unlike my_create_window, we do not do this
3947 indirectly via the Window thread, as we do not need to process Window
3948 messages for the tooltip. Creating tooltips indirectly also creates
3949 deadlocks when tooltips are created for menu items. */
3950 static void
3951 my_create_tip_window (f)
3952 struct frame *f;
3954 RECT rect;
3956 rect.left = rect.top = 0;
3957 rect.right = FRAME_PIXEL_WIDTH (f);
3958 rect.bottom = FRAME_PIXEL_HEIGHT (f);
3960 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3961 FRAME_EXTERNAL_MENU_BAR (f));
3963 tip_window = FRAME_W32_WINDOW (f)
3964 = CreateWindow (EMACS_CLASS,
3965 f->namebuf,
3966 f->output_data.w32->dwStyle,
3967 f->left_pos,
3968 f->top_pos,
3969 rect.right - rect.left,
3970 rect.bottom - rect.top,
3971 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
3972 NULL,
3973 hinst,
3974 NULL);
3976 if (tip_window)
3978 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
3979 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
3980 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
3981 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3983 /* Tip frames have no scrollbars. */
3984 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
3986 /* Do this to discard the default setting specified by our parent. */
3987 ShowWindow (tip_window, SW_HIDE);
3992 /* Create and set up the w32 window for frame F. */
3994 static void
3995 w32_window (f, window_prompting, minibuffer_only)
3996 struct frame *f;
3997 long window_prompting;
3998 int minibuffer_only;
4000 BLOCK_INPUT;
4002 /* Use the resource name as the top-level window name
4003 for looking up resources. Make a non-Lisp copy
4004 for the window manager, so GC relocation won't bother it.
4006 Elsewhere we specify the window name for the window manager. */
4009 char *str = (char *) SDATA (Vx_resource_name);
4010 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4011 strcpy (f->namebuf, str);
4014 my_create_window (f);
4016 validate_x_resource_name ();
4018 /* x_set_name normally ignores requests to set the name if the
4019 requested name is the same as the current name. This is the one
4020 place where that assumption isn't correct; f->name is set, but
4021 the server hasn't been told. */
4023 Lisp_Object name;
4024 int explicit = f->explicit_name;
4026 f->explicit_name = 0;
4027 name = f->name;
4028 f->name = Qnil;
4029 x_set_name (f, name, explicit);
4032 UNBLOCK_INPUT;
4034 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4035 initialize_frame_menubar (f);
4037 if (FRAME_W32_WINDOW (f) == 0)
4038 error ("Unable to create window");
4041 /* Handle the icon stuff for this window. Perhaps later we might
4042 want an x_set_icon_position which can be called interactively as
4043 well. */
4045 static void
4046 x_icon (f, parms)
4047 struct frame *f;
4048 Lisp_Object parms;
4050 Lisp_Object icon_x, icon_y;
4052 /* Set the position of the icon. Note that Windows 95 groups all
4053 icons in the tray. */
4054 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4055 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4056 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4058 CHECK_NUMBER (icon_x);
4059 CHECK_NUMBER (icon_y);
4061 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4062 error ("Both left and top icon corners of icon must be specified");
4064 BLOCK_INPUT;
4066 if (! EQ (icon_x, Qunbound))
4067 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4069 #if 0 /* TODO */
4070 /* Start up iconic or window? */
4071 x_wm_set_window_state
4072 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4073 ? IconicState
4074 : NormalState));
4076 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
4077 ? f->icon_name
4078 : f->name)));
4079 #endif
4081 UNBLOCK_INPUT;
4085 static void
4086 x_make_gc (f)
4087 struct frame *f;
4089 XGCValues gc_values;
4091 BLOCK_INPUT;
4093 /* Create the GC's of this frame.
4094 Note that many default values are used. */
4096 /* Normal video */
4097 gc_values.font = FRAME_FONT (f);
4099 /* Cursor has cursor-color background, background-color foreground. */
4100 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4101 gc_values.background = f->output_data.w32->cursor_pixel;
4102 f->output_data.w32->cursor_gc
4103 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4104 (GCFont | GCForeground | GCBackground),
4105 &gc_values);
4107 /* Reliefs. */
4108 f->output_data.w32->white_relief.gc = 0;
4109 f->output_data.w32->black_relief.gc = 0;
4111 UNBLOCK_INPUT;
4115 /* Handler for signals raised during x_create_frame and
4116 x_create_top_frame. FRAME is the frame which is partially
4117 constructed. */
4119 static Lisp_Object
4120 unwind_create_frame (frame)
4121 Lisp_Object frame;
4123 struct frame *f = XFRAME (frame);
4125 /* If frame is ``official'', nothing to do. */
4126 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
4128 #ifdef GLYPH_DEBUG
4129 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4130 #endif
4132 x_free_frame_resources (f);
4134 /* Check that reference counts are indeed correct. */
4135 xassert (dpyinfo->reference_count == dpyinfo_refcount);
4136 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
4138 return Qt;
4141 return Qnil;
4145 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4146 1, 1, 0,
4147 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4148 Returns an Emacs frame object.
4149 PARAMETERS is an alist of frame parameters.
4150 If the parameters specify that the frame should not have a minibuffer,
4151 and do not specify a specific minibuffer window to use,
4152 then `default-minibuffer-frame' must be a frame whose minibuffer can
4153 be shared by the new frame.
4155 This function is an internal primitive--use `make-frame' instead. */)
4156 (parameters)
4157 Lisp_Object parameters;
4159 struct frame *f;
4160 Lisp_Object frame, tem;
4161 Lisp_Object name;
4162 int minibuffer_only = 0;
4163 long window_prompting = 0;
4164 int width, height;
4165 int count = SPECPDL_INDEX ();
4166 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4167 Lisp_Object display;
4168 struct w32_display_info *dpyinfo = NULL;
4169 Lisp_Object parent;
4170 struct kboard *kb;
4172 check_w32 ();
4174 /* Use this general default value to start with
4175 until we know if this frame has a specified name. */
4176 Vx_resource_name = Vinvocation_name;
4178 display = w32_get_arg (parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4179 if (EQ (display, Qunbound))
4180 display = Qnil;
4181 dpyinfo = check_x_display_info (display);
4182 #ifdef MULTI_KBOARD
4183 kb = dpyinfo->kboard;
4184 #else
4185 kb = &the_only_kboard;
4186 #endif
4188 name = w32_get_arg (parameters, Qname, "name", "Name", RES_TYPE_STRING);
4189 if (!STRINGP (name)
4190 && ! EQ (name, Qunbound)
4191 && ! NILP (name))
4192 error ("Invalid frame name--not a string or nil");
4194 if (STRINGP (name))
4195 Vx_resource_name = name;
4197 /* See if parent window is specified. */
4198 parent = w32_get_arg (parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4199 if (EQ (parent, Qunbound))
4200 parent = Qnil;
4201 if (! NILP (parent))
4202 CHECK_NUMBER (parent);
4204 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4205 /* No need to protect DISPLAY because that's not used after passing
4206 it to make_frame_without_minibuffer. */
4207 frame = Qnil;
4208 GCPRO4 (parameters, parent, name, frame);
4209 tem = w32_get_arg (parameters, Qminibuffer, "minibuffer", "Minibuffer",
4210 RES_TYPE_SYMBOL);
4211 if (EQ (tem, Qnone) || NILP (tem))
4212 f = make_frame_without_minibuffer (Qnil, kb, display);
4213 else if (EQ (tem, Qonly))
4215 f = make_minibuffer_frame ();
4216 minibuffer_only = 1;
4218 else if (WINDOWP (tem))
4219 f = make_frame_without_minibuffer (tem, kb, display);
4220 else
4221 f = make_frame (1);
4223 XSETFRAME (frame, f);
4225 /* Note that Windows does support scroll bars. */
4226 FRAME_CAN_HAVE_SCROLL_BARS (f) = 1;
4228 /* By default, make scrollbars the system standard width. */
4229 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4231 f->output_method = output_w32;
4232 f->output_data.w32 =
4233 (struct w32_output *) xmalloc (sizeof (struct w32_output));
4234 bzero (f->output_data.w32, sizeof (struct w32_output));
4235 FRAME_FONTSET (f) = -1;
4236 record_unwind_protect (unwind_create_frame, frame);
4238 f->icon_name
4239 = w32_get_arg (parameters, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
4240 if (! STRINGP (f->icon_name))
4241 f->icon_name = Qnil;
4243 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
4244 #ifdef MULTI_KBOARD
4245 FRAME_KBOARD (f) = kb;
4246 #endif
4248 /* Specify the parent under which to make this window. */
4250 if (!NILP (parent))
4252 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4253 f->output_data.w32->explicit_parent = 1;
4255 else
4257 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4258 f->output_data.w32->explicit_parent = 0;
4261 /* Set the name; the functions to which we pass f expect the name to
4262 be set. */
4263 if (EQ (name, Qunbound) || NILP (name))
4265 f->name = build_string (dpyinfo->w32_id_name);
4266 f->explicit_name = 0;
4268 else
4270 f->name = name;
4271 f->explicit_name = 1;
4272 /* use the frame's title when getting resources for this frame. */
4273 specbind (Qx_resource_name, name);
4276 /* Extract the window parameters from the supplied values
4277 that are needed to determine window geometry. */
4279 Lisp_Object font;
4281 font = w32_get_arg (parameters, Qfont, "font", "Font", RES_TYPE_STRING);
4283 BLOCK_INPUT;
4284 /* First, try whatever font the caller has specified. */
4285 if (STRINGP (font))
4287 tem = Fquery_fontset (font, Qnil);
4288 if (STRINGP (tem))
4289 font = x_new_fontset (f, SDATA (tem));
4290 else
4291 font = x_new_font (f, SDATA (font));
4293 /* Try out a font which we hope has bold and italic variations. */
4294 if (!STRINGP (font))
4295 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
4296 if (! STRINGP (font))
4297 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
4298 /* If those didn't work, look for something which will at least work. */
4299 if (! STRINGP (font))
4300 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
4301 UNBLOCK_INPUT;
4302 if (! STRINGP (font))
4303 font = build_string ("Fixedsys");
4305 x_default_parameter (f, parameters, Qfont, font,
4306 "font", "Font", RES_TYPE_STRING);
4309 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4310 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4311 /* This defaults to 2 in order to match xterm. We recognize either
4312 internalBorderWidth or internalBorder (which is what xterm calls
4313 it). */
4314 if (NILP (Fassq (Qinternal_border_width, parameters)))
4316 Lisp_Object value;
4318 value = w32_get_arg (parameters, Qinternal_border_width,
4319 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4320 if (! EQ (value, Qunbound))
4321 parameters = Fcons (Fcons (Qinternal_border_width, value),
4322 parameters);
4324 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4325 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4326 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4327 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4328 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4330 /* Also do the stuff which must be set before the window exists. */
4331 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4332 "foreground", "Foreground", RES_TYPE_STRING);
4333 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4334 "background", "Background", RES_TYPE_STRING);
4335 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4336 "pointerColor", "Foreground", RES_TYPE_STRING);
4337 x_default_parameter (f, parameters, Qcursor_color, build_string ("black"),
4338 "cursorColor", "Foreground", RES_TYPE_STRING);
4339 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4340 "borderColor", "BorderColor", RES_TYPE_STRING);
4341 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4342 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4343 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4344 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4345 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4346 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4347 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4348 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4351 /* Init faces before x_default_parameter is called for scroll-bar
4352 parameters because that function calls x_set_scroll_bar_width,
4353 which calls change_frame_size, which calls Fset_window_buffer,
4354 which runs hooks, which call Fvertical_motion. At the end, we
4355 end up in init_iterator with a null face cache, which should not
4356 happen. */
4357 init_frame_faces (f);
4359 x_default_parameter (f, parameters, Qmenu_bar_lines, make_number (1),
4360 "menuBar", "MenuBar", RES_TYPE_NUMBER);
4361 x_default_parameter (f, parameters, Qtool_bar_lines, make_number (1),
4362 "toolBar", "ToolBar", RES_TYPE_NUMBER);
4364 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4365 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4366 x_default_parameter (f, parameters, Qtitle, Qnil,
4367 "title", "Title", RES_TYPE_STRING);
4368 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4369 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4371 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4372 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4374 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4375 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4376 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4377 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4378 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4379 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4381 window_prompting = x_figure_window_size (f, parameters, 1);
4383 tem = w32_get_arg (parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4384 f->no_split = minibuffer_only || EQ (tem, Qt);
4386 w32_window (f, window_prompting, minibuffer_only);
4387 x_icon (f, parameters);
4389 x_make_gc (f);
4391 /* Now consider the frame official. */
4392 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
4393 Vframe_list = Fcons (frame, Vframe_list);
4395 /* We need to do this after creating the window, so that the
4396 icon-creation functions can say whose icon they're describing. */
4397 x_default_parameter (f, parameters, Qicon_type, Qnil,
4398 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4400 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4401 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4402 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4403 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4404 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4405 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4406 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4407 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4409 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4410 Change will not be effected unless different from the current
4411 FRAME_LINES (f). */
4412 width = FRAME_COLS (f);
4413 height = FRAME_LINES (f);
4415 FRAME_LINES (f) = 0;
4416 SET_FRAME_COLS (f, 0);
4417 change_frame_size (f, height, width, 1, 0, 0);
4419 /* Tell the server what size and position, etc, we want, and how
4420 badly we want them. This should be done after we have the menu
4421 bar so that its size can be taken into account. */
4422 BLOCK_INPUT;
4423 x_wm_set_size_hint (f, window_prompting, 0);
4424 UNBLOCK_INPUT;
4426 /* Make the window appear on the frame and enable display, unless
4427 the caller says not to. However, with explicit parent, Emacs
4428 cannot control visibility, so don't try. */
4429 if (! f->output_data.w32->explicit_parent)
4431 Lisp_Object visibility;
4433 visibility = w32_get_arg (parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4434 if (EQ (visibility, Qunbound))
4435 visibility = Qt;
4437 if (EQ (visibility, Qicon))
4438 x_iconify_frame (f);
4439 else if (! NILP (visibility))
4440 x_make_frame_visible (f);
4441 else
4442 /* Must have been Qnil. */
4445 UNGCPRO;
4447 /* Make sure windows on this frame appear in calls to next-window
4448 and similar functions. */
4449 Vwindow_list = Qnil;
4451 return unbind_to (count, frame);
4454 /* FRAME is used only to get a handle on the X display. We don't pass the
4455 display info directly because we're called from frame.c, which doesn't
4456 know about that structure. */
4457 Lisp_Object
4458 x_get_focus_frame (frame)
4459 struct frame *frame;
4461 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
4462 Lisp_Object xfocus;
4463 if (! dpyinfo->w32_focus_frame)
4464 return Qnil;
4466 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4467 return xfocus;
4470 DEFUN ("w32-focus-frame", Fw32_focus_frame, Sw32_focus_frame, 1, 1, 0,
4471 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
4472 (frame)
4473 Lisp_Object frame;
4475 x_focus_on_frame (check_x_frame (frame));
4476 return Qnil;
4480 /* Return the charset portion of a font name. */
4481 char * xlfd_charset_of_font (char * fontname)
4483 char *charset, *encoding;
4485 encoding = strrchr(fontname, '-');
4486 if (!encoding || encoding == fontname)
4487 return NULL;
4489 for (charset = encoding - 1; charset >= fontname; charset--)
4490 if (*charset == '-')
4491 break;
4493 if (charset == fontname || strcmp(charset, "-*-*") == 0)
4494 return NULL;
4496 return charset + 1;
4499 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
4500 int size, char* filename);
4501 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
4502 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
4503 char * charset);
4504 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
4506 static struct font_info *
4507 w32_load_system_font (f,fontname,size)
4508 struct frame *f;
4509 char * fontname;
4510 int size;
4512 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4513 Lisp_Object font_names;
4515 /* Get a list of all the fonts that match this name. Once we
4516 have a list of matching fonts, we compare them against the fonts
4517 we already have loaded by comparing names. */
4518 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
4520 if (!NILP (font_names))
4522 Lisp_Object tail;
4523 int i;
4525 /* First check if any are already loaded, as that is cheaper
4526 than loading another one. */
4527 for (i = 0; i < dpyinfo->n_fonts; i++)
4528 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
4529 if (dpyinfo->font_table[i].name
4530 && (!strcmp (dpyinfo->font_table[i].name,
4531 SDATA (XCAR (tail)))
4532 || !strcmp (dpyinfo->font_table[i].full_name,
4533 SDATA (XCAR (tail)))))
4534 return (dpyinfo->font_table + i);
4536 fontname = (char *) SDATA (XCAR (font_names));
4538 else if (w32_strict_fontnames)
4540 /* If EnumFontFamiliesEx was available, we got a full list of
4541 fonts back so stop now to avoid the possibility of loading a
4542 random font. If we had to fall back to EnumFontFamilies, the
4543 list is incomplete, so continue whether the font we want was
4544 listed or not. */
4545 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
4546 FARPROC enum_font_families_ex
4547 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
4548 if (enum_font_families_ex)
4549 return NULL;
4552 /* Load the font and add it to the table. */
4554 char *full_name, *encoding, *charset;
4555 XFontStruct *font;
4556 struct font_info *fontp;
4557 LOGFONT lf;
4558 BOOL ok;
4559 int codepage;
4560 int i;
4562 if (!fontname || !x_to_w32_font (fontname, &lf))
4563 return (NULL);
4565 if (!*lf.lfFaceName)
4566 /* If no name was specified for the font, we get a random font
4567 from CreateFontIndirect - this is not particularly
4568 desirable, especially since CreateFontIndirect does not
4569 fill out the missing name in lf, so we never know what we
4570 ended up with. */
4571 return NULL;
4573 lf.lfQuality = DEFAULT_QUALITY;
4575 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
4576 bzero (font, sizeof (*font));
4578 /* Set bdf to NULL to indicate that this is a Windows font. */
4579 font->bdf = NULL;
4581 BLOCK_INPUT;
4583 font->hfont = CreateFontIndirect (&lf);
4585 if (font->hfont == NULL)
4587 ok = FALSE;
4589 else
4591 HDC hdc;
4592 HANDLE oldobj;
4594 codepage = w32_codepage_for_font (fontname);
4596 hdc = GetDC (dpyinfo->root_window);
4597 oldobj = SelectObject (hdc, font->hfont);
4599 ok = GetTextMetrics (hdc, &font->tm);
4600 if (codepage == CP_UNICODE)
4601 font->double_byte_p = 1;
4602 else
4604 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
4605 don't report themselves as double byte fonts, when
4606 patently they are. So instead of trusting
4607 GetFontLanguageInfo, we check the properties of the
4608 codepage directly, since that is ultimately what we are
4609 working from anyway. */
4610 /* font->double_byte_p = GetFontLanguageInfo(hdc) & GCP_DBCS; */
4611 CPINFO cpi = {0};
4612 GetCPInfo (codepage, &cpi);
4613 font->double_byte_p = cpi.MaxCharSize > 1;
4616 SelectObject (hdc, oldobj);
4617 ReleaseDC (dpyinfo->root_window, hdc);
4618 /* Fill out details in lf according to the font that was
4619 actually loaded. */
4620 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
4621 lf.lfWidth = font->tm.tmMaxCharWidth;
4622 lf.lfWeight = font->tm.tmWeight;
4623 lf.lfItalic = font->tm.tmItalic;
4624 lf.lfCharSet = font->tm.tmCharSet;
4625 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
4626 ? VARIABLE_PITCH : FIXED_PITCH);
4627 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
4628 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
4630 w32_cache_char_metrics (font);
4633 UNBLOCK_INPUT;
4635 if (!ok)
4637 w32_unload_font (dpyinfo, font);
4638 return (NULL);
4641 /* Find a free slot in the font table. */
4642 for (i = 0; i < dpyinfo->n_fonts; ++i)
4643 if (dpyinfo->font_table[i].name == NULL)
4644 break;
4646 /* If no free slot found, maybe enlarge the font table. */
4647 if (i == dpyinfo->n_fonts
4648 && dpyinfo->n_fonts == dpyinfo->font_table_size)
4650 int sz;
4651 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
4652 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
4653 dpyinfo->font_table
4654 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
4657 fontp = dpyinfo->font_table + i;
4658 if (i == dpyinfo->n_fonts)
4659 ++dpyinfo->n_fonts;
4661 /* Now fill in the slots of *FONTP. */
4662 BLOCK_INPUT;
4663 bzero (fontp, sizeof (*fontp));
4664 fontp->font = font;
4665 fontp->font_idx = i;
4666 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
4667 bcopy (fontname, fontp->name, strlen (fontname) + 1);
4669 if (lf.lfPitchAndFamily == FIXED_PITCH)
4671 /* Fixed width font. */
4672 fontp->average_width = fontp->space_width = FONT_WIDTH (font);
4674 else
4676 wchar_t space = 32;
4677 XCharStruct* pcm;
4678 pcm = w32_per_char_metric (font, &space, ANSI_FONT);
4679 if (pcm)
4680 fontp->space_width = pcm->width;
4681 else
4682 fontp->space_width = FONT_WIDTH (font);
4684 fontp->average_width = font->tm.tmAveCharWidth;
4687 charset = xlfd_charset_of_font (fontname);
4689 /* Cache the W32 codepage for a font. This makes w32_encode_char
4690 (called for every glyph during redisplay) much faster. */
4691 fontp->codepage = codepage;
4693 /* Work out the font's full name. */
4694 full_name = (char *)xmalloc (100);
4695 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
4696 fontp->full_name = full_name;
4697 else
4699 /* If all else fails - just use the name we used to load it. */
4700 xfree (full_name);
4701 fontp->full_name = fontp->name;
4704 fontp->size = FONT_WIDTH (font);
4705 fontp->height = FONT_HEIGHT (font);
4707 /* The slot `encoding' specifies how to map a character
4708 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
4709 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
4710 (0:0x20..0x7F, 1:0xA0..0xFF,
4711 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
4712 2:0xA020..0xFF7F). For the moment, we don't know which charset
4713 uses this font. So, we set information in fontp->encoding[1]
4714 which is never used by any charset. If mapping can't be
4715 decided, set FONT_ENCODING_NOT_DECIDED. */
4717 /* SJIS fonts need to be set to type 4, all others seem to work as
4718 type FONT_ENCODING_NOT_DECIDED. */
4719 encoding = strrchr (fontp->name, '-');
4720 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
4721 fontp->encoding[1] = 4;
4722 else
4723 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
4725 /* The following three values are set to 0 under W32, which is
4726 what they get set to if XGetFontProperty fails under X. */
4727 fontp->baseline_offset = 0;
4728 fontp->relative_compose = 0;
4729 fontp->default_ascent = 0;
4731 /* Set global flag fonts_changed_p to non-zero if the font loaded
4732 has a character with a smaller width than any other character
4733 before, or if the font loaded has a smaller height than any
4734 other font loaded before. If this happens, it will make a
4735 glyph matrix reallocation necessary. */
4736 fonts_changed_p |= x_compute_min_glyph_bounds (f);
4737 UNBLOCK_INPUT;
4738 return fontp;
4742 /* Load font named FONTNAME of size SIZE for frame F, and return a
4743 pointer to the structure font_info while allocating it dynamically.
4744 If loading fails, return NULL. */
4745 struct font_info *
4746 w32_load_font (f,fontname,size)
4747 struct frame *f;
4748 char * fontname;
4749 int size;
4751 Lisp_Object bdf_fonts;
4752 struct font_info *retval = NULL;
4753 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4755 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
4757 while (!retval && CONSP (bdf_fonts))
4759 char *bdf_name, *bdf_file;
4760 Lisp_Object bdf_pair;
4761 int i;
4763 bdf_name = SDATA (XCAR (bdf_fonts));
4764 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
4765 bdf_file = SDATA (XCDR (bdf_pair));
4767 // If the font is already loaded, do not load it again.
4768 for (i = 0; i < dpyinfo->n_fonts; i++)
4770 if ((dpyinfo->font_table[i].name
4771 && !strcmp (dpyinfo->font_table[i].name, bdf_name))
4772 || (dpyinfo->font_table[i].full_name
4773 && !strcmp (dpyinfo->font_table[i].full_name, bdf_name)))
4774 return dpyinfo->font_table + i;
4777 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
4779 bdf_fonts = XCDR (bdf_fonts);
4782 if (retval)
4783 return retval;
4785 return w32_load_system_font(f, fontname, size);
4789 void
4790 w32_unload_font (dpyinfo, font)
4791 struct w32_display_info *dpyinfo;
4792 XFontStruct * font;
4794 if (font)
4796 if (font->per_char) xfree (font->per_char);
4797 if (font->bdf) w32_free_bdf_font (font->bdf);
4799 if (font->hfont) DeleteObject(font->hfont);
4800 xfree (font);
4804 /* The font conversion stuff between x and w32 */
4806 /* X font string is as follows (from faces.el)
4807 * (let ((- "[-?]")
4808 * (foundry "[^-]+")
4809 * (family "[^-]+")
4810 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
4811 * (weight\? "\\([^-]*\\)") ; 1
4812 * (slant "\\([ior]\\)") ; 2
4813 * (slant\? "\\([^-]?\\)") ; 2
4814 * (swidth "\\([^-]*\\)") ; 3
4815 * (adstyle "[^-]*") ; 4
4816 * (pixelsize "[0-9]+")
4817 * (pointsize "[0-9][0-9]+")
4818 * (resx "[0-9][0-9]+")
4819 * (resy "[0-9][0-9]+")
4820 * (spacing "[cmp?*]")
4821 * (avgwidth "[0-9]+")
4822 * (registry "[^-]+")
4823 * (encoding "[^-]+")
4827 static LONG
4828 x_to_w32_weight (lpw)
4829 char * lpw;
4831 if (!lpw) return (FW_DONTCARE);
4833 if (stricmp (lpw,"heavy") == 0) return FW_HEAVY;
4834 else if (stricmp (lpw,"extrabold") == 0) return FW_EXTRABOLD;
4835 else if (stricmp (lpw,"bold") == 0) return FW_BOLD;
4836 else if (stricmp (lpw,"demibold") == 0) return FW_SEMIBOLD;
4837 else if (stricmp (lpw,"semibold") == 0) return FW_SEMIBOLD;
4838 else if (stricmp (lpw,"medium") == 0) return FW_MEDIUM;
4839 else if (stricmp (lpw,"normal") == 0) return FW_NORMAL;
4840 else if (stricmp (lpw,"light") == 0) return FW_LIGHT;
4841 else if (stricmp (lpw,"extralight") == 0) return FW_EXTRALIGHT;
4842 else if (stricmp (lpw,"thin") == 0) return FW_THIN;
4843 else
4844 return FW_DONTCARE;
4848 static char *
4849 w32_to_x_weight (fnweight)
4850 int fnweight;
4852 if (fnweight >= FW_HEAVY) return "heavy";
4853 if (fnweight >= FW_EXTRABOLD) return "extrabold";
4854 if (fnweight >= FW_BOLD) return "bold";
4855 if (fnweight >= FW_SEMIBOLD) return "demibold";
4856 if (fnweight >= FW_MEDIUM) return "medium";
4857 if (fnweight >= FW_NORMAL) return "normal";
4858 if (fnweight >= FW_LIGHT) return "light";
4859 if (fnweight >= FW_EXTRALIGHT) return "extralight";
4860 if (fnweight >= FW_THIN) return "thin";
4861 else
4862 return "*";
4865 static LONG
4866 x_to_w32_charset (lpcs)
4867 char * lpcs;
4869 Lisp_Object this_entry, w32_charset;
4870 char *charset;
4871 int len = strlen (lpcs);
4873 /* Support "*-#nnn" format for unknown charsets. */
4874 if (strncmp (lpcs, "*-#", 3) == 0)
4875 return atoi (lpcs + 3);
4877 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
4878 charset = alloca (len + 1);
4879 strcpy (charset, lpcs);
4880 lpcs = strchr (charset, '*');
4881 if (lpcs)
4882 *lpcs = 0;
4884 /* Look through w32-charset-info-alist for the character set.
4885 Format of each entry is
4886 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
4888 this_entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
4890 if (NILP(this_entry))
4892 /* At startup, we want iso8859-1 fonts to come up properly. */
4893 if (stricmp(charset, "iso8859-1") == 0)
4894 return ANSI_CHARSET;
4895 else
4896 return DEFAULT_CHARSET;
4899 w32_charset = Fcar (Fcdr (this_entry));
4901 /* Translate Lisp symbol to number. */
4902 if (EQ (w32_charset, Qw32_charset_ansi))
4903 return ANSI_CHARSET;
4904 if (EQ (w32_charset, Qw32_charset_symbol))
4905 return SYMBOL_CHARSET;
4906 if (EQ (w32_charset, Qw32_charset_shiftjis))
4907 return SHIFTJIS_CHARSET;
4908 if (EQ (w32_charset, Qw32_charset_hangeul))
4909 return HANGEUL_CHARSET;
4910 if (EQ (w32_charset, Qw32_charset_chinesebig5))
4911 return CHINESEBIG5_CHARSET;
4912 if (EQ (w32_charset, Qw32_charset_gb2312))
4913 return GB2312_CHARSET;
4914 if (EQ (w32_charset, Qw32_charset_oem))
4915 return OEM_CHARSET;
4916 #ifdef JOHAB_CHARSET
4917 if (EQ (w32_charset, Qw32_charset_johab))
4918 return JOHAB_CHARSET;
4919 if (EQ (w32_charset, Qw32_charset_easteurope))
4920 return EASTEUROPE_CHARSET;
4921 if (EQ (w32_charset, Qw32_charset_turkish))
4922 return TURKISH_CHARSET;
4923 if (EQ (w32_charset, Qw32_charset_baltic))
4924 return BALTIC_CHARSET;
4925 if (EQ (w32_charset, Qw32_charset_russian))
4926 return RUSSIAN_CHARSET;
4927 if (EQ (w32_charset, Qw32_charset_arabic))
4928 return ARABIC_CHARSET;
4929 if (EQ (w32_charset, Qw32_charset_greek))
4930 return GREEK_CHARSET;
4931 if (EQ (w32_charset, Qw32_charset_hebrew))
4932 return HEBREW_CHARSET;
4933 if (EQ (w32_charset, Qw32_charset_vietnamese))
4934 return VIETNAMESE_CHARSET;
4935 if (EQ (w32_charset, Qw32_charset_thai))
4936 return THAI_CHARSET;
4937 if (EQ (w32_charset, Qw32_charset_mac))
4938 return MAC_CHARSET;
4939 #endif /* JOHAB_CHARSET */
4940 #ifdef UNICODE_CHARSET
4941 if (EQ (w32_charset, Qw32_charset_unicode))
4942 return UNICODE_CHARSET;
4943 #endif
4945 return DEFAULT_CHARSET;
4949 static char *
4950 w32_to_x_charset (fncharset)
4951 int fncharset;
4953 static char buf[32];
4954 Lisp_Object charset_type;
4956 switch (fncharset)
4958 case ANSI_CHARSET:
4959 /* Handle startup case of w32-charset-info-alist not
4960 being set up yet. */
4961 if (NILP(Vw32_charset_info_alist))
4962 return "iso8859-1";
4963 charset_type = Qw32_charset_ansi;
4964 break;
4965 case DEFAULT_CHARSET:
4966 charset_type = Qw32_charset_default;
4967 break;
4968 case SYMBOL_CHARSET:
4969 charset_type = Qw32_charset_symbol;
4970 break;
4971 case SHIFTJIS_CHARSET:
4972 charset_type = Qw32_charset_shiftjis;
4973 break;
4974 case HANGEUL_CHARSET:
4975 charset_type = Qw32_charset_hangeul;
4976 break;
4977 case GB2312_CHARSET:
4978 charset_type = Qw32_charset_gb2312;
4979 break;
4980 case CHINESEBIG5_CHARSET:
4981 charset_type = Qw32_charset_chinesebig5;
4982 break;
4983 case OEM_CHARSET:
4984 charset_type = Qw32_charset_oem;
4985 break;
4987 /* More recent versions of Windows (95 and NT4.0) define more
4988 character sets. */
4989 #ifdef EASTEUROPE_CHARSET
4990 case EASTEUROPE_CHARSET:
4991 charset_type = Qw32_charset_easteurope;
4992 break;
4993 case TURKISH_CHARSET:
4994 charset_type = Qw32_charset_turkish;
4995 break;
4996 case BALTIC_CHARSET:
4997 charset_type = Qw32_charset_baltic;
4998 break;
4999 case RUSSIAN_CHARSET:
5000 charset_type = Qw32_charset_russian;
5001 break;
5002 case ARABIC_CHARSET:
5003 charset_type = Qw32_charset_arabic;
5004 break;
5005 case GREEK_CHARSET:
5006 charset_type = Qw32_charset_greek;
5007 break;
5008 case HEBREW_CHARSET:
5009 charset_type = Qw32_charset_hebrew;
5010 break;
5011 case VIETNAMESE_CHARSET:
5012 charset_type = Qw32_charset_vietnamese;
5013 break;
5014 case THAI_CHARSET:
5015 charset_type = Qw32_charset_thai;
5016 break;
5017 case MAC_CHARSET:
5018 charset_type = Qw32_charset_mac;
5019 break;
5020 case JOHAB_CHARSET:
5021 charset_type = Qw32_charset_johab;
5022 break;
5023 #endif
5025 #ifdef UNICODE_CHARSET
5026 case UNICODE_CHARSET:
5027 charset_type = Qw32_charset_unicode;
5028 break;
5029 #endif
5030 default:
5031 /* Encode numerical value of unknown charset. */
5032 sprintf (buf, "*-#%u", fncharset);
5033 return buf;
5037 Lisp_Object rest;
5038 char * best_match = NULL;
5040 /* Look through w32-charset-info-alist for the character set.
5041 Prefer ISO codepages, and prefer lower numbers in the ISO
5042 range. Only return charsets for codepages which are installed.
5044 Format of each entry is
5045 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5047 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5049 char * x_charset;
5050 Lisp_Object w32_charset;
5051 Lisp_Object codepage;
5053 Lisp_Object this_entry = XCAR (rest);
5055 /* Skip invalid entries in alist. */
5056 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5057 || !CONSP (XCDR (this_entry))
5058 || !SYMBOLP (XCAR (XCDR (this_entry))))
5059 continue;
5061 x_charset = SDATA (XCAR (this_entry));
5062 w32_charset = XCAR (XCDR (this_entry));
5063 codepage = XCDR (XCDR (this_entry));
5065 /* Look for Same charset and a valid codepage (or non-int
5066 which means ignore). */
5067 if (EQ (w32_charset, charset_type)
5068 && (!INTEGERP (codepage) || XINT (codepage) == CP_DEFAULT
5069 || IsValidCodePage (XINT (codepage))))
5071 /* If we don't have a match already, then this is the
5072 best. */
5073 if (!best_match)
5074 best_match = x_charset;
5075 /* If this is an ISO codepage, and the best so far isn't,
5076 then this is better. */
5077 else if (strnicmp (best_match, "iso", 3) != 0
5078 && strnicmp (x_charset, "iso", 3) == 0)
5079 best_match = x_charset;
5080 /* If both are ISO8859 codepages, choose the one with the
5081 lowest number in the encoding field. */
5082 else if (strnicmp (best_match, "iso8859-", 8) == 0
5083 && strnicmp (x_charset, "iso8859-", 8) == 0)
5085 int best_enc = atoi (best_match + 8);
5086 int this_enc = atoi (x_charset + 8);
5087 if (this_enc > 0 && this_enc < best_enc)
5088 best_match = x_charset;
5093 /* If no match, encode the numeric value. */
5094 if (!best_match)
5096 sprintf (buf, "*-#%u", fncharset);
5097 return buf;
5100 strncpy(buf, best_match, 31);
5101 buf[31] = '\0';
5102 return buf;
5107 /* Return all the X charsets that map to a font. */
5108 static Lisp_Object
5109 w32_to_all_x_charsets (fncharset)
5110 int fncharset;
5112 static char buf[32];
5113 Lisp_Object charset_type;
5114 Lisp_Object retval = Qnil;
5116 switch (fncharset)
5118 case ANSI_CHARSET:
5119 /* Handle startup case of w32-charset-info-alist not
5120 being set up yet. */
5121 if (NILP(Vw32_charset_info_alist))
5122 return Fcons (build_string ("iso8859-1"), Qnil);
5124 charset_type = Qw32_charset_ansi;
5125 break;
5126 case DEFAULT_CHARSET:
5127 charset_type = Qw32_charset_default;
5128 break;
5129 case SYMBOL_CHARSET:
5130 charset_type = Qw32_charset_symbol;
5131 break;
5132 case SHIFTJIS_CHARSET:
5133 charset_type = Qw32_charset_shiftjis;
5134 break;
5135 case HANGEUL_CHARSET:
5136 charset_type = Qw32_charset_hangeul;
5137 break;
5138 case GB2312_CHARSET:
5139 charset_type = Qw32_charset_gb2312;
5140 break;
5141 case CHINESEBIG5_CHARSET:
5142 charset_type = Qw32_charset_chinesebig5;
5143 break;
5144 case OEM_CHARSET:
5145 charset_type = Qw32_charset_oem;
5146 break;
5148 /* More recent versions of Windows (95 and NT4.0) define more
5149 character sets. */
5150 #ifdef EASTEUROPE_CHARSET
5151 case EASTEUROPE_CHARSET:
5152 charset_type = Qw32_charset_easteurope;
5153 break;
5154 case TURKISH_CHARSET:
5155 charset_type = Qw32_charset_turkish;
5156 break;
5157 case BALTIC_CHARSET:
5158 charset_type = Qw32_charset_baltic;
5159 break;
5160 case RUSSIAN_CHARSET:
5161 charset_type = Qw32_charset_russian;
5162 break;
5163 case ARABIC_CHARSET:
5164 charset_type = Qw32_charset_arabic;
5165 break;
5166 case GREEK_CHARSET:
5167 charset_type = Qw32_charset_greek;
5168 break;
5169 case HEBREW_CHARSET:
5170 charset_type = Qw32_charset_hebrew;
5171 break;
5172 case VIETNAMESE_CHARSET:
5173 charset_type = Qw32_charset_vietnamese;
5174 break;
5175 case THAI_CHARSET:
5176 charset_type = Qw32_charset_thai;
5177 break;
5178 case MAC_CHARSET:
5179 charset_type = Qw32_charset_mac;
5180 break;
5181 case JOHAB_CHARSET:
5182 charset_type = Qw32_charset_johab;
5183 break;
5184 #endif
5186 #ifdef UNICODE_CHARSET
5187 case UNICODE_CHARSET:
5188 charset_type = Qw32_charset_unicode;
5189 break;
5190 #endif
5191 default:
5192 /* Encode numerical value of unknown charset. */
5193 sprintf (buf, "*-#%u", fncharset);
5194 return Fcons (build_string (buf), Qnil);
5198 Lisp_Object rest;
5199 /* Look through w32-charset-info-alist for the character set.
5200 Only return charsets for codepages which are installed.
5202 Format of each entry in Vw32_charset_info_alist is
5203 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5205 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5207 Lisp_Object x_charset;
5208 Lisp_Object w32_charset;
5209 Lisp_Object codepage;
5211 Lisp_Object this_entry = XCAR (rest);
5213 /* Skip invalid entries in alist. */
5214 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5215 || !CONSP (XCDR (this_entry))
5216 || !SYMBOLP (XCAR (XCDR (this_entry))))
5217 continue;
5219 x_charset = XCAR (this_entry);
5220 w32_charset = XCAR (XCDR (this_entry));
5221 codepage = XCDR (XCDR (this_entry));
5223 /* Look for Same charset and a valid codepage (or non-int
5224 which means ignore). */
5225 if (EQ (w32_charset, charset_type)
5226 && (!INTEGERP (codepage) || XINT (codepage) == CP_DEFAULT
5227 || IsValidCodePage (XINT (codepage))))
5229 retval = Fcons (x_charset, retval);
5233 /* If no match, encode the numeric value. */
5234 if (NILP (retval))
5236 sprintf (buf, "*-#%u", fncharset);
5237 return Fcons (build_string (buf), Qnil);
5240 return retval;
5244 /* Get the Windows codepage corresponding to the specified font. The
5245 charset info in the font name is used to look up
5246 w32-charset-to-codepage-alist. */
5248 w32_codepage_for_font (char *fontname)
5250 Lisp_Object codepage, entry;
5251 char *charset_str, *charset, *end;
5253 if (NILP (Vw32_charset_info_alist))
5254 return CP_DEFAULT;
5256 /* Extract charset part of font string. */
5257 charset = xlfd_charset_of_font (fontname);
5259 if (!charset)
5260 return CP_UNKNOWN;
5262 charset_str = (char *) alloca (strlen (charset) + 1);
5263 strcpy (charset_str, charset);
5265 #if 0
5266 /* Remove leading "*-". */
5267 if (strncmp ("*-", charset_str, 2) == 0)
5268 charset = charset_str + 2;
5269 else
5270 #endif
5271 charset = charset_str;
5273 /* Stop match at wildcard (including preceding '-'). */
5274 if (end = strchr (charset, '*'))
5276 if (end > charset && *(end-1) == '-')
5277 end--;
5278 *end = '\0';
5281 entry = Fassoc (build_string(charset), Vw32_charset_info_alist);
5282 if (NILP (entry))
5283 return CP_UNKNOWN;
5285 codepage = Fcdr (Fcdr (entry));
5287 if (NILP (codepage))
5288 return CP_8BIT;
5289 else if (XFASTINT (codepage) == XFASTINT (Qt))
5290 return CP_UNICODE;
5291 else if (INTEGERP (codepage))
5292 return XINT (codepage);
5293 else
5294 return CP_UNKNOWN;
5298 static BOOL
5299 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
5300 LOGFONT * lplogfont;
5301 char * lpxstr;
5302 int len;
5303 char * specific_charset;
5305 char* fonttype;
5306 char *fontname;
5307 char height_pixels[8];
5308 char height_dpi[8];
5309 char width_pixels[8];
5310 char *fontname_dash;
5311 int display_resy = (int) one_w32_display_info.resy;
5312 int display_resx = (int) one_w32_display_info.resx;
5313 int bufsz;
5314 struct coding_system coding;
5316 if (!lpxstr) abort ();
5318 if (!lplogfont)
5319 return FALSE;
5321 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5322 fonttype = "raster";
5323 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5324 fonttype = "outline";
5325 else
5326 fonttype = "unknown";
5328 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
5329 &coding);
5330 coding.src_multibyte = 0;
5331 coding.dst_multibyte = 1;
5332 coding.mode |= CODING_MODE_LAST_BLOCK;
5333 /* We explicitely disable composition handling because selection
5334 data should not contain any composition sequence. */
5335 coding.composing = COMPOSITION_DISABLED;
5336 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
5338 fontname = alloca(sizeof(*fontname) * bufsz);
5339 decode_coding (&coding, lplogfont->lfFaceName, fontname,
5340 strlen(lplogfont->lfFaceName), bufsz - 1);
5341 *(fontname + coding.produced) = '\0';
5343 /* Replace dashes with underscores so the dashes are not
5344 misinterpreted. */
5345 fontname_dash = fontname;
5346 while (fontname_dash = strchr (fontname_dash, '-'))
5347 *fontname_dash = '_';
5349 if (lplogfont->lfHeight)
5351 sprintf (height_pixels, "%u", abs (lplogfont->lfHeight));
5352 sprintf (height_dpi, "%u",
5353 abs (lplogfont->lfHeight) * 720 / display_resy);
5355 else
5357 strcpy (height_pixels, "*");
5358 strcpy (height_dpi, "*");
5361 #if 0 /* Never put the width in the xfld. It fails on fonts with
5362 double-width characters. */
5363 if (lplogfont->lfWidth)
5364 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5365 else
5366 #endif
5367 strcpy (width_pixels, "*");
5369 _snprintf (lpxstr, len - 1,
5370 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5371 fonttype, /* foundry */
5372 fontname, /* family */
5373 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5374 lplogfont->lfItalic?'i':'r', /* slant */
5375 /* setwidth name */
5376 /* add style name */
5377 height_pixels, /* pixel size */
5378 height_dpi, /* point size */
5379 display_resx, /* resx */
5380 display_resy, /* resy */
5381 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5382 ? 'p' : 'c', /* spacing */
5383 width_pixels, /* avg width */
5384 specific_charset ? specific_charset
5385 : w32_to_x_charset (lplogfont->lfCharSet)
5386 /* charset registry and encoding */
5389 lpxstr[len - 1] = 0; /* just to be sure */
5390 return (TRUE);
5393 static BOOL
5394 x_to_w32_font (lpxstr, lplogfont)
5395 char * lpxstr;
5396 LOGFONT * lplogfont;
5398 struct coding_system coding;
5400 if (!lplogfont) return (FALSE);
5402 memset (lplogfont, 0, sizeof (*lplogfont));
5404 /* Set default value for each field. */
5405 #if 1
5406 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5407 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5408 lplogfont->lfQuality = DEFAULT_QUALITY;
5409 #else
5410 /* go for maximum quality */
5411 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5412 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5413 lplogfont->lfQuality = PROOF_QUALITY;
5414 #endif
5416 lplogfont->lfCharSet = DEFAULT_CHARSET;
5417 lplogfont->lfWeight = FW_DONTCARE;
5418 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5420 if (!lpxstr)
5421 return FALSE;
5423 /* Provide a simple escape mechanism for specifying Windows font names
5424 * directly -- if font spec does not beginning with '-', assume this
5425 * format:
5426 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5429 if (*lpxstr == '-')
5431 int fields, tem;
5432 char name[50], weight[20], slant, pitch, pixels[10], height[10],
5433 width[10], resy[10], remainder[50];
5434 char * encoding;
5435 int dpi = (int) one_w32_display_info.resy;
5437 fields = sscanf (lpxstr,
5438 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
5439 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
5440 if (fields == EOF)
5441 return (FALSE);
5443 /* In the general case when wildcards cover more than one field,
5444 we don't know which field is which, so don't fill any in.
5445 However, we need to cope with this particular form, which is
5446 generated by font_list_1 (invoked by try_font_list):
5447 "-raster-6x10-*-gb2312*-*"
5448 and make sure to correctly parse the charset field. */
5449 if (fields == 3)
5451 fields = sscanf (lpxstr,
5452 "-%*[^-]-%49[^-]-*-%49s",
5453 name, remainder);
5455 else if (fields < 9)
5457 fields = 0;
5458 remainder[0] = 0;
5461 if (fields > 0 && name[0] != '*')
5463 int bufsize;
5464 unsigned char *buf;
5466 setup_coding_system
5467 (Fcheck_coding_system (Vlocale_coding_system), &coding);
5468 coding.src_multibyte = 1;
5469 coding.dst_multibyte = 0;
5470 /* Need to set COMPOSITION_DISABLED, otherwise Emacs crashes in
5471 encode_coding_iso2022 trying to dereference a null pointer. */
5472 coding.composing = COMPOSITION_DISABLED;
5473 if (coding.type == coding_type_iso2022)
5474 coding.flags |= CODING_FLAG_ISO_SAFE;
5475 bufsize = encoding_buffer_size (&coding, strlen (name));
5476 buf = (unsigned char *) alloca (bufsize);
5477 coding.mode |= CODING_MODE_LAST_BLOCK;
5478 encode_coding (&coding, name, buf, strlen (name), bufsize);
5479 if (coding.produced >= LF_FACESIZE)
5480 coding.produced = LF_FACESIZE - 1;
5481 buf[coding.produced] = 0;
5482 strcpy (lplogfont->lfFaceName, buf);
5484 else
5486 lplogfont->lfFaceName[0] = '\0';
5489 fields--;
5491 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5493 fields--;
5495 lplogfont->lfItalic = (fields > 0 && slant == 'i');
5497 fields--;
5499 if (fields > 0 && pixels[0] != '*')
5500 lplogfont->lfHeight = atoi (pixels);
5502 fields--;
5503 fields--;
5504 if (fields > 0 && resy[0] != '*')
5506 tem = atoi (resy);
5507 if (tem > 0) dpi = tem;
5510 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
5511 lplogfont->lfHeight = atoi (height) * dpi / 720;
5513 if (fields > 0)
5514 lplogfont->lfPitchAndFamily =
5515 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
5517 fields--;
5519 if (fields > 0 && width[0] != '*')
5520 lplogfont->lfWidth = atoi (width) / 10;
5522 fields--;
5524 /* Strip the trailing '-' if present. (it shouldn't be, as it
5525 fails the test against xlfd-tight-regexp in fontset.el). */
5527 int len = strlen (remainder);
5528 if (len > 0 && remainder[len-1] == '-')
5529 remainder[len-1] = 0;
5531 encoding = remainder;
5532 #if 0
5533 if (strncmp (encoding, "*-", 2) == 0)
5534 encoding += 2;
5535 #endif
5536 lplogfont->lfCharSet = x_to_w32_charset (encoding);
5538 else
5540 int fields;
5541 char name[100], height[10], width[10], weight[20];
5543 fields = sscanf (lpxstr,
5544 "%99[^:]:%9[^:]:%9[^:]:%19s",
5545 name, height, width, weight);
5547 if (fields == EOF) return (FALSE);
5549 if (fields > 0)
5551 strncpy (lplogfont->lfFaceName,name, LF_FACESIZE);
5552 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
5554 else
5556 lplogfont->lfFaceName[0] = 0;
5559 fields--;
5561 if (fields > 0)
5562 lplogfont->lfHeight = atoi (height);
5564 fields--;
5566 if (fields > 0)
5567 lplogfont->lfWidth = atoi (width);
5569 fields--;
5571 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5574 /* This makes TrueType fonts work better. */
5575 lplogfont->lfHeight = - abs (lplogfont->lfHeight);
5577 return (TRUE);
5580 /* Strip the pixel height and point height from the given xlfd, and
5581 return the pixel height. If no pixel height is specified, calculate
5582 one from the point height, or if that isn't defined either, return
5583 0 (which usually signifies a scalable font).
5585 static int
5586 xlfd_strip_height (char *fontname)
5588 int pixel_height, field_number;
5589 char *read_from, *write_to;
5591 xassert (fontname);
5593 pixel_height = field_number = 0;
5594 write_to = NULL;
5596 /* Look for height fields. */
5597 for (read_from = fontname; *read_from; read_from++)
5599 if (*read_from == '-')
5601 field_number++;
5602 if (field_number == 7) /* Pixel height. */
5604 read_from++;
5605 write_to = read_from;
5607 /* Find end of field. */
5608 for (;*read_from && *read_from != '-'; read_from++)
5611 /* Split the fontname at end of field. */
5612 if (*read_from)
5614 *read_from = '\0';
5615 read_from++;
5617 pixel_height = atoi (write_to);
5618 /* Blank out field. */
5619 if (read_from > write_to)
5621 *write_to = '-';
5622 write_to++;
5624 /* If the pixel height field is at the end (partial xlfd),
5625 return now. */
5626 else
5627 return pixel_height;
5629 /* If we got a pixel height, the point height can be
5630 ignored. Just blank it out and break now. */
5631 if (pixel_height)
5633 /* Find end of point size field. */
5634 for (; *read_from && *read_from != '-'; read_from++)
5637 if (*read_from)
5638 read_from++;
5640 /* Blank out the point size field. */
5641 if (read_from > write_to)
5643 *write_to = '-';
5644 write_to++;
5646 else
5647 return pixel_height;
5649 break;
5651 /* If the point height is already blank, break now. */
5652 if (*read_from == '-')
5654 read_from++;
5655 break;
5658 else if (field_number == 8)
5660 /* If we didn't get a pixel height, try to get the point
5661 height and convert that. */
5662 int point_size;
5663 char *point_size_start = read_from++;
5665 /* Find end of field. */
5666 for (; *read_from && *read_from != '-'; read_from++)
5669 if (*read_from)
5671 *read_from = '\0';
5672 read_from++;
5675 point_size = atoi (point_size_start);
5677 /* Convert to pixel height. */
5678 pixel_height = point_size
5679 * one_w32_display_info.height_in / 720;
5681 /* Blank out this field and break. */
5682 *write_to = '-';
5683 write_to++;
5684 break;
5689 /* Shift the rest of the font spec into place. */
5690 if (write_to && read_from > write_to)
5692 for (; *read_from; read_from++, write_to++)
5693 *write_to = *read_from;
5694 *write_to = '\0';
5697 return pixel_height;
5700 /* Assume parameter 1 is fully qualified, no wildcards. */
5701 static BOOL
5702 w32_font_match (fontname, pattern)
5703 char * fontname;
5704 char * pattern;
5706 char *ptr;
5707 char *font_name_copy;
5708 char *regex = alloca (strlen (pattern) * 2 + 3);
5710 font_name_copy = alloca (strlen (fontname) + 1);
5711 strcpy (font_name_copy, fontname);
5713 ptr = regex;
5714 *ptr++ = '^';
5716 /* Turn pattern into a regexp and do a regexp match. */
5717 for (; *pattern; pattern++)
5719 if (*pattern == '?')
5720 *ptr++ = '.';
5721 else if (*pattern == '*')
5723 *ptr++ = '.';
5724 *ptr++ = '*';
5726 else
5727 *ptr++ = *pattern;
5729 *ptr = '$';
5730 *(ptr + 1) = '\0';
5732 /* Strip out font heights and compare them seperately, since
5733 rounding error can cause mismatches. This also allows a
5734 comparison between a font that declares only a pixel height and a
5735 pattern that declares the point height.
5738 int font_height, pattern_height;
5740 font_height = xlfd_strip_height (font_name_copy);
5741 pattern_height = xlfd_strip_height (regex);
5743 /* Compare now, and don't bother doing expensive regexp matching
5744 if the heights differ. */
5745 if (font_height && pattern_height && (font_height != pattern_height))
5746 return FALSE;
5749 return (fast_string_match_ignore_case (build_string (regex),
5750 build_string(font_name_copy)) >= 0);
5753 /* Callback functions, and a structure holding info they need, for
5754 listing system fonts on W32. We need one set of functions to do the
5755 job properly, but these don't work on NT 3.51 and earlier, so we
5756 have a second set which don't handle character sets properly to
5757 fall back on.
5759 In both cases, there are two passes made. The first pass gets one
5760 font from each family, the second pass lists all the fonts from
5761 each family. */
5763 typedef struct enumfont_t
5765 HDC hdc;
5766 int numFonts;
5767 LOGFONT logfont;
5768 XFontStruct *size_ref;
5769 Lisp_Object pattern;
5770 Lisp_Object list;
5771 } enumfont_t;
5774 static void
5775 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
5778 static int CALLBACK
5779 enum_font_cb2 (lplf, lptm, FontType, lpef)
5780 ENUMLOGFONT * lplf;
5781 NEWTEXTMETRIC * lptm;
5782 int FontType;
5783 enumfont_t * lpef;
5785 /* Ignore struck out and underlined versions of fonts. */
5786 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
5787 return 1;
5789 /* Only return fonts with names starting with @ if they were
5790 explicitly specified, since Microsoft uses an initial @ to
5791 denote fonts for vertical writing, without providing a more
5792 convenient way of identifying them. */
5793 if (lplf->elfLogFont.lfFaceName[0] == '@'
5794 && lpef->logfont.lfFaceName[0] != '@')
5795 return 1;
5797 /* Check that the character set matches if it was specified */
5798 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
5799 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
5800 return 1;
5802 if (FontType == RASTER_FONTTYPE)
5804 /* DBCS raster fonts have problems displaying, so skip them. */
5805 int charset = lplf->elfLogFont.lfCharSet;
5806 if (charset == SHIFTJIS_CHARSET
5807 || charset == HANGEUL_CHARSET
5808 || charset == CHINESEBIG5_CHARSET
5809 || charset == GB2312_CHARSET
5810 #ifdef JOHAB_CHARSET
5811 || charset == JOHAB_CHARSET
5812 #endif
5814 return 1;
5818 char buf[100];
5819 Lisp_Object width = Qnil;
5820 Lisp_Object charset_list = Qnil;
5821 char *charset = NULL;
5823 /* Truetype fonts do not report their true metrics until loaded */
5824 if (FontType != RASTER_FONTTYPE)
5826 if (!NILP (lpef->pattern))
5828 /* Scalable fonts are as big as you want them to be. */
5829 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
5830 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
5831 width = make_number (lpef->logfont.lfWidth);
5833 else
5835 lplf->elfLogFont.lfHeight = 0;
5836 lplf->elfLogFont.lfWidth = 0;
5840 /* Make sure the height used here is the same as everywhere
5841 else (ie character height, not cell height). */
5842 if (lplf->elfLogFont.lfHeight > 0)
5844 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
5845 if (FontType == RASTER_FONTTYPE)
5846 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
5847 else
5848 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
5851 if (!NILP (lpef->pattern))
5853 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
5855 /* We already checked charsets above, but DEFAULT_CHARSET
5856 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
5857 if (charset
5858 && strncmp (charset, "*-*", 3) != 0
5859 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
5860 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
5861 return 1;
5864 if (charset)
5865 charset_list = Fcons (build_string (charset), Qnil);
5866 else
5867 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
5869 /* Loop through the charsets. */
5870 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
5872 Lisp_Object this_charset = Fcar (charset_list);
5873 charset = SDATA (this_charset);
5875 /* List bold and italic variations if w32-enable-synthesized-fonts
5876 is non-nil and this is a plain font. */
5877 if (w32_enable_synthesized_fonts
5878 && lplf->elfLogFont.lfWeight == FW_NORMAL
5879 && lplf->elfLogFont.lfItalic == FALSE)
5881 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5882 charset, width);
5883 /* bold. */
5884 lplf->elfLogFont.lfWeight = FW_BOLD;
5885 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5886 charset, width);
5887 /* bold italic. */
5888 lplf->elfLogFont.lfItalic = TRUE;
5889 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5890 charset, width);
5891 /* italic. */
5892 lplf->elfLogFont.lfWeight = FW_NORMAL;
5893 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5894 charset, width);
5896 else
5897 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5898 charset, width);
5902 return 1;
5905 static void
5906 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
5907 enumfont_t * lpef;
5908 LOGFONT * logfont;
5909 char * match_charset;
5910 Lisp_Object width;
5912 char buf[100];
5914 if (!w32_to_x_font (logfont, buf, 100, match_charset))
5915 return;
5917 if (NILP (lpef->pattern)
5918 || w32_font_match (buf, SDATA (lpef->pattern)))
5920 /* Check if we already listed this font. This may happen if
5921 w32_enable_synthesized_fonts is non-nil, and there are real
5922 bold and italic versions of the font. */
5923 Lisp_Object font_name = build_string (buf);
5924 if (NILP (Fmember (font_name, lpef->list)))
5926 Lisp_Object entry = Fcons (font_name, width);
5927 lpef->list = Fcons (entry, lpef->list);
5928 lpef->numFonts++;
5934 static int CALLBACK
5935 enum_font_cb1 (lplf, lptm, FontType, lpef)
5936 ENUMLOGFONT * lplf;
5937 NEWTEXTMETRIC * lptm;
5938 int FontType;
5939 enumfont_t * lpef;
5941 return EnumFontFamilies (lpef->hdc,
5942 lplf->elfLogFont.lfFaceName,
5943 (FONTENUMPROC) enum_font_cb2,
5944 (LPARAM) lpef);
5948 static int CALLBACK
5949 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
5950 ENUMLOGFONTEX * lplf;
5951 NEWTEXTMETRICEX * lptm;
5952 int font_type;
5953 enumfont_t * lpef;
5955 /* We are not interested in the extra info we get back from the 'Ex
5956 version - only the fact that we get character set variations
5957 enumerated seperately. */
5958 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
5959 font_type, lpef);
5962 static int CALLBACK
5963 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
5964 ENUMLOGFONTEX * lplf;
5965 NEWTEXTMETRICEX * lptm;
5966 int font_type;
5967 enumfont_t * lpef;
5969 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5970 FARPROC enum_font_families_ex
5971 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
5972 /* We don't really expect EnumFontFamiliesEx to disappear once we
5973 get here, so don't bother handling it gracefully. */
5974 if (enum_font_families_ex == NULL)
5975 error ("gdi32.dll has disappeared!");
5976 return enum_font_families_ex (lpef->hdc,
5977 &lplf->elfLogFont,
5978 (FONTENUMPROC) enum_fontex_cb2,
5979 (LPARAM) lpef, 0);
5982 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
5983 and xterm.c in Emacs 20.3) */
5985 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
5987 char *fontname, *ptnstr;
5988 Lisp_Object list, tem, newlist = Qnil;
5989 int n_fonts = 0;
5991 list = Vw32_bdf_filename_alist;
5992 ptnstr = SDATA (pattern);
5994 for ( ; CONSP (list); list = XCDR (list))
5996 tem = XCAR (list);
5997 if (CONSP (tem))
5998 fontname = SDATA (XCAR (tem));
5999 else if (STRINGP (tem))
6000 fontname = SDATA (tem);
6001 else
6002 continue;
6004 if (w32_font_match (fontname, ptnstr))
6006 newlist = Fcons (XCAR (tem), newlist);
6007 n_fonts++;
6008 if (max_names >= 0 && n_fonts >= max_names)
6009 break;
6013 return newlist;
6017 /* Return a list of names of available fonts matching PATTERN on frame
6018 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6019 to be listed. Frame F NULL means we have not yet created any
6020 frame, which means we can't get proper size info, as we don't have
6021 a device context to use for GetTextMetrics.
6022 MAXNAMES sets a limit on how many fonts to match. If MAXNAMES is
6023 negative, then all matching fonts are returned. */
6025 Lisp_Object
6026 w32_list_fonts (f, pattern, size, maxnames)
6027 struct frame *f;
6028 Lisp_Object pattern;
6029 int size;
6030 int maxnames;
6032 Lisp_Object patterns, key = Qnil, tem, tpat;
6033 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6034 struct w32_display_info *dpyinfo = &one_w32_display_info;
6035 int n_fonts = 0;
6037 patterns = Fassoc (pattern, Valternate_fontname_alist);
6038 if (NILP (patterns))
6039 patterns = Fcons (pattern, Qnil);
6041 for (; CONSP (patterns); patterns = XCDR (patterns))
6043 enumfont_t ef;
6044 int codepage;
6046 tpat = XCAR (patterns);
6048 if (!STRINGP (tpat))
6049 continue;
6051 /* Avoid expensive EnumFontFamilies functions if we are not
6052 going to be able to output one of these anyway. */
6053 codepage = w32_codepage_for_font (SDATA (tpat));
6054 if (codepage != CP_8BIT && codepage != CP_UNICODE
6055 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6056 && !IsValidCodePage(codepage))
6057 continue;
6059 /* See if we cached the result for this particular query.
6060 The cache is an alist of the form:
6061 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6063 if (tem = XCDR (dpyinfo->name_list_element),
6064 !NILP (list = Fassoc (tpat, tem)))
6066 list = Fcdr_safe (list);
6067 /* We have a cached list. Don't have to get the list again. */
6068 goto label_cached;
6071 BLOCK_INPUT;
6072 /* At first, put PATTERN in the cache. */
6073 ef.pattern = tpat;
6074 ef.list = Qnil;
6075 ef.numFonts = 0;
6077 /* Use EnumFontFamiliesEx where it is available, as it knows
6078 about character sets. Fall back to EnumFontFamilies for
6079 older versions of NT that don't support the 'Ex function. */
6080 x_to_w32_font (SDATA (tpat), &ef.logfont);
6082 LOGFONT font_match_pattern;
6083 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6084 FARPROC enum_font_families_ex
6085 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6087 /* We do our own pattern matching so we can handle wildcards. */
6088 font_match_pattern.lfFaceName[0] = 0;
6089 font_match_pattern.lfPitchAndFamily = 0;
6090 /* We can use the charset, because if it is a wildcard it will
6091 be DEFAULT_CHARSET anyway. */
6092 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6094 ef.hdc = GetDC (dpyinfo->root_window);
6096 if (enum_font_families_ex)
6097 enum_font_families_ex (ef.hdc,
6098 &font_match_pattern,
6099 (FONTENUMPROC) enum_fontex_cb1,
6100 (LPARAM) &ef, 0);
6101 else
6102 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6103 (LPARAM)&ef);
6105 ReleaseDC (dpyinfo->root_window, ef.hdc);
6108 UNBLOCK_INPUT;
6109 list = ef.list;
6111 /* Make a list of the fonts we got back.
6112 Store that in the font cache for the display. */
6113 XSETCDR (dpyinfo->name_list_element,
6114 Fcons (Fcons (tpat, list),
6115 XCDR (dpyinfo->name_list_element)));
6117 label_cached:
6118 if (NILP (list)) continue; /* Try the remaining alternatives. */
6120 newlist = second_best = Qnil;
6122 /* Make a list of the fonts that have the right width. */
6123 for (; CONSP (list); list = XCDR (list))
6125 int found_size;
6126 tem = XCAR (list);
6128 if (!CONSP (tem))
6129 continue;
6130 if (NILP (XCAR (tem)))
6131 continue;
6132 if (!size)
6134 newlist = Fcons (XCAR (tem), newlist);
6135 n_fonts++;
6136 if (maxnames >= 0 && n_fonts >= maxnames)
6137 break;
6138 else
6139 continue;
6141 if (!INTEGERP (XCDR (tem)))
6143 /* Since we don't yet know the size of the font, we must
6144 load it and try GetTextMetrics. */
6145 W32FontStruct thisinfo;
6146 LOGFONT lf;
6147 HDC hdc;
6148 HANDLE oldobj;
6150 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
6151 continue;
6153 BLOCK_INPUT;
6154 thisinfo.bdf = NULL;
6155 thisinfo.hfont = CreateFontIndirect (&lf);
6156 if (thisinfo.hfont == NULL)
6157 continue;
6159 hdc = GetDC (dpyinfo->root_window);
6160 oldobj = SelectObject (hdc, thisinfo.hfont);
6161 if (GetTextMetrics (hdc, &thisinfo.tm))
6162 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
6163 else
6164 XSETCDR (tem, make_number (0));
6165 SelectObject (hdc, oldobj);
6166 ReleaseDC (dpyinfo->root_window, hdc);
6167 DeleteObject(thisinfo.hfont);
6168 UNBLOCK_INPUT;
6170 found_size = XINT (XCDR (tem));
6171 if (found_size == size)
6173 newlist = Fcons (XCAR (tem), newlist);
6174 n_fonts++;
6175 if (maxnames >= 0 && n_fonts >= maxnames)
6176 break;
6178 /* keep track of the closest matching size in case
6179 no exact match is found. */
6180 else if (found_size > 0)
6182 if (NILP (second_best))
6183 second_best = tem;
6185 else if (found_size < size)
6187 if (XINT (XCDR (second_best)) > size
6188 || XINT (XCDR (second_best)) < found_size)
6189 second_best = tem;
6191 else
6193 if (XINT (XCDR (second_best)) > size
6194 && XINT (XCDR (second_best)) >
6195 found_size)
6196 second_best = tem;
6201 if (!NILP (newlist))
6202 break;
6203 else if (!NILP (second_best))
6205 newlist = Fcons (XCAR (second_best), Qnil);
6206 break;
6210 /* Include any bdf fonts. */
6211 if (n_fonts < maxnames || maxnames < 0)
6213 Lisp_Object combined[2];
6214 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6215 combined[1] = newlist;
6216 newlist = Fnconc(2, combined);
6219 return newlist;
6223 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6224 struct font_info *
6225 w32_get_font_info (f, font_idx)
6226 FRAME_PTR f;
6227 int font_idx;
6229 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6233 struct font_info*
6234 w32_query_font (struct frame *f, char *fontname)
6236 int i;
6237 struct font_info *pfi;
6239 pfi = FRAME_W32_FONT_TABLE (f);
6241 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6243 if (stricmp(pfi->name, fontname) == 0) return pfi;
6246 return NULL;
6249 /* Find a CCL program for a font specified by FONTP, and set the member
6250 `encoder' of the structure. */
6252 void
6253 w32_find_ccl_program (fontp)
6254 struct font_info *fontp;
6256 Lisp_Object list, elt;
6258 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6260 elt = XCAR (list);
6261 if (CONSP (elt)
6262 && STRINGP (XCAR (elt))
6263 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6264 >= 0))
6265 break;
6267 if (! NILP (list))
6269 struct ccl_program *ccl
6270 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6272 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6273 xfree (ccl);
6274 else
6275 fontp->font_encoder = ccl;
6279 /* directory-files from dired.c. */
6280 Lisp_Object Fdirectory_files P_((Lisp_Object, Lisp_Object, Lisp_Object, Lisp_Object));
6283 /* Find BDF files in a specified directory. (use GCPRO when calling,
6284 as this calls lisp to get a directory listing). */
6285 static Lisp_Object
6286 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
6288 Lisp_Object filelist, list = Qnil;
6289 char fontname[100];
6291 if (!STRINGP(directory))
6292 return Qnil;
6294 filelist = Fdirectory_files (directory, Qt,
6295 build_string (".*\\.[bB][dD][fF]"), Qt);
6297 for ( ; CONSP(filelist); filelist = XCDR (filelist))
6299 Lisp_Object filename = XCAR (filelist);
6300 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
6301 store_in_alist (&list, build_string (fontname), filename);
6303 return list;
6306 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6307 1, 1, 0,
6308 doc: /* Return a list of BDF fonts in DIRECTORY.
6309 The list is suitable for appending to `w32-bdf-filename-alist'.
6310 Fonts which do not contain an xlfd description will not be included
6311 in the list. DIRECTORY may be a list of directories. */)
6312 (directory)
6313 Lisp_Object directory;
6315 Lisp_Object list = Qnil;
6316 struct gcpro gcpro1, gcpro2;
6318 if (!CONSP (directory))
6319 return w32_find_bdf_fonts_in_dir (directory);
6321 for ( ; CONSP (directory); directory = XCDR (directory))
6323 Lisp_Object pair[2];
6324 pair[0] = list;
6325 pair[1] = Qnil;
6326 GCPRO2 (directory, list);
6327 pair[1] = w32_find_bdf_fonts_in_dir( XCAR (directory) );
6328 list = Fnconc( 2, pair );
6329 UNGCPRO;
6331 return list;
6335 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6336 doc: /* Internal function called by `color-defined-p', which see. */)
6337 (color, frame)
6338 Lisp_Object color, frame;
6340 XColor foo;
6341 FRAME_PTR f = check_x_frame (frame);
6343 CHECK_STRING (color);
6345 if (w32_defined_color (f, SDATA (color), &foo, 0))
6346 return Qt;
6347 else
6348 return Qnil;
6351 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6352 doc: /* Internal function called by `color-values', which see. */)
6353 (color, frame)
6354 Lisp_Object color, frame;
6356 XColor foo;
6357 FRAME_PTR f = check_x_frame (frame);
6359 CHECK_STRING (color);
6361 if (w32_defined_color (f, SDATA (color), &foo, 0))
6362 return list3 (make_number ((GetRValue (foo.pixel) << 8)
6363 | GetRValue (foo.pixel)),
6364 make_number ((GetGValue (foo.pixel) << 8)
6365 | GetGValue (foo.pixel)),
6366 make_number ((GetBValue (foo.pixel) << 8)
6367 | GetBValue (foo.pixel)));
6368 else
6369 return Qnil;
6372 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6373 doc: /* Internal function called by `display-color-p', which see. */)
6374 (display)
6375 Lisp_Object display;
6377 struct w32_display_info *dpyinfo = check_x_display_info (display);
6379 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6380 return Qnil;
6382 return Qt;
6385 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6386 Sx_display_grayscale_p, 0, 1, 0,
6387 doc: /* Return t if DISPLAY supports shades of gray.
6388 Note that color displays do support shades of gray.
6389 The optional argument DISPLAY specifies which display to ask about.
6390 DISPLAY should be either a frame or a display name (a string).
6391 If omitted or nil, that stands for the selected frame's display. */)
6392 (display)
6393 Lisp_Object display;
6395 struct w32_display_info *dpyinfo = check_x_display_info (display);
6397 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6398 return Qnil;
6400 return Qt;
6403 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6404 Sx_display_pixel_width, 0, 1, 0,
6405 doc: /* Returns the width in pixels of DISPLAY.
6406 The optional argument DISPLAY specifies which display to ask about.
6407 DISPLAY should be either a frame or a display name (a string).
6408 If omitted or nil, that stands for the selected frame's display. */)
6409 (display)
6410 Lisp_Object display;
6412 struct w32_display_info *dpyinfo = check_x_display_info (display);
6414 return make_number (dpyinfo->width);
6417 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6418 Sx_display_pixel_height, 0, 1, 0,
6419 doc: /* Returns the height in pixels of DISPLAY.
6420 The optional argument DISPLAY specifies which display to ask about.
6421 DISPLAY should be either a frame or a display name (a string).
6422 If omitted or nil, that stands for the selected frame's display. */)
6423 (display)
6424 Lisp_Object display;
6426 struct w32_display_info *dpyinfo = check_x_display_info (display);
6428 return make_number (dpyinfo->height);
6431 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6432 0, 1, 0,
6433 doc: /* Returns the number of bitplanes of DISPLAY.
6434 The optional argument DISPLAY specifies which display to ask about.
6435 DISPLAY should be either a frame or a display name (a string).
6436 If omitted or nil, that stands for the selected frame's display. */)
6437 (display)
6438 Lisp_Object display;
6440 struct w32_display_info *dpyinfo = check_x_display_info (display);
6442 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6445 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6446 0, 1, 0,
6447 doc: /* Returns the number of color cells of DISPLAY.
6448 The optional argument DISPLAY specifies which display to ask about.
6449 DISPLAY should be either a frame or a display name (a string).
6450 If omitted or nil, that stands for the selected frame's display. */)
6451 (display)
6452 Lisp_Object display;
6454 struct w32_display_info *dpyinfo = check_x_display_info (display);
6455 HDC hdc;
6456 int cap;
6458 hdc = GetDC (dpyinfo->root_window);
6459 if (dpyinfo->has_palette)
6460 cap = GetDeviceCaps (hdc, SIZEPALETTE);
6461 else
6462 cap = GetDeviceCaps (hdc, NUMCOLORS);
6464 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
6465 and because probably is more meaningful on Windows anyway */
6466 if (cap < 0)
6467 cap = 1 << min(dpyinfo->n_planes * dpyinfo->n_cbits, 24);
6469 ReleaseDC (dpyinfo->root_window, hdc);
6471 return make_number (cap);
6474 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6475 Sx_server_max_request_size,
6476 0, 1, 0,
6477 doc: /* Returns the maximum request size of the server of DISPLAY.
6478 The optional argument DISPLAY specifies which display to ask about.
6479 DISPLAY should be either a frame or a display name (a string).
6480 If omitted or nil, that stands for the selected frame's display. */)
6481 (display)
6482 Lisp_Object display;
6484 struct w32_display_info *dpyinfo = check_x_display_info (display);
6486 return make_number (1);
6489 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6490 doc: /* Returns the "vendor ID" string of the W32 system (Microsoft).
6491 The optional argument DISPLAY specifies which display to ask about.
6492 DISPLAY should be either a frame or a display name (a string).
6493 If omitted or nil, that stands for the selected frame's display. */)
6494 (display)
6495 Lisp_Object display;
6497 return build_string ("Microsoft Corp.");
6500 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6501 doc: /* Returns the version numbers of the server of DISPLAY.
6502 The value is a list of three integers: the major and minor
6503 version numbers of the X Protocol in use, and the distributor-specific release
6504 number. See also the function `x-server-vendor'.
6506 The optional argument DISPLAY specifies which display to ask about.
6507 DISPLAY should be either a frame or a display name (a string).
6508 If omitted or nil, that stands for the selected frame's display. */)
6509 (display)
6510 Lisp_Object display;
6512 return Fcons (make_number (w32_major_version),
6513 Fcons (make_number (w32_minor_version),
6514 Fcons (make_number (w32_build_number), Qnil)));
6517 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6518 doc: /* Returns the number of screens on the server of DISPLAY.
6519 The optional argument DISPLAY specifies which display to ask about.
6520 DISPLAY should be either a frame or a display name (a string).
6521 If omitted or nil, that stands for the selected frame's display. */)
6522 (display)
6523 Lisp_Object display;
6525 return make_number (1);
6528 DEFUN ("x-display-mm-height", Fx_display_mm_height,
6529 Sx_display_mm_height, 0, 1, 0,
6530 doc: /* Returns the height in millimeters of DISPLAY.
6531 The optional argument DISPLAY specifies which display to ask about.
6532 DISPLAY should be either a frame or a display name (a string).
6533 If omitted or nil, that stands for the selected frame's display. */)
6534 (display)
6535 Lisp_Object display;
6537 struct w32_display_info *dpyinfo = check_x_display_info (display);
6538 HDC hdc;
6539 int cap;
6541 hdc = GetDC (dpyinfo->root_window);
6543 cap = GetDeviceCaps (hdc, VERTSIZE);
6545 ReleaseDC (dpyinfo->root_window, hdc);
6547 return make_number (cap);
6550 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6551 doc: /* Returns the width in millimeters of DISPLAY.
6552 The optional argument DISPLAY specifies which display to ask about.
6553 DISPLAY should be either a frame or a display name (a string).
6554 If omitted or nil, that stands for the selected frame's display. */)
6555 (display)
6556 Lisp_Object display;
6558 struct w32_display_info *dpyinfo = check_x_display_info (display);
6560 HDC hdc;
6561 int cap;
6563 hdc = GetDC (dpyinfo->root_window);
6565 cap = GetDeviceCaps (hdc, HORZSIZE);
6567 ReleaseDC (dpyinfo->root_window, hdc);
6569 return make_number (cap);
6572 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6573 Sx_display_backing_store, 0, 1, 0,
6574 doc: /* Returns an indication of whether DISPLAY does backing store.
6575 The value may be `always', `when-mapped', or `not-useful'.
6576 The optional argument DISPLAY specifies which display to ask about.
6577 DISPLAY should be either a frame or a display name (a string).
6578 If omitted or nil, that stands for the selected frame's display. */)
6579 (display)
6580 Lisp_Object display;
6582 return intern ("not-useful");
6585 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6586 Sx_display_visual_class, 0, 1, 0,
6587 doc: /* Returns the visual class of DISPLAY.
6588 The value is one of the symbols `static-gray', `gray-scale',
6589 `static-color', `pseudo-color', `true-color', or `direct-color'.
6591 The optional argument DISPLAY specifies which display to ask about.
6592 DISPLAY should be either a frame or a display name (a string).
6593 If omitted or nil, that stands for the selected frame's display. */)
6594 (display)
6595 Lisp_Object display;
6597 struct w32_display_info *dpyinfo = check_x_display_info (display);
6598 Lisp_Object result = Qnil;
6600 if (dpyinfo->has_palette)
6601 result = intern ("pseudo-color");
6602 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6603 result = intern ("static-grey");
6604 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6605 result = intern ("static-color");
6606 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6607 result = intern ("true-color");
6609 return result;
6612 DEFUN ("x-display-save-under", Fx_display_save_under,
6613 Sx_display_save_under, 0, 1, 0,
6614 doc: /* Returns t if DISPLAY supports the save-under feature.
6615 The optional argument DISPLAY specifies which display to ask about.
6616 DISPLAY should be either a frame or a display name (a string).
6617 If omitted or nil, that stands for the selected frame's display. */)
6618 (display)
6619 Lisp_Object display;
6621 return Qnil;
6625 x_pixel_width (f)
6626 register struct frame *f;
6628 return FRAME_PIXEL_WIDTH (f);
6632 x_pixel_height (f)
6633 register struct frame *f;
6635 return FRAME_PIXEL_HEIGHT (f);
6639 x_char_width (f)
6640 register struct frame *f;
6642 return FRAME_COLUMN_WIDTH (f);
6646 x_char_height (f)
6647 register struct frame *f;
6649 return FRAME_LINE_HEIGHT (f);
6653 x_screen_planes (f)
6654 register struct frame *f;
6656 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
6659 /* Return the display structure for the display named NAME.
6660 Open a new connection if necessary. */
6662 struct w32_display_info *
6663 x_display_info_for_name (name)
6664 Lisp_Object name;
6666 Lisp_Object names;
6667 struct w32_display_info *dpyinfo;
6669 CHECK_STRING (name);
6671 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
6672 dpyinfo;
6673 dpyinfo = dpyinfo->next, names = XCDR (names))
6675 Lisp_Object tem;
6676 tem = Fstring_equal (XCAR (XCAR (names)), name);
6677 if (!NILP (tem))
6678 return dpyinfo;
6681 /* Use this general default value to start with. */
6682 Vx_resource_name = Vinvocation_name;
6684 validate_x_resource_name ();
6686 dpyinfo = w32_term_init (name, (unsigned char *)0,
6687 (char *) SDATA (Vx_resource_name));
6689 if (dpyinfo == 0)
6690 error ("Cannot connect to server %s", SDATA (name));
6692 w32_in_use = 1;
6693 XSETFASTINT (Vwindow_system_version, 3);
6695 return dpyinfo;
6698 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6699 1, 3, 0, doc: /* Open a connection to a server.
6700 DISPLAY is the name of the display to connect to.
6701 Optional second arg XRM-STRING is a string of resources in xrdb format.
6702 If the optional third arg MUST-SUCCEED is non-nil,
6703 terminate Emacs if we can't open the connection. */)
6704 (display, xrm_string, must_succeed)
6705 Lisp_Object display, xrm_string, must_succeed;
6707 unsigned char *xrm_option;
6708 struct w32_display_info *dpyinfo;
6710 /* If initialization has already been done, return now to avoid
6711 overwriting critical parts of one_w32_display_info. */
6712 if (w32_in_use)
6713 return Qnil;
6715 CHECK_STRING (display);
6716 if (! NILP (xrm_string))
6717 CHECK_STRING (xrm_string);
6719 if (! EQ (Vwindow_system, intern ("w32")))
6720 error ("Not using Microsoft Windows");
6722 /* Allow color mapping to be defined externally; first look in user's
6723 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6725 Lisp_Object color_file;
6726 struct gcpro gcpro1;
6728 color_file = build_string("~/rgb.txt");
6730 GCPRO1 (color_file);
6732 if (NILP (Ffile_readable_p (color_file)))
6733 color_file =
6734 Fexpand_file_name (build_string ("rgb.txt"),
6735 Fsymbol_value (intern ("data-directory")));
6737 Vw32_color_map = Fw32_load_color_file (color_file);
6739 UNGCPRO;
6741 if (NILP (Vw32_color_map))
6742 Vw32_color_map = Fw32_default_color_map ();
6744 /* Merge in system logical colors. */
6745 add_system_logical_colors_to_map (&Vw32_color_map);
6747 if (! NILP (xrm_string))
6748 xrm_option = (unsigned char *) SDATA (xrm_string);
6749 else
6750 xrm_option = (unsigned char *) 0;
6752 /* Use this general default value to start with. */
6753 /* First remove .exe suffix from invocation-name - it looks ugly. */
6755 char basename[ MAX_PATH ], *str;
6757 strcpy (basename, SDATA (Vinvocation_name));
6758 str = strrchr (basename, '.');
6759 if (str) *str = 0;
6760 Vinvocation_name = build_string (basename);
6762 Vx_resource_name = Vinvocation_name;
6764 validate_x_resource_name ();
6766 /* This is what opens the connection and sets x_current_display.
6767 This also initializes many symbols, such as those used for input. */
6768 dpyinfo = w32_term_init (display, xrm_option,
6769 (char *) SDATA (Vx_resource_name));
6771 if (dpyinfo == 0)
6773 if (!NILP (must_succeed))
6774 fatal ("Cannot connect to server %s.\n",
6775 SDATA (display));
6776 else
6777 error ("Cannot connect to server %s", SDATA (display));
6780 w32_in_use = 1;
6782 XSETFASTINT (Vwindow_system_version, 3);
6783 return Qnil;
6786 DEFUN ("x-close-connection", Fx_close_connection,
6787 Sx_close_connection, 1, 1, 0,
6788 doc: /* Close the connection to DISPLAY's server.
6789 For DISPLAY, specify either a frame or a display name (a string).
6790 If DISPLAY is nil, that stands for the selected frame's display. */)
6791 (display)
6792 Lisp_Object display;
6794 struct w32_display_info *dpyinfo = check_x_display_info (display);
6795 int i;
6797 if (dpyinfo->reference_count > 0)
6798 error ("Display still has frames on it");
6800 BLOCK_INPUT;
6801 /* Free the fonts in the font table. */
6802 for (i = 0; i < dpyinfo->n_fonts; i++)
6803 if (dpyinfo->font_table[i].name)
6805 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
6806 xfree (dpyinfo->font_table[i].full_name);
6807 xfree (dpyinfo->font_table[i].name);
6808 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
6810 x_destroy_all_bitmaps (dpyinfo);
6812 x_delete_display (dpyinfo);
6813 UNBLOCK_INPUT;
6815 return Qnil;
6818 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6819 doc: /* Return the list of display names that Emacs has connections to. */)
6822 Lisp_Object tail, result;
6824 result = Qnil;
6825 for (tail = w32_display_name_list; ! NILP (tail); tail = XCDR (tail))
6826 result = Fcons (XCAR (XCAR (tail)), result);
6828 return result;
6831 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6832 doc: /* This is a noop on W32 systems. */)
6833 (on, display)
6834 Lisp_Object display, on;
6836 return Qnil;
6841 /***********************************************************************
6842 Window properties
6843 ***********************************************************************/
6845 DEFUN ("x-change-window-property", Fx_change_window_property,
6846 Sx_change_window_property, 2, 6, 0,
6847 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6848 VALUE may be a string or a list of conses, numbers and/or strings.
6849 If an element in the list is a string, it is converted to
6850 an Atom and the value of the Atom is used. If an element is a cons,
6851 it is converted to a 32 bit number where the car is the 16 top bits and the
6852 cdr is the lower 16 bits.
6853 FRAME nil or omitted means use the selected frame.
6854 If TYPE is given and non-nil, it is the name of the type of VALUE.
6855 If TYPE is not given or nil, the type is STRING.
6856 FORMAT gives the size in bits of each element if VALUE is a list.
6857 It must be one of 8, 16 or 32.
6858 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6859 If OUTER_P is non-nil, the property is changed for the outer X window of
6860 FRAME. Default is to change on the edit X window.
6862 Value is VALUE. */)
6863 (prop, value, frame, type, format, outer_p)
6864 Lisp_Object prop, value, frame, type, format, outer_p;
6866 #if 0 /* TODO : port window properties to W32 */
6867 struct frame *f = check_x_frame (frame);
6868 Atom prop_atom;
6870 CHECK_STRING (prop);
6871 CHECK_STRING (value);
6873 BLOCK_INPUT;
6874 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6875 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6876 prop_atom, XA_STRING, 8, PropModeReplace,
6877 SDATA (value), SCHARS (value));
6879 /* Make sure the property is set when we return. */
6880 XFlush (FRAME_W32_DISPLAY (f));
6881 UNBLOCK_INPUT;
6883 #endif /* TODO */
6885 return value;
6889 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6890 Sx_delete_window_property, 1, 2, 0,
6891 doc: /* Remove window property PROP from X window of FRAME.
6892 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6893 (prop, frame)
6894 Lisp_Object prop, frame;
6896 #if 0 /* TODO : port window properties to W32 */
6898 struct frame *f = check_x_frame (frame);
6899 Atom prop_atom;
6901 CHECK_STRING (prop);
6902 BLOCK_INPUT;
6903 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6904 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6906 /* Make sure the property is removed when we return. */
6907 XFlush (FRAME_W32_DISPLAY (f));
6908 UNBLOCK_INPUT;
6909 #endif /* TODO */
6911 return prop;
6915 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6916 1, 2, 0,
6917 doc: /* Value is the value of window property PROP on FRAME.
6918 If FRAME is nil or omitted, use the selected frame. Value is nil
6919 if FRAME hasn't a property with name PROP or if PROP has no string
6920 value. */)
6921 (prop, frame)
6922 Lisp_Object prop, frame;
6924 #if 0 /* TODO : port window properties to W32 */
6926 struct frame *f = check_x_frame (frame);
6927 Atom prop_atom;
6928 int rc;
6929 Lisp_Object prop_value = Qnil;
6930 char *tmp_data = NULL;
6931 Atom actual_type;
6932 int actual_format;
6933 unsigned long actual_size, bytes_remaining;
6935 CHECK_STRING (prop);
6936 BLOCK_INPUT;
6937 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6938 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6939 prop_atom, 0, 0, False, XA_STRING,
6940 &actual_type, &actual_format, &actual_size,
6941 &bytes_remaining, (unsigned char **) &tmp_data);
6942 if (rc == Success)
6944 int size = bytes_remaining;
6946 XFree (tmp_data);
6947 tmp_data = NULL;
6949 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6950 prop_atom, 0, bytes_remaining,
6951 False, XA_STRING,
6952 &actual_type, &actual_format,
6953 &actual_size, &bytes_remaining,
6954 (unsigned char **) &tmp_data);
6955 if (rc == Success)
6956 prop_value = make_string (tmp_data, size);
6958 XFree (tmp_data);
6961 UNBLOCK_INPUT;
6963 return prop_value;
6965 #endif /* TODO */
6966 return Qnil;
6971 /***********************************************************************
6972 Busy cursor
6973 ***********************************************************************/
6975 /* If non-null, an asynchronous timer that, when it expires, displays
6976 an hourglass cursor on all frames. */
6978 static struct atimer *hourglass_atimer;
6980 /* Non-zero means an hourglass cursor is currently shown. */
6982 static int hourglass_shown_p;
6984 /* Number of seconds to wait before displaying an hourglass cursor. */
6986 static Lisp_Object Vhourglass_delay;
6988 /* Default number of seconds to wait before displaying an hourglass
6989 cursor. */
6991 #define DEFAULT_HOURGLASS_DELAY 1
6993 /* Function prototypes. */
6995 static void show_hourglass P_ ((struct atimer *));
6996 static void hide_hourglass P_ ((void));
6999 /* Cancel a currently active hourglass timer, and start a new one. */
7001 void
7002 start_hourglass ()
7004 #if 0 /* TODO: cursor shape changes. */
7005 EMACS_TIME delay;
7006 int secs, usecs = 0;
7008 cancel_hourglass ();
7010 if (INTEGERP (Vhourglass_delay)
7011 && XINT (Vhourglass_delay) > 0)
7012 secs = XFASTINT (Vhourglass_delay);
7013 else if (FLOATP (Vhourglass_delay)
7014 && XFLOAT_DATA (Vhourglass_delay) > 0)
7016 Lisp_Object tem;
7017 tem = Ftruncate (Vhourglass_delay, Qnil);
7018 secs = XFASTINT (tem);
7019 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
7021 else
7022 secs = DEFAULT_HOURGLASS_DELAY;
7024 EMACS_SET_SECS_USECS (delay, secs, usecs);
7025 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
7026 show_hourglass, NULL);
7027 #endif
7031 /* Cancel the hourglass cursor timer if active, hide an hourglass
7032 cursor if shown. */
7034 void
7035 cancel_hourglass ()
7037 if (hourglass_atimer)
7039 cancel_atimer (hourglass_atimer);
7040 hourglass_atimer = NULL;
7043 if (hourglass_shown_p)
7044 hide_hourglass ();
7048 /* Timer function of hourglass_atimer. TIMER is equal to
7049 hourglass_atimer.
7051 Display an hourglass cursor on all frames by mapping the frames'
7052 hourglass_window. Set the hourglass_p flag in the frames'
7053 output_data.x structure to indicate that an hourglass cursor is
7054 shown on the frames. */
7056 static void
7057 show_hourglass (timer)
7058 struct atimer *timer;
7060 #if 0 /* TODO: cursor shape changes. */
7061 /* The timer implementation will cancel this timer automatically
7062 after this function has run. Set hourglass_atimer to null
7063 so that we know the timer doesn't have to be canceled. */
7064 hourglass_atimer = NULL;
7066 if (!hourglass_shown_p)
7068 Lisp_Object rest, frame;
7070 BLOCK_INPUT;
7072 FOR_EACH_FRAME (rest, frame)
7073 if (FRAME_W32_P (XFRAME (frame)))
7075 struct frame *f = XFRAME (frame);
7077 f->output_data.w32->hourglass_p = 1;
7079 if (!f->output_data.w32->hourglass_window)
7081 unsigned long mask = CWCursor;
7082 XSetWindowAttributes attrs;
7084 attrs.cursor = f->output_data.w32->hourglass_cursor;
7086 f->output_data.w32->hourglass_window
7087 = XCreateWindow (FRAME_X_DISPLAY (f),
7088 FRAME_OUTER_WINDOW (f),
7089 0, 0, 32000, 32000, 0, 0,
7090 InputOnly,
7091 CopyFromParent,
7092 mask, &attrs);
7095 XMapRaised (FRAME_X_DISPLAY (f),
7096 f->output_data.w32->hourglass_window);
7097 XFlush (FRAME_X_DISPLAY (f));
7100 hourglass_shown_p = 1;
7101 UNBLOCK_INPUT;
7103 #endif
7107 /* Hide the hourglass cursor on all frames, if it is currently shown. */
7109 static void
7110 hide_hourglass ()
7112 #if 0 /* TODO: cursor shape changes. */
7113 if (hourglass_shown_p)
7115 Lisp_Object rest, frame;
7117 BLOCK_INPUT;
7118 FOR_EACH_FRAME (rest, frame)
7120 struct frame *f = XFRAME (frame);
7122 if (FRAME_W32_P (f)
7123 /* Watch out for newly created frames. */
7124 && f->output_data.x->hourglass_window)
7126 XUnmapWindow (FRAME_X_DISPLAY (f),
7127 f->output_data.x->hourglass_window);
7128 /* Sync here because XTread_socket looks at the
7129 hourglass_p flag that is reset to zero below. */
7130 XSync (FRAME_X_DISPLAY (f), False);
7131 f->output_data.x->hourglass_p = 0;
7135 hourglass_shown_p = 0;
7136 UNBLOCK_INPUT;
7138 #endif
7143 /***********************************************************************
7144 Tool tips
7145 ***********************************************************************/
7147 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
7148 Lisp_Object, Lisp_Object));
7149 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
7150 Lisp_Object, int, int, int *, int *));
7152 /* The frame of a currently visible tooltip. */
7154 Lisp_Object tip_frame;
7156 /* If non-nil, a timer started that hides the last tooltip when it
7157 fires. */
7159 Lisp_Object tip_timer;
7160 Window tip_window;
7162 /* If non-nil, a vector of 3 elements containing the last args
7163 with which x-show-tip was called. See there. */
7165 Lisp_Object last_show_tip_args;
7167 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
7169 Lisp_Object Vx_max_tooltip_size;
7172 static Lisp_Object
7173 unwind_create_tip_frame (frame)
7174 Lisp_Object frame;
7176 Lisp_Object deleted;
7178 deleted = unwind_create_frame (frame);
7179 if (EQ (deleted, Qt))
7181 tip_window = NULL;
7182 tip_frame = Qnil;
7185 return deleted;
7189 /* Create a frame for a tooltip on the display described by DPYINFO.
7190 PARMS is a list of frame parameters. TEXT is the string to
7191 display in the tip frame. Value is the frame.
7193 Note that functions called here, esp. x_default_parameter can
7194 signal errors, for instance when a specified color name is
7195 undefined. We have to make sure that we're in a consistent state
7196 when this happens. */
7198 static Lisp_Object
7199 x_create_tip_frame (dpyinfo, parms, text)
7200 struct w32_display_info *dpyinfo;
7201 Lisp_Object parms, text;
7203 struct frame *f;
7204 Lisp_Object frame, tem;
7205 Lisp_Object name;
7206 long window_prompting = 0;
7207 int width, height;
7208 int count = SPECPDL_INDEX ();
7209 struct gcpro gcpro1, gcpro2, gcpro3;
7210 struct kboard *kb;
7211 int face_change_count_before = face_change_count;
7212 Lisp_Object buffer;
7213 struct buffer *old_buffer;
7215 check_w32 ();
7217 /* Use this general default value to start with until we know if
7218 this frame has a specified name. */
7219 Vx_resource_name = Vinvocation_name;
7221 #ifdef MULTI_KBOARD
7222 kb = dpyinfo->kboard;
7223 #else
7224 kb = &the_only_kboard;
7225 #endif
7227 /* Get the name of the frame to use for resource lookup. */
7228 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
7229 if (!STRINGP (name)
7230 && !EQ (name, Qunbound)
7231 && !NILP (name))
7232 error ("Invalid frame name--not a string or nil");
7233 Vx_resource_name = name;
7235 frame = Qnil;
7236 GCPRO3 (parms, name, frame);
7237 /* Make a frame without minibuffer nor mode-line. */
7238 f = make_frame (0);
7239 f->wants_modeline = 0;
7240 XSETFRAME (frame, f);
7242 buffer = Fget_buffer_create (build_string (" *tip*"));
7243 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer, Qnil);
7244 old_buffer = current_buffer;
7245 set_buffer_internal_1 (XBUFFER (buffer));
7246 current_buffer->truncate_lines = Qnil;
7247 specbind (Qinhibit_read_only, Qt);
7248 specbind (Qinhibit_modification_hooks, Qt);
7249 Ferase_buffer ();
7250 Finsert (1, &text);
7251 set_buffer_internal_1 (old_buffer);
7253 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
7254 record_unwind_protect (unwind_create_tip_frame, frame);
7256 /* By setting the output method, we're essentially saying that
7257 the frame is live, as per FRAME_LIVE_P. If we get a signal
7258 from this point on, x_destroy_window might screw up reference
7259 counts etc. */
7260 f->output_method = output_w32;
7261 f->output_data.w32 =
7262 (struct w32_output *) xmalloc (sizeof (struct w32_output));
7263 bzero (f->output_data.w32, sizeof (struct w32_output));
7265 FRAME_FONTSET (f) = -1;
7266 f->icon_name = Qnil;
7268 #if 0 /* GLYPH_DEBUG TODO: image support. */
7269 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
7270 dpyinfo_refcount = dpyinfo->reference_count;
7271 #endif /* GLYPH_DEBUG */
7272 #ifdef MULTI_KBOARD
7273 FRAME_KBOARD (f) = kb;
7274 #endif
7275 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
7276 f->output_data.w32->explicit_parent = 0;
7278 /* Set the name; the functions to which we pass f expect the name to
7279 be set. */
7280 if (EQ (name, Qunbound) || NILP (name))
7282 f->name = build_string (dpyinfo->w32_id_name);
7283 f->explicit_name = 0;
7285 else
7287 f->name = name;
7288 f->explicit_name = 1;
7289 /* use the frame's title when getting resources for this frame. */
7290 specbind (Qx_resource_name, name);
7293 /* Extract the window parameters from the supplied values
7294 that are needed to determine window geometry. */
7296 Lisp_Object font;
7298 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
7300 BLOCK_INPUT;
7301 /* First, try whatever font the caller has specified. */
7302 if (STRINGP (font))
7304 tem = Fquery_fontset (font, Qnil);
7305 if (STRINGP (tem))
7306 font = x_new_fontset (f, SDATA (tem));
7307 else
7308 font = x_new_font (f, SDATA (font));
7311 /* Try out a font which we hope has bold and italic variations. */
7312 if (!STRINGP (font))
7313 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
7314 if (! STRINGP (font))
7315 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
7316 /* If those didn't work, look for something which will at least work. */
7317 if (! STRINGP (font))
7318 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
7319 UNBLOCK_INPUT;
7320 if (! STRINGP (font))
7321 font = build_string ("Fixedsys");
7323 x_default_parameter (f, parms, Qfont, font,
7324 "font", "Font", RES_TYPE_STRING);
7327 x_default_parameter (f, parms, Qborder_width, make_number (2),
7328 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
7329 /* This defaults to 2 in order to match xterm. We recognize either
7330 internalBorderWidth or internalBorder (which is what xterm calls
7331 it). */
7332 if (NILP (Fassq (Qinternal_border_width, parms)))
7334 Lisp_Object value;
7336 value = w32_get_arg (parms, Qinternal_border_width,
7337 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
7338 if (! EQ (value, Qunbound))
7339 parms = Fcons (Fcons (Qinternal_border_width, value),
7340 parms);
7342 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
7343 "internalBorderWidth", "internalBorderWidth",
7344 RES_TYPE_NUMBER);
7346 /* Also do the stuff which must be set before the window exists. */
7347 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
7348 "foreground", "Foreground", RES_TYPE_STRING);
7349 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
7350 "background", "Background", RES_TYPE_STRING);
7351 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
7352 "pointerColor", "Foreground", RES_TYPE_STRING);
7353 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
7354 "cursorColor", "Foreground", RES_TYPE_STRING);
7355 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
7356 "borderColor", "BorderColor", RES_TYPE_STRING);
7358 /* Init faces before x_default_parameter is called for scroll-bar
7359 parameters because that function calls x_set_scroll_bar_width,
7360 which calls change_frame_size, which calls Fset_window_buffer,
7361 which runs hooks, which call Fvertical_motion. At the end, we
7362 end up in init_iterator with a null face cache, which should not
7363 happen. */
7364 init_frame_faces (f);
7366 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
7367 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
7369 window_prompting = x_figure_window_size (f, parms, 0);
7371 /* No fringes on tip frame. */
7372 f->fringe_cols = 0;
7373 f->left_fringe_width = 0;
7374 f->right_fringe_width = 0;
7376 BLOCK_INPUT;
7377 my_create_tip_window (f);
7378 UNBLOCK_INPUT;
7380 x_make_gc (f);
7382 x_default_parameter (f, parms, Qauto_raise, Qnil,
7383 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7384 x_default_parameter (f, parms, Qauto_lower, Qnil,
7385 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7386 x_default_parameter (f, parms, Qcursor_type, Qbox,
7387 "cursorType", "CursorType", RES_TYPE_SYMBOL);
7389 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
7390 Change will not be effected unless different from the current
7391 FRAME_LINES (f). */
7392 width = FRAME_COLS (f);
7393 height = FRAME_LINES (f);
7394 FRAME_LINES (f) = 0;
7395 SET_FRAME_COLS (f, 0);
7396 change_frame_size (f, height, width, 1, 0, 0);
7398 /* Add `tooltip' frame parameter's default value. */
7399 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
7400 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
7401 Qnil));
7403 /* Set up faces after all frame parameters are known. This call
7404 also merges in face attributes specified for new frames.
7406 Frame parameters may be changed if .Xdefaults contains
7407 specifications for the default font. For example, if there is an
7408 `Emacs.default.attributeBackground: pink', the `background-color'
7409 attribute of the frame get's set, which let's the internal border
7410 of the tooltip frame appear in pink. Prevent this. */
7412 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
7414 /* Set tip_frame here, so that */
7415 tip_frame = frame;
7416 call1 (Qface_set_after_frame_default, frame);
7418 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
7419 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
7420 Qnil));
7423 f->no_split = 1;
7425 UNGCPRO;
7427 /* It is now ok to make the frame official even if we get an error
7428 below. And the frame needs to be on Vframe_list or making it
7429 visible won't work. */
7430 Vframe_list = Fcons (frame, Vframe_list);
7432 /* Now that the frame is official, it counts as a reference to
7433 its display. */
7434 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
7436 /* Setting attributes of faces of the tooltip frame from resources
7437 and similar will increment face_change_count, which leads to the
7438 clearing of all current matrices. Since this isn't necessary
7439 here, avoid it by resetting face_change_count to the value it
7440 had before we created the tip frame. */
7441 face_change_count = face_change_count_before;
7443 /* Discard the unwind_protect. */
7444 return unbind_to (count, frame);
7448 /* Compute where to display tip frame F. PARMS is the list of frame
7449 parameters for F. DX and DY are specified offsets from the current
7450 location of the mouse. WIDTH and HEIGHT are the width and height
7451 of the tooltip. Return coordinates relative to the root window of
7452 the display in *ROOT_X, and *ROOT_Y. */
7454 static void
7455 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
7456 struct frame *f;
7457 Lisp_Object parms, dx, dy;
7458 int width, height;
7459 int *root_x, *root_y;
7461 Lisp_Object left, top;
7463 /* User-specified position? */
7464 left = Fcdr (Fassq (Qleft, parms));
7465 top = Fcdr (Fassq (Qtop, parms));
7467 /* Move the tooltip window where the mouse pointer is. Resize and
7468 show it. */
7469 if (!INTEGERP (left) || !INTEGERP (top))
7471 POINT pt;
7473 BLOCK_INPUT;
7474 GetCursorPos (&pt);
7475 *root_x = pt.x;
7476 *root_y = pt.y;
7477 UNBLOCK_INPUT;
7480 if (INTEGERP (top))
7481 *root_y = XINT (top);
7482 else if (*root_y + XINT (dy) <= 0)
7483 *root_y = 0; /* Can happen for negative dy */
7484 else if (*root_y + XINT (dy) + height <= FRAME_W32_DISPLAY_INFO (f)->height)
7485 /* It fits below the pointer */
7486 *root_y += XINT (dy);
7487 else if (height + XINT (dy) <= *root_y)
7488 /* It fits above the pointer. */
7489 *root_y -= height + XINT (dy);
7490 else
7491 /* Put it on the top. */
7492 *root_y = 0;
7494 if (INTEGERP (left))
7495 *root_x = XINT (left);
7496 else if (*root_x + XINT (dx) <= 0)
7497 *root_x = 0; /* Can happen for negative dx */
7498 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
7499 /* It fits to the right of the pointer. */
7500 *root_x += XINT (dx);
7501 else if (width + XINT (dx) <= *root_x)
7502 /* It fits to the left of the pointer. */
7503 *root_x -= width + XINT (dx);
7504 else
7505 /* Put it left justified on the screen -- it ought to fit that way. */
7506 *root_x = 0;
7510 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
7511 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
7512 A tooltip window is a small window displaying a string.
7514 This is an internal function; Lisp code should call `tooltip-show'.
7516 FRAME nil or omitted means use the selected frame.
7518 PARMS is an optional list of frame parameters which can be
7519 used to change the tooltip's appearance.
7521 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
7522 means use the default timeout of 5 seconds.
7524 If the list of frame parameters PARMS contains a `left' parameter,
7525 the tooltip is displayed at that x-position. Otherwise it is
7526 displayed at the mouse position, with offset DX added (default is 5 if
7527 DX isn't specified). Likewise for the y-position; if a `top' frame
7528 parameter is specified, it determines the y-position of the tooltip
7529 window, otherwise it is displayed at the mouse position, with offset
7530 DY added (default is -10).
7532 A tooltip's maximum size is specified by `x-max-tooltip-size'.
7533 Text larger than the specified size is clipped. */)
7534 (string, frame, parms, timeout, dx, dy)
7535 Lisp_Object string, frame, parms, timeout, dx, dy;
7537 struct frame *f;
7538 struct window *w;
7539 int root_x, root_y;
7540 struct buffer *old_buffer;
7541 struct text_pos pos;
7542 int i, width, height;
7543 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
7544 int old_windows_or_buffers_changed = windows_or_buffers_changed;
7545 int count = SPECPDL_INDEX ();
7547 specbind (Qinhibit_redisplay, Qt);
7549 GCPRO4 (string, parms, frame, timeout);
7551 CHECK_STRING (string);
7552 f = check_x_frame (frame);
7553 if (NILP (timeout))
7554 timeout = make_number (5);
7555 else
7556 CHECK_NATNUM (timeout);
7558 if (NILP (dx))
7559 dx = make_number (5);
7560 else
7561 CHECK_NUMBER (dx);
7563 if (NILP (dy))
7564 dy = make_number (-10);
7565 else
7566 CHECK_NUMBER (dy);
7568 if (NILP (last_show_tip_args))
7569 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
7571 if (!NILP (tip_frame))
7573 Lisp_Object last_string = AREF (last_show_tip_args, 0);
7574 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
7575 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
7577 if (EQ (frame, last_frame)
7578 && !NILP (Fequal (last_string, string))
7579 && !NILP (Fequal (last_parms, parms)))
7581 struct frame *f = XFRAME (tip_frame);
7583 /* Only DX and DY have changed. */
7584 if (!NILP (tip_timer))
7586 Lisp_Object timer = tip_timer;
7587 tip_timer = Qnil;
7588 call1 (Qcancel_timer, timer);
7591 BLOCK_INPUT;
7592 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
7593 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
7595 /* Put tooltip in topmost group and in position. */
7596 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
7597 root_x, root_y, 0, 0,
7598 SWP_NOSIZE | SWP_NOACTIVATE);
7600 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7601 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
7602 0, 0, 0, 0,
7603 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
7605 UNBLOCK_INPUT;
7606 goto start_timer;
7610 /* Hide a previous tip, if any. */
7611 Fx_hide_tip ();
7613 ASET (last_show_tip_args, 0, string);
7614 ASET (last_show_tip_args, 1, frame);
7615 ASET (last_show_tip_args, 2, parms);
7617 /* Add default values to frame parameters. */
7618 if (NILP (Fassq (Qname, parms)))
7619 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7620 if (NILP (Fassq (Qinternal_border_width, parms)))
7621 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7622 if (NILP (Fassq (Qborder_width, parms)))
7623 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7624 if (NILP (Fassq (Qborder_color, parms)))
7625 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7626 if (NILP (Fassq (Qbackground_color, parms)))
7627 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7628 parms);
7630 /* Block input until the tip has been fully drawn, to avoid crashes
7631 when drawing tips in menus. */
7632 BLOCK_INPUT;
7634 /* Create a frame for the tooltip, and record it in the global
7635 variable tip_frame. */
7636 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
7637 f = XFRAME (frame);
7639 /* Set up the frame's root window. */
7640 w = XWINDOW (FRAME_ROOT_WINDOW (f));
7641 w->left_col = w->top_line = make_number (0);
7643 if (CONSP (Vx_max_tooltip_size)
7644 && INTEGERP (XCAR (Vx_max_tooltip_size))
7645 && XINT (XCAR (Vx_max_tooltip_size)) > 0
7646 && INTEGERP (XCDR (Vx_max_tooltip_size))
7647 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
7649 w->total_cols = XCAR (Vx_max_tooltip_size);
7650 w->total_lines = XCDR (Vx_max_tooltip_size);
7652 else
7654 w->total_cols = make_number (80);
7655 w->total_lines = make_number (40);
7658 FRAME_TOTAL_COLS (f) = XINT (w->total_cols);
7659 adjust_glyphs (f);
7660 w->pseudo_window_p = 1;
7662 /* Display the tooltip text in a temporary buffer. */
7663 old_buffer = current_buffer;
7664 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
7665 current_buffer->truncate_lines = Qnil;
7666 clear_glyph_matrix (w->desired_matrix);
7667 clear_glyph_matrix (w->current_matrix);
7668 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7669 try_window (FRAME_ROOT_WINDOW (f), pos, 0);
7671 /* Compute width and height of the tooltip. */
7672 width = height = 0;
7673 for (i = 0; i < w->desired_matrix->nrows; ++i)
7675 struct glyph_row *row = &w->desired_matrix->rows[i];
7676 struct glyph *last;
7677 int row_width;
7679 /* Stop at the first empty row at the end. */
7680 if (!row->enabled_p || !row->displays_text_p)
7681 break;
7683 /* Let the row go over the full width of the frame. */
7684 row->full_width_p = 1;
7686 #ifdef TODO /* Investigate why some fonts need more width than is
7687 calculated for some tooltips. */
7688 /* There's a glyph at the end of rows that is use to place
7689 the cursor there. Don't include the width of this glyph. */
7690 if (row->used[TEXT_AREA])
7692 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
7693 row_width = row->pixel_width - last->pixel_width;
7695 else
7696 #endif
7697 row_width = row->pixel_width;
7699 /* TODO: find why tips do not draw along baseline as instructed. */
7700 height += row->height;
7701 width = max (width, row_width);
7704 /* Add the frame's internal border to the width and height the X
7705 window should have. */
7706 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
7707 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
7709 /* Move the tooltip window where the mouse pointer is. Resize and
7710 show it. */
7711 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
7714 /* Adjust Window size to take border into account. */
7715 RECT rect;
7716 rect.left = rect.top = 0;
7717 rect.right = width;
7718 rect.bottom = height;
7719 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
7720 FRAME_EXTERNAL_MENU_BAR (f));
7722 /* Position and size tooltip, and put it in the topmost group.
7723 The add-on of 3 to the 5th argument is a kludge: without it,
7724 some fonts cause the last character of the tip to be truncated,
7725 for some obscure reason. */
7726 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
7727 root_x, root_y, rect.right - rect.left + 3,
7728 rect.bottom - rect.top, SWP_NOACTIVATE);
7730 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7731 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
7732 0, 0, 0, 0,
7733 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
7735 /* Let redisplay know that we have made the frame visible already. */
7736 f->async_visible = 1;
7738 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
7741 /* Draw into the window. */
7742 w->must_be_updated_p = 1;
7743 update_single_window (w, 1);
7745 UNBLOCK_INPUT;
7747 /* Restore original current buffer. */
7748 set_buffer_internal_1 (old_buffer);
7749 windows_or_buffers_changed = old_windows_or_buffers_changed;
7751 start_timer:
7752 /* Let the tip disappear after timeout seconds. */
7753 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7754 intern ("x-hide-tip"));
7756 UNGCPRO;
7757 return unbind_to (count, Qnil);
7761 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7762 doc: /* Hide the current tooltip window, if there is any.
7763 Value is t if tooltip was open, nil otherwise. */)
7766 int count;
7767 Lisp_Object deleted, frame, timer;
7768 struct gcpro gcpro1, gcpro2;
7770 /* Return quickly if nothing to do. */
7771 if (NILP (tip_timer) && NILP (tip_frame))
7772 return Qnil;
7774 frame = tip_frame;
7775 timer = tip_timer;
7776 GCPRO2 (frame, timer);
7777 tip_frame = tip_timer = deleted = Qnil;
7779 count = SPECPDL_INDEX ();
7780 specbind (Qinhibit_redisplay, Qt);
7781 specbind (Qinhibit_quit, Qt);
7783 if (!NILP (timer))
7784 call1 (Qcancel_timer, timer);
7786 if (FRAMEP (frame))
7788 Fdelete_frame (frame, Qnil);
7789 deleted = Qt;
7792 UNGCPRO;
7793 return unbind_to (count, deleted);
7798 /***********************************************************************
7799 File selection dialog
7800 ***********************************************************************/
7801 extern Lisp_Object Qfile_name_history;
7803 /* Callback for altering the behaviour of the Open File dialog.
7804 Makes the Filename text field contain "Current Directory" and be
7805 read-only when "Directories" is selected in the filter. This
7806 allows us to work around the fact that the standard Open File
7807 dialog does not support directories. */
7808 UINT CALLBACK
7809 file_dialog_callback (hwnd, msg, wParam, lParam)
7810 HWND hwnd;
7811 UINT msg;
7812 WPARAM wParam;
7813 LPARAM lParam;
7815 if (msg == WM_NOTIFY)
7817 OFNOTIFY * notify = (OFNOTIFY *)lParam;
7818 /* Detect when the Filter dropdown is changed. */
7819 if (notify->hdr.code == CDN_TYPECHANGE
7820 || notify->hdr.code == CDN_INITDONE)
7822 HWND dialog = GetParent (hwnd);
7823 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7825 /* Directories is in index 2. */
7826 if (notify->lpOFN->nFilterIndex == 2)
7828 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
7829 "Current Directory");
7830 EnableWindow (edit_control, FALSE);
7832 else
7834 /* Don't override default filename on init done. */
7835 if (notify->hdr.code == CDN_TYPECHANGE)
7836 CommDlg_OpenSave_SetControlText (dialog,
7837 FILE_NAME_TEXT_FIELD, "");
7838 EnableWindow (edit_control, TRUE);
7842 return 0;
7845 /* Since we compile with _WIN32_WINNT set to 0x0400 (for NT4 compatibility)
7846 we end up with the old file dialogs. Define a big enough struct for the
7847 new dialog to trick GetOpenFileName into giving us the new dialogs on
7848 Windows 2000 and XP. */
7849 typedef struct
7851 OPENFILENAME real_details;
7852 void * pReserved;
7853 DWORD dwReserved;
7854 DWORD FlagsEx;
7855 } NEWOPENFILENAME;
7858 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7859 doc: /* Read file name, prompting with PROMPT in directory DIR.
7860 Use a file selection dialog.
7861 Select DEFAULT-FILENAME in the dialog's file selection box, if
7862 specified. Ensure that file exists if MUSTMATCH is non-nil.
7863 If ONLY-DIR-P is non-nil, the user can only select directories. */)
7864 (prompt, dir, default_filename, mustmatch, only_dir_p)
7865 Lisp_Object prompt, dir, default_filename, mustmatch, only_dir_p;
7867 struct frame *f = SELECTED_FRAME ();
7868 Lisp_Object file = Qnil;
7869 int count = SPECPDL_INDEX ();
7870 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
7871 char filename[MAX_PATH + 1];
7872 char init_dir[MAX_PATH + 1];
7873 int default_filter_index = 1; /* 1: All Files, 2: Directories only */
7875 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, file);
7876 CHECK_STRING (prompt);
7877 CHECK_STRING (dir);
7879 /* Create the dialog with PROMPT as title, using DIR as initial
7880 directory and using "*" as pattern. */
7881 dir = Fexpand_file_name (dir, Qnil);
7882 strncpy (init_dir, SDATA (ENCODE_FILE (dir)), MAX_PATH);
7883 init_dir[MAX_PATH] = '\0';
7884 unixtodos_filename (init_dir);
7886 if (STRINGP (default_filename))
7888 char *file_name_only;
7889 char *full_path_name = SDATA (ENCODE_FILE (default_filename));
7891 unixtodos_filename (full_path_name);
7893 file_name_only = strrchr (full_path_name, '\\');
7894 if (!file_name_only)
7895 file_name_only = full_path_name;
7896 else
7897 file_name_only++;
7899 strncpy (filename, file_name_only, MAX_PATH);
7900 filename[MAX_PATH] = '\0';
7902 else
7903 filename[0] = '\0';
7906 NEWOPENFILENAME new_file_details;
7907 BOOL file_opened = FALSE;
7908 OPENFILENAME * file_details = &new_file_details.real_details;
7910 /* Prevent redisplay. */
7911 specbind (Qinhibit_redisplay, Qt);
7912 BLOCK_INPUT;
7914 bzero (&new_file_details, sizeof (new_file_details));
7915 /* Apparently NT4 crashes if you give it an unexpected size.
7916 I'm not sure about Windows 9x, so play it safe. */
7917 if (w32_major_version > 4 && w32_major_version < 95)
7918 file_details->lStructSize = sizeof (NEWOPENFILENAME);
7919 else
7920 file_details->lStructSize = sizeof (OPENFILENAME);
7922 file_details->hwndOwner = FRAME_W32_WINDOW (f);
7923 /* Undocumented Bug in Common File Dialog:
7924 If a filter is not specified, shell links are not resolved. */
7925 file_details->lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
7926 file_details->lpstrFile = filename;
7927 file_details->nMaxFile = sizeof (filename);
7928 file_details->lpstrInitialDir = init_dir;
7929 file_details->lpstrTitle = SDATA (prompt);
7931 if (! NILP (only_dir_p))
7932 default_filter_index = 2;
7934 file_details->nFilterIndex = default_filter_index;
7936 file_details->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7937 | OFN_EXPLORER | OFN_ENABLEHOOK);
7938 if (!NILP (mustmatch))
7940 /* Require that the path to the parent directory exists. */
7941 file_details->Flags |= OFN_PATHMUSTEXIST;
7942 /* If we are looking for a file, require that it exists. */
7943 if (NILP (only_dir_p))
7944 file_details->Flags |= OFN_FILEMUSTEXIST;
7947 file_details->lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
7949 file_opened = GetOpenFileName (file_details);
7951 UNBLOCK_INPUT;
7953 if (file_opened)
7955 dostounix_filename (filename);
7957 if (file_details->nFilterIndex == 2)
7959 /* "Directories" selected - strip dummy file name. */
7960 char * last = strrchr (filename, '/');
7961 *last = '\0';
7964 file = DECODE_FILE(build_string (filename));
7966 /* User cancelled the dialog without making a selection. */
7967 else if (!CommDlgExtendedError ())
7968 file = Qnil;
7969 /* An error occurred, fallback on reading from the mini-buffer. */
7970 else
7971 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
7972 dir, mustmatch, dir, Qfile_name_history,
7973 default_filename, Qnil);
7975 file = unbind_to (count, file);
7978 UNGCPRO;
7980 /* Make "Cancel" equivalent to C-g. */
7981 if (NILP (file))
7982 Fsignal (Qquit, Qnil);
7984 return unbind_to (count, file);
7989 /***********************************************************************
7990 w32 specialized functions
7991 ***********************************************************************/
7993 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
7994 doc: /* Select a font for the named FRAME using the W32 font dialog.
7995 Returns an X-style font string corresponding to the selection.
7997 If FRAME is omitted or nil, it defaults to the selected frame.
7998 If INCLUDE-PROPORTIONAL is non-nil, include proportional fonts
7999 in the font selection dialog. */)
8000 (frame, include_proportional)
8001 Lisp_Object frame, include_proportional;
8003 FRAME_PTR f = check_x_frame (frame);
8004 CHOOSEFONT cf;
8005 LOGFONT lf;
8006 TEXTMETRIC tm;
8007 HDC hdc;
8008 HANDLE oldobj;
8009 char buf[100];
8011 bzero (&cf, sizeof (cf));
8012 bzero (&lf, sizeof (lf));
8014 cf.lStructSize = sizeof (cf);
8015 cf.hwndOwner = FRAME_W32_WINDOW (f);
8016 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
8018 /* Unless include_proportional is non-nil, limit the selection to
8019 monospaced fonts. */
8020 if (NILP (include_proportional))
8021 cf.Flags |= CF_FIXEDPITCHONLY;
8023 cf.lpLogFont = &lf;
8025 /* Initialize as much of the font details as we can from the current
8026 default font. */
8027 hdc = GetDC (FRAME_W32_WINDOW (f));
8028 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
8029 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
8030 if (GetTextMetrics (hdc, &tm))
8032 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
8033 lf.lfWeight = tm.tmWeight;
8034 lf.lfItalic = tm.tmItalic;
8035 lf.lfUnderline = tm.tmUnderlined;
8036 lf.lfStrikeOut = tm.tmStruckOut;
8037 lf.lfCharSet = tm.tmCharSet;
8038 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
8040 SelectObject (hdc, oldobj);
8041 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
8043 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
8044 return Qnil;
8046 return build_string (buf);
8049 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
8050 Sw32_send_sys_command, 1, 2, 0,
8051 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
8052 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
8053 to minimize), #xf120 to restore frame to original size, and #xf100
8054 to activate the menubar for keyboard access. #xf140 activates the
8055 screen saver if defined.
8057 If optional parameter FRAME is not specified, use selected frame. */)
8058 (command, frame)
8059 Lisp_Object command, frame;
8061 FRAME_PTR f = check_x_frame (frame);
8063 CHECK_NUMBER (command);
8065 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
8067 return Qnil;
8070 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
8071 doc: /* Get Windows to perform OPERATION on DOCUMENT.
8072 This is a wrapper around the ShellExecute system function, which
8073 invokes the application registered to handle OPERATION for DOCUMENT.
8075 OPERATION is either nil or a string that names a supported operation.
8076 What operations can be used depends on the particular DOCUMENT and its
8077 handler application, but typically it is one of the following common
8078 operations:
8080 \"open\" - open DOCUMENT, which could be a file, a directory, or an
8081 executable program. If it is an application, that
8082 application is launched in the current buffer's default
8083 directory. Otherwise, the application associated with
8084 DOCUMENT is launched in the buffer's default directory.
8085 \"print\" - print DOCUMENT, which must be a file
8086 \"explore\" - start the Windows Explorer on DOCUMENT
8087 \"edit\" - launch an editor and open DOCUMENT for editing; which
8088 editor is launched depends on the association for the
8089 specified DOCUMENT
8090 \"find\" - initiate search starting from DOCUMENT which must specify
8091 a directory
8092 nil - invoke the default OPERATION, or \"open\" if default is
8093 not defined or unavailable
8095 DOCUMENT is typically the name of a document file or a URL, but can
8096 also be a program executable to run, or a directory to open in the
8097 Windows Explorer.
8099 If DOCUMENT is a program executable, the optional arg PARAMETERS can
8100 be a string containing command line parameters that will be passed to
8101 the program; otherwise, PARAMETERS should be nil or unspecified.
8103 Second optional argument SHOW-FLAG can be used to control how the
8104 application will be displayed when it is invoked. If SHOW-FLAG is nil
8105 or unspceified, the application is displayed normally, otherwise it is
8106 an integer representing a ShowWindow flag:
8108 0 - start hidden
8109 1 - start normally
8110 3 - start maximized
8111 6 - start minimized */)
8112 (operation, document, parameters, show_flag)
8113 Lisp_Object operation, document, parameters, show_flag;
8115 Lisp_Object current_dir;
8117 CHECK_STRING (document);
8119 /* Encode filename and current directory. */
8120 current_dir = ENCODE_FILE (current_buffer->directory);
8121 document = ENCODE_FILE (document);
8122 if ((int) ShellExecute (NULL,
8123 (STRINGP (operation) ?
8124 SDATA (operation) : NULL),
8125 SDATA (document),
8126 (STRINGP (parameters) ?
8127 SDATA (parameters) : NULL),
8128 SDATA (current_dir),
8129 (INTEGERP (show_flag) ?
8130 XINT (show_flag) : SW_SHOWDEFAULT))
8131 > 32)
8132 return Qt;
8133 error ("ShellExecute failed: %s", w32_strerror (0));
8136 /* Lookup virtual keycode from string representing the name of a
8137 non-ascii keystroke into the corresponding virtual key, using
8138 lispy_function_keys. */
8139 static int
8140 lookup_vk_code (char *key)
8142 int i;
8144 for (i = 0; i < 256; i++)
8145 if (lispy_function_keys[i] != 0
8146 && strcmp (lispy_function_keys[i], key) == 0)
8147 return i;
8149 return -1;
8152 /* Convert a one-element vector style key sequence to a hot key
8153 definition. */
8154 static Lisp_Object
8155 w32_parse_hot_key (key)
8156 Lisp_Object key;
8158 /* Copied from Fdefine_key and store_in_keymap. */
8159 register Lisp_Object c;
8160 int vk_code;
8161 int lisp_modifiers;
8162 int w32_modifiers;
8163 struct gcpro gcpro1;
8165 CHECK_VECTOR (key);
8167 if (XFASTINT (Flength (key)) != 1)
8168 return Qnil;
8170 GCPRO1 (key);
8172 c = Faref (key, make_number (0));
8174 if (CONSP (c) && lucid_event_type_list_p (c))
8175 c = Fevent_convert_list (c);
8177 UNGCPRO;
8179 if (! INTEGERP (c) && ! SYMBOLP (c))
8180 error ("Key definition is invalid");
8182 /* Work out the base key and the modifiers. */
8183 if (SYMBOLP (c))
8185 c = parse_modifiers (c);
8186 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8187 c = Fcar (c);
8188 if (!SYMBOLP (c))
8189 abort ();
8190 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
8192 else if (INTEGERP (c))
8194 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8195 /* Many ascii characters are their own virtual key code. */
8196 vk_code = XINT (c) & CHARACTERBITS;
8199 if (vk_code < 0 || vk_code > 255)
8200 return Qnil;
8202 if ((lisp_modifiers & meta_modifier) != 0
8203 && !NILP (Vw32_alt_is_meta))
8204 lisp_modifiers |= alt_modifier;
8206 /* Supply defs missing from mingw32. */
8207 #ifndef MOD_ALT
8208 #define MOD_ALT 0x0001
8209 #define MOD_CONTROL 0x0002
8210 #define MOD_SHIFT 0x0004
8211 #define MOD_WIN 0x0008
8212 #endif
8214 /* Convert lisp modifiers to Windows hot-key form. */
8215 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8216 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8217 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8218 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8220 return HOTKEY (vk_code, w32_modifiers);
8223 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8224 Sw32_register_hot_key, 1, 1, 0,
8225 doc: /* Register KEY as a hot-key combination.
8226 Certain key combinations like Alt-Tab are reserved for system use on
8227 Windows, and therefore are normally intercepted by the system. However,
8228 most of these key combinations can be received by registering them as
8229 hot-keys, overriding their special meaning.
8231 KEY must be a one element key definition in vector form that would be
8232 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
8233 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
8234 is always interpreted as the Windows modifier keys.
8236 The return value is the hotkey-id if registered, otherwise nil. */)
8237 (key)
8238 Lisp_Object key;
8240 key = w32_parse_hot_key (key);
8242 if (NILP (Fmemq (key, w32_grabbed_keys)))
8244 /* Reuse an empty slot if possible. */
8245 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8247 /* Safe to add new key to list, even if we have focus. */
8248 if (NILP (item))
8249 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8250 else
8251 XSETCAR (item, key);
8253 /* Notify input thread about new hot-key definition, so that it
8254 takes effect without needing to switch focus. */
8255 #ifdef USE_LISP_UNION_TYPE
8256 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8257 (WPARAM) key.i, 0);
8258 #else
8259 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8260 (WPARAM) key, 0);
8261 #endif
8264 return key;
8267 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8268 Sw32_unregister_hot_key, 1, 1, 0,
8269 doc: /* Unregister KEY as a hot-key combination. */)
8270 (key)
8271 Lisp_Object key;
8273 Lisp_Object item;
8275 if (!INTEGERP (key))
8276 key = w32_parse_hot_key (key);
8278 item = Fmemq (key, w32_grabbed_keys);
8280 if (!NILP (item))
8282 /* Notify input thread about hot-key definition being removed, so
8283 that it takes effect without needing focus switch. */
8284 #ifdef USE_LISP_UNION_TYPE
8285 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8286 (WPARAM) XINT (XCAR (item)), (LPARAM) item.i))
8287 #else
8288 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8289 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
8291 #endif
8293 MSG msg;
8294 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8296 return Qt;
8298 return Qnil;
8301 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8302 Sw32_registered_hot_keys, 0, 0, 0,
8303 doc: /* Return list of registered hot-key IDs. */)
8306 return Fcopy_sequence (w32_grabbed_keys);
8309 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8310 Sw32_reconstruct_hot_key, 1, 1, 0,
8311 doc: /* Convert hot-key ID to a lisp key combination.
8312 usage: (w32-reconstruct-hot-key ID) */)
8313 (hotkeyid)
8314 Lisp_Object hotkeyid;
8316 int vk_code, w32_modifiers;
8317 Lisp_Object key;
8319 CHECK_NUMBER (hotkeyid);
8321 vk_code = HOTKEY_VK_CODE (hotkeyid);
8322 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8324 if (lispy_function_keys[vk_code])
8325 key = intern (lispy_function_keys[vk_code]);
8326 else
8327 key = make_number (vk_code);
8329 key = Fcons (key, Qnil);
8330 if (w32_modifiers & MOD_SHIFT)
8331 key = Fcons (Qshift, key);
8332 if (w32_modifiers & MOD_CONTROL)
8333 key = Fcons (Qctrl, key);
8334 if (w32_modifiers & MOD_ALT)
8335 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8336 if (w32_modifiers & MOD_WIN)
8337 key = Fcons (Qhyper, key);
8339 return key;
8342 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8343 Sw32_toggle_lock_key, 1, 2, 0,
8344 doc: /* Toggle the state of the lock key KEY.
8345 KEY can be `capslock', `kp-numlock', or `scroll'.
8346 If the optional parameter NEW-STATE is a number, then the state of KEY
8347 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
8348 (key, new_state)
8349 Lisp_Object key, new_state;
8351 int vk_code;
8353 if (EQ (key, intern ("capslock")))
8354 vk_code = VK_CAPITAL;
8355 else if (EQ (key, intern ("kp-numlock")))
8356 vk_code = VK_NUMLOCK;
8357 else if (EQ (key, intern ("scroll")))
8358 vk_code = VK_SCROLL;
8359 else
8360 return Qnil;
8362 if (!dwWindowsThreadId)
8363 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8365 #ifdef USE_LISP_UNION_TYPE
8366 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8367 (WPARAM) vk_code, (LPARAM) new_state.i))
8368 #else
8369 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8370 (WPARAM) vk_code, (LPARAM) new_state))
8371 #endif
8373 MSG msg;
8374 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8375 return make_number (msg.wParam);
8377 return Qnil;
8380 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8381 2, 2, 0,
8382 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8384 This is a direct interface to the Windows API FindWindow function. */)
8385 (class, name)
8386 Lisp_Object class, name;
8388 HWND hnd;
8390 if (!NILP (class))
8391 CHECK_STRING (class);
8392 if (!NILP (name))
8393 CHECK_STRING (name);
8395 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8396 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8397 if (!hnd)
8398 return Qnil;
8399 return Qt;
8404 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8405 doc: /* Return storage information about the file system FILENAME is on.
8406 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8407 storage of the file system, FREE is the free storage, and AVAIL is the
8408 storage available to a non-superuser. All 3 numbers are in bytes.
8409 If the underlying system call fails, value is nil. */)
8410 (filename)
8411 Lisp_Object filename;
8413 Lisp_Object encoded, value;
8415 CHECK_STRING (filename);
8416 filename = Fexpand_file_name (filename, Qnil);
8417 encoded = ENCODE_FILE (filename);
8419 value = Qnil;
8421 /* Determining the required information on Windows turns out, sadly,
8422 to be more involved than one would hope. The original Win32 api
8423 call for this will return bogus information on some systems, but we
8424 must dynamically probe for the replacement api, since that was
8425 added rather late on. */
8427 HMODULE hKernel = GetModuleHandle ("kernel32");
8428 BOOL (*pfn_GetDiskFreeSpaceEx)
8429 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
8430 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
8432 /* On Windows, we may need to specify the root directory of the
8433 volume holding FILENAME. */
8434 char rootname[MAX_PATH];
8435 char *name = SDATA (encoded);
8437 /* find the root name of the volume if given */
8438 if (isalpha (name[0]) && name[1] == ':')
8440 rootname[0] = name[0];
8441 rootname[1] = name[1];
8442 rootname[2] = '\\';
8443 rootname[3] = 0;
8445 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8447 char *str = rootname;
8448 int slashes = 4;
8451 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8452 break;
8453 *str++ = *name++;
8455 while ( *name );
8457 *str++ = '\\';
8458 *str = 0;
8461 if (pfn_GetDiskFreeSpaceEx)
8463 /* Unsigned large integers cannot be cast to double, so
8464 use signed ones instead. */
8465 LARGE_INTEGER availbytes;
8466 LARGE_INTEGER freebytes;
8467 LARGE_INTEGER totalbytes;
8469 if (pfn_GetDiskFreeSpaceEx(rootname,
8470 (ULARGE_INTEGER *)&availbytes,
8471 (ULARGE_INTEGER *)&totalbytes,
8472 (ULARGE_INTEGER *)&freebytes))
8473 value = list3 (make_float ((double) totalbytes.QuadPart),
8474 make_float ((double) freebytes.QuadPart),
8475 make_float ((double) availbytes.QuadPart));
8477 else
8479 DWORD sectors_per_cluster;
8480 DWORD bytes_per_sector;
8481 DWORD free_clusters;
8482 DWORD total_clusters;
8484 if (GetDiskFreeSpace(rootname,
8485 &sectors_per_cluster,
8486 &bytes_per_sector,
8487 &free_clusters,
8488 &total_clusters))
8489 value = list3 (make_float ((double) total_clusters
8490 * sectors_per_cluster * bytes_per_sector),
8491 make_float ((double) free_clusters
8492 * sectors_per_cluster * bytes_per_sector),
8493 make_float ((double) free_clusters
8494 * sectors_per_cluster * bytes_per_sector));
8498 return value;
8501 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8502 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8505 static char pname_buf[256];
8506 int err;
8507 HANDLE hPrn;
8508 PRINTER_INFO_2 *ppi2 = NULL;
8509 DWORD dwNeeded = 0, dwReturned = 0;
8511 /* Retrieve the default string from Win.ini (the registry).
8512 * String will be in form "printername,drivername,portname".
8513 * This is the most portable way to get the default printer. */
8514 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8515 return Qnil;
8516 /* printername precedes first "," character */
8517 strtok (pname_buf, ",");
8518 /* We want to know more than the printer name */
8519 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8520 return Qnil;
8521 GetPrinter (hPrn, 2, NULL, 0, &dwNeeded);
8522 if (dwNeeded == 0)
8524 ClosePrinter (hPrn);
8525 return Qnil;
8527 /* Allocate memory for the PRINTER_INFO_2 struct */
8528 ppi2 = (PRINTER_INFO_2 *) xmalloc (dwNeeded);
8529 if (!ppi2)
8531 ClosePrinter (hPrn);
8532 return Qnil;
8534 /* Call GetPrinter() again with big enouth memory block */
8535 err = GetPrinter (hPrn, 2, (LPBYTE)ppi2, dwNeeded, &dwReturned);
8536 ClosePrinter (hPrn);
8537 if (!err)
8539 xfree(ppi2);
8540 return Qnil;
8543 if (ppi2)
8545 if (ppi2->Attributes & PRINTER_ATTRIBUTE_SHARED && ppi2->pServerName)
8547 /* a remote printer */
8548 if (*ppi2->pServerName == '\\')
8549 _snprintf(pname_buf, sizeof (pname_buf), "%s\\%s", ppi2->pServerName,
8550 ppi2->pShareName);
8551 else
8552 _snprintf(pname_buf, sizeof (pname_buf), "\\\\%s\\%s", ppi2->pServerName,
8553 ppi2->pShareName);
8554 pname_buf[sizeof (pname_buf) - 1] = '\0';
8556 else
8558 /* a local printer */
8559 strncpy(pname_buf, ppi2->pPortName, sizeof (pname_buf));
8560 pname_buf[sizeof (pname_buf) - 1] = '\0';
8561 /* `pPortName' can include several ports, delimited by ','.
8562 * we only use the first one. */
8563 strtok(pname_buf, ",");
8565 xfree(ppi2);
8568 return build_string (pname_buf);
8571 /***********************************************************************
8572 Initialization
8573 ***********************************************************************/
8575 /* Keep this list in the same order as frame_parms in frame.c.
8576 Use 0 for unsupported frame parameters. */
8578 frame_parm_handler w32_frame_parm_handlers[] =
8580 x_set_autoraise,
8581 x_set_autolower,
8582 x_set_background_color,
8583 x_set_border_color,
8584 x_set_border_width,
8585 x_set_cursor_color,
8586 x_set_cursor_type,
8587 x_set_font,
8588 x_set_foreground_color,
8589 x_set_icon_name,
8590 x_set_icon_type,
8591 x_set_internal_border_width,
8592 x_set_menu_bar_lines,
8593 x_set_mouse_color,
8594 x_explicitly_set_name,
8595 x_set_scroll_bar_width,
8596 x_set_title,
8597 x_set_unsplittable,
8598 x_set_vertical_scroll_bars,
8599 x_set_visibility,
8600 x_set_tool_bar_lines,
8601 0, /* x_set_scroll_bar_foreground, */
8602 0, /* x_set_scroll_bar_background, */
8603 x_set_screen_gamma,
8604 x_set_line_spacing,
8605 x_set_fringe_width,
8606 x_set_fringe_width,
8607 0, /* x_set_wait_for_wm, */
8608 x_set_fullscreen,
8611 void
8612 syms_of_w32fns ()
8614 globals_of_w32fns ();
8615 /* This is zero if not using MS-Windows. */
8616 w32_in_use = 0;
8617 track_mouse_window = NULL;
8619 w32_visible_system_caret_hwnd = NULL;
8621 Qnone = intern ("none");
8622 staticpro (&Qnone);
8623 Qsuppress_icon = intern ("suppress-icon");
8624 staticpro (&Qsuppress_icon);
8625 Qundefined_color = intern ("undefined-color");
8626 staticpro (&Qundefined_color);
8627 Qcancel_timer = intern ("cancel-timer");
8628 staticpro (&Qcancel_timer);
8630 Qhyper = intern ("hyper");
8631 staticpro (&Qhyper);
8632 Qsuper = intern ("super");
8633 staticpro (&Qsuper);
8634 Qmeta = intern ("meta");
8635 staticpro (&Qmeta);
8636 Qalt = intern ("alt");
8637 staticpro (&Qalt);
8638 Qctrl = intern ("ctrl");
8639 staticpro (&Qctrl);
8640 Qcontrol = intern ("control");
8641 staticpro (&Qcontrol);
8642 Qshift = intern ("shift");
8643 staticpro (&Qshift);
8644 /* This is the end of symbol initialization. */
8646 /* Text property `display' should be nonsticky by default. */
8647 Vtext_property_default_nonsticky
8648 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
8651 Fput (Qundefined_color, Qerror_conditions,
8652 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
8653 Fput (Qundefined_color, Qerror_message,
8654 build_string ("Undefined color"));
8656 staticpro (&w32_grabbed_keys);
8657 w32_grabbed_keys = Qnil;
8659 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
8660 doc: /* An array of color name mappings for Windows. */);
8661 Vw32_color_map = Qnil;
8663 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
8664 doc: /* Non-nil if Alt key presses are passed on to Windows.
8665 When non-nil, for example, Alt pressed and released and then space will
8666 open the System menu. When nil, Emacs processes the Alt key events, and
8667 then silently swallows them. */);
8668 Vw32_pass_alt_to_system = Qnil;
8670 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
8671 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8672 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8673 Vw32_alt_is_meta = Qt;
8675 DEFVAR_INT ("w32-quit-key", &w32_quit_key,
8676 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8677 w32_quit_key = 0;
8679 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8680 &Vw32_pass_lwindow_to_system,
8681 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8683 When non-nil, the Start menu is opened by tapping the key.
8684 If you set this to nil, the left \"Windows\" key is processed by Emacs
8685 according to the value of `w32-lwindow-modifier', which see.
8687 Note that some combinations of the left \"Windows\" key with other keys are
8688 caught by Windows at low level, and so binding them in Emacs will have no
8689 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8690 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8691 the doc string of `w32-phantom-key-code'. */);
8692 Vw32_pass_lwindow_to_system = Qt;
8694 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8695 &Vw32_pass_rwindow_to_system,
8696 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8698 When non-nil, the Start menu is opened by tapping the key.
8699 If you set this to nil, the right \"Windows\" key is processed by Emacs
8700 according to the value of `w32-rwindow-modifier', which see.
8702 Note that some combinations of the right \"Windows\" key with other keys are
8703 caught by Windows at low level, and so binding them in Emacs will have no
8704 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8705 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8706 the doc string of `w32-phantom-key-code'. */);
8707 Vw32_pass_rwindow_to_system = Qt;
8709 DEFVAR_LISP ("w32-phantom-key-code",
8710 &Vw32_phantom_key_code,
8711 doc: /* Virtual key code used to generate \"phantom\" key presses.
8712 Value is a number between 0 and 255.
8714 Phantom key presses are generated in order to stop the system from
8715 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8716 `w32-pass-rwindow-to-system' is nil. */);
8717 /* Although 255 is technically not a valid key code, it works and
8718 means that this hack won't interfere with any real key code. */
8719 XSETINT (Vw32_phantom_key_code, 255);
8721 DEFVAR_LISP ("w32-enable-num-lock",
8722 &Vw32_enable_num_lock,
8723 doc: /* If non-nil, the Num Lock key acts normally.
8724 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8725 Vw32_enable_num_lock = Qt;
8727 DEFVAR_LISP ("w32-enable-caps-lock",
8728 &Vw32_enable_caps_lock,
8729 doc: /* If non-nil, the Caps Lock key acts normally.
8730 Set to nil to handle Caps Lock as the `capslock' key. */);
8731 Vw32_enable_caps_lock = Qt;
8733 DEFVAR_LISP ("w32-scroll-lock-modifier",
8734 &Vw32_scroll_lock_modifier,
8735 doc: /* Modifier to use for the Scroll Lock ON state.
8736 The value can be hyper, super, meta, alt, control or shift for the
8737 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8738 Any other value will cause the Scroll Lock key to be ignored. */);
8739 Vw32_scroll_lock_modifier = Qt;
8741 DEFVAR_LISP ("w32-lwindow-modifier",
8742 &Vw32_lwindow_modifier,
8743 doc: /* Modifier to use for the left \"Windows\" key.
8744 The value can be hyper, super, meta, alt, control or shift for the
8745 respective modifier, or nil to appear as the `lwindow' key.
8746 Any other value will cause the key to be ignored. */);
8747 Vw32_lwindow_modifier = Qnil;
8749 DEFVAR_LISP ("w32-rwindow-modifier",
8750 &Vw32_rwindow_modifier,
8751 doc: /* Modifier to use for the right \"Windows\" key.
8752 The value can be hyper, super, meta, alt, control or shift for the
8753 respective modifier, or nil to appear as the `rwindow' key.
8754 Any other value will cause the key to be ignored. */);
8755 Vw32_rwindow_modifier = Qnil;
8757 DEFVAR_LISP ("w32-apps-modifier",
8758 &Vw32_apps_modifier,
8759 doc: /* Modifier to use for the \"Apps\" key.
8760 The value can be hyper, super, meta, alt, control or shift for the
8761 respective modifier, or nil to appear as the `apps' key.
8762 Any other value will cause the key to be ignored. */);
8763 Vw32_apps_modifier = Qnil;
8765 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
8766 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8767 w32_enable_synthesized_fonts = 0;
8769 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
8770 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8771 Vw32_enable_palette = Qt;
8773 DEFVAR_INT ("w32-mouse-button-tolerance",
8774 &w32_mouse_button_tolerance,
8775 doc: /* Analogue of double click interval for faking middle mouse events.
8776 The value is the minimum time in milliseconds that must elapse between
8777 left and right button down events before they are considered distinct events.
8778 If both mouse buttons are depressed within this interval, a middle mouse
8779 button down event is generated instead. */);
8780 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8782 DEFVAR_INT ("w32-mouse-move-interval",
8783 &w32_mouse_move_interval,
8784 doc: /* Minimum interval between mouse move events.
8785 The value is the minimum time in milliseconds that must elapse between
8786 successive mouse move (or scroll bar drag) events before they are
8787 reported as lisp events. */);
8788 w32_mouse_move_interval = 0;
8790 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8791 &w32_pass_extra_mouse_buttons_to_system,
8792 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8793 Recent versions of Windows support mice with up to five buttons.
8794 Since most applications don't support these extra buttons, most mouse
8795 drivers will allow you to map them to functions at the system level.
8796 If this variable is non-nil, Emacs will pass them on, allowing the
8797 system to handle them. */);
8798 w32_pass_extra_mouse_buttons_to_system = 0;
8800 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
8801 doc: /* The shape of the pointer when over text.
8802 Changing the value does not affect existing frames
8803 unless you set the mouse color. */);
8804 Vx_pointer_shape = Qnil;
8806 Vx_nontext_pointer_shape = Qnil;
8808 Vx_mode_pointer_shape = Qnil;
8810 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
8811 doc: /* The shape of the pointer when Emacs is busy.
8812 This variable takes effect when you create a new frame
8813 or when you set the mouse color. */);
8814 Vx_hourglass_pointer_shape = Qnil;
8816 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
8817 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
8818 display_hourglass_p = 1;
8820 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
8821 doc: /* *Seconds to wait before displaying an hourglass pointer.
8822 Value must be an integer or float. */);
8823 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
8825 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8826 &Vx_sensitive_text_pointer_shape,
8827 doc: /* The shape of the pointer when over mouse-sensitive text.
8828 This variable takes effect when you create a new frame
8829 or when you set the mouse color. */);
8830 Vx_sensitive_text_pointer_shape = Qnil;
8832 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8833 &Vx_window_horizontal_drag_shape,
8834 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8835 This variable takes effect when you create a new frame
8836 or when you set the mouse color. */);
8837 Vx_window_horizontal_drag_shape = Qnil;
8839 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
8840 doc: /* A string indicating the foreground color of the cursor box. */);
8841 Vx_cursor_fore_pixel = Qnil;
8843 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
8844 doc: /* Maximum size for tooltips.
8845 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8846 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8848 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
8849 doc: /* Non-nil if no window manager is in use.
8850 Emacs doesn't try to figure this out; this is always nil
8851 unless you set it to something else. */);
8852 /* We don't have any way to find this out, so set it to nil
8853 and maybe the user would like to set it to t. */
8854 Vx_no_window_manager = Qnil;
8856 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8857 &Vx_pixel_size_width_font_regexp,
8858 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8860 Since Emacs gets width of a font matching with this regexp from
8861 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8862 such a font. This is especially effective for such large fonts as
8863 Chinese, Japanese, and Korean. */);
8864 Vx_pixel_size_width_font_regexp = Qnil;
8866 DEFVAR_LISP ("w32-bdf-filename-alist",
8867 &Vw32_bdf_filename_alist,
8868 doc: /* List of bdf fonts and their corresponding filenames. */);
8869 Vw32_bdf_filename_alist = Qnil;
8871 DEFVAR_BOOL ("w32-strict-fontnames",
8872 &w32_strict_fontnames,
8873 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8874 Default is nil, which allows old fontnames that are not XLFD compliant,
8875 and allows third-party CJK display to work by specifying false charset
8876 fields to trick Emacs into translating to Big5, SJIS etc.
8877 Setting this to t will prevent wrong fonts being selected when
8878 fontsets are automatically created. */);
8879 w32_strict_fontnames = 0;
8881 DEFVAR_BOOL ("w32-strict-painting",
8882 &w32_strict_painting,
8883 doc: /* Non-nil means use strict rules for repainting frames.
8884 Set this to nil to get the old behavior for repainting; this should
8885 only be necessary if the default setting causes problems. */);
8886 w32_strict_painting = 1;
8888 DEFVAR_LISP ("w32-charset-info-alist",
8889 &Vw32_charset_info_alist,
8890 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
8891 Each entry should be of the form:
8893 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
8895 where CHARSET_NAME is a string used in font names to identify the charset,
8896 WINDOWS_CHARSET is a symbol that can be one of:
8897 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
8898 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
8899 w32-charset-chinesebig5,
8900 w32-charset-johab, w32-charset-hebrew,
8901 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
8902 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
8903 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
8904 w32-charset-unicode,
8905 or w32-charset-oem.
8906 CODEPAGE should be an integer specifying the codepage that should be used
8907 to display the character set, t to do no translation and output as Unicode,
8908 or nil to do no translation and output as 8 bit (or multibyte on far-east
8909 versions of Windows) characters. */);
8910 Vw32_charset_info_alist = Qnil;
8912 staticpro (&Qw32_charset_ansi);
8913 Qw32_charset_ansi = intern ("w32-charset-ansi");
8914 staticpro (&Qw32_charset_symbol);
8915 Qw32_charset_default = intern ("w32-charset-default");
8916 staticpro (&Qw32_charset_default);
8917 Qw32_charset_symbol = intern ("w32-charset-symbol");
8918 staticpro (&Qw32_charset_shiftjis);
8919 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
8920 staticpro (&Qw32_charset_hangeul);
8921 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
8922 staticpro (&Qw32_charset_chinesebig5);
8923 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
8924 staticpro (&Qw32_charset_gb2312);
8925 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
8926 staticpro (&Qw32_charset_oem);
8927 Qw32_charset_oem = intern ("w32-charset-oem");
8929 #ifdef JOHAB_CHARSET
8931 static int w32_extra_charsets_defined = 1;
8932 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
8933 doc: /* Internal variable. */);
8935 staticpro (&Qw32_charset_johab);
8936 Qw32_charset_johab = intern ("w32-charset-johab");
8937 staticpro (&Qw32_charset_easteurope);
8938 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
8939 staticpro (&Qw32_charset_turkish);
8940 Qw32_charset_turkish = intern ("w32-charset-turkish");
8941 staticpro (&Qw32_charset_baltic);
8942 Qw32_charset_baltic = intern ("w32-charset-baltic");
8943 staticpro (&Qw32_charset_russian);
8944 Qw32_charset_russian = intern ("w32-charset-russian");
8945 staticpro (&Qw32_charset_arabic);
8946 Qw32_charset_arabic = intern ("w32-charset-arabic");
8947 staticpro (&Qw32_charset_greek);
8948 Qw32_charset_greek = intern ("w32-charset-greek");
8949 staticpro (&Qw32_charset_hebrew);
8950 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
8951 staticpro (&Qw32_charset_vietnamese);
8952 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
8953 staticpro (&Qw32_charset_thai);
8954 Qw32_charset_thai = intern ("w32-charset-thai");
8955 staticpro (&Qw32_charset_mac);
8956 Qw32_charset_mac = intern ("w32-charset-mac");
8958 #endif
8960 #ifdef UNICODE_CHARSET
8962 static int w32_unicode_charset_defined = 1;
8963 DEFVAR_BOOL ("w32-unicode-charset-defined",
8964 &w32_unicode_charset_defined,
8965 doc: /* Internal variable. */);
8967 staticpro (&Qw32_charset_unicode);
8968 Qw32_charset_unicode = intern ("w32-charset-unicode");
8970 #endif
8972 #if 0 /* TODO: Port to W32 */
8973 defsubr (&Sx_change_window_property);
8974 defsubr (&Sx_delete_window_property);
8975 defsubr (&Sx_window_property);
8976 #endif
8977 defsubr (&Sxw_display_color_p);
8978 defsubr (&Sx_display_grayscale_p);
8979 defsubr (&Sxw_color_defined_p);
8980 defsubr (&Sxw_color_values);
8981 defsubr (&Sx_server_max_request_size);
8982 defsubr (&Sx_server_vendor);
8983 defsubr (&Sx_server_version);
8984 defsubr (&Sx_display_pixel_width);
8985 defsubr (&Sx_display_pixel_height);
8986 defsubr (&Sx_display_mm_width);
8987 defsubr (&Sx_display_mm_height);
8988 defsubr (&Sx_display_screens);
8989 defsubr (&Sx_display_planes);
8990 defsubr (&Sx_display_color_cells);
8991 defsubr (&Sx_display_visual_class);
8992 defsubr (&Sx_display_backing_store);
8993 defsubr (&Sx_display_save_under);
8994 defsubr (&Sx_create_frame);
8995 defsubr (&Sx_open_connection);
8996 defsubr (&Sx_close_connection);
8997 defsubr (&Sx_display_list);
8998 defsubr (&Sx_synchronize);
9000 /* W32 specific functions */
9002 defsubr (&Sw32_focus_frame);
9003 defsubr (&Sw32_select_font);
9004 defsubr (&Sw32_define_rgb_color);
9005 defsubr (&Sw32_default_color_map);
9006 defsubr (&Sw32_load_color_file);
9007 defsubr (&Sw32_send_sys_command);
9008 defsubr (&Sw32_shell_execute);
9009 defsubr (&Sw32_register_hot_key);
9010 defsubr (&Sw32_unregister_hot_key);
9011 defsubr (&Sw32_registered_hot_keys);
9012 defsubr (&Sw32_reconstruct_hot_key);
9013 defsubr (&Sw32_toggle_lock_key);
9014 defsubr (&Sw32_window_exists_p);
9015 defsubr (&Sw32_find_bdf_fonts);
9017 defsubr (&Sfile_system_info);
9018 defsubr (&Sdefault_printer_name);
9020 /* Setting callback functions for fontset handler. */
9021 get_font_info_func = w32_get_font_info;
9023 #if 0 /* This function pointer doesn't seem to be used anywhere.
9024 And the pointer assigned has the wrong type, anyway. */
9025 list_fonts_func = w32_list_fonts;
9026 #endif
9028 load_font_func = w32_load_font;
9029 find_ccl_program_func = w32_find_ccl_program;
9030 query_font_func = w32_query_font;
9031 set_frame_fontset_func = x_set_font;
9032 check_window_system_func = check_w32;
9035 hourglass_atimer = NULL;
9036 hourglass_shown_p = 0;
9037 defsubr (&Sx_show_tip);
9038 defsubr (&Sx_hide_tip);
9039 tip_timer = Qnil;
9040 staticpro (&tip_timer);
9041 tip_frame = Qnil;
9042 staticpro (&tip_frame);
9044 last_show_tip_args = Qnil;
9045 staticpro (&last_show_tip_args);
9047 defsubr (&Sx_file_dialog);
9052 globals_of_w32fns is used to initialize those global variables that
9053 must always be initialized on startup even when the global variable
9054 initialized is non zero (see the function main in emacs.c).
9055 globals_of_w32fns is called from syms_of_w32fns when the global
9056 variable initialized is 0 and directly from main when initialized
9057 is non zero.
9059 void globals_of_w32fns ()
9061 HMODULE user32_lib = GetModuleHandle ("user32.dll");
9063 TrackMouseEvent not available in all versions of Windows, so must load
9064 it dynamically. Do it once, here, instead of every time it is used.
9066 track_mouse_event_fn = (TrackMouseEvent_Proc)
9067 GetProcAddress (user32_lib, "TrackMouseEvent");
9068 /* ditto for GetClipboardSequenceNumber. */
9069 clipboard_sequence_fn = (ClipboardSequence_Proc)
9070 GetProcAddress (user32_lib, "GetClipboardSequenceNumber");
9072 DEFVAR_INT ("w32-ansi-code-page",
9073 &w32_ansi_code_page,
9074 doc: /* The ANSI code page used by the system. */);
9075 w32_ansi_code_page = GetACP ();
9078 #undef abort
9080 void w32_abort (void) NO_RETURN;
9082 void
9083 w32_abort()
9085 int button;
9086 button = MessageBox (NULL,
9087 "A fatal error has occurred!\n\n"
9088 "Would you like to attach a debugger?\n\n"
9089 "Select YES to debug, NO to abort Emacs"
9090 #if __GNUC__
9091 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
9092 "\"continue\" inside GDB before clicking YES.)"
9093 #endif
9094 , "Emacs Abort Dialog",
9095 MB_ICONEXCLAMATION | MB_TASKMODAL
9096 | MB_SETFOREGROUND | MB_YESNO);
9097 switch (button)
9099 case IDYES:
9100 DebugBreak ();
9101 exit (2); /* tell the compiler we will never return */
9102 case IDNO:
9103 default:
9104 abort ();
9105 break;
9109 /* For convenience when debugging. */
9111 w32_last_error()
9113 return GetLastError ();
9116 /* arch-tag: 707589ab-b9be-4638-8cdd-74629cc9b446
9117 (do not change this comment) */