(Button Types): For define-button-type, clarify type of NAME.
[emacs.git] / src / w32fns.c
blob6320fdf951ab8fd13a35c1b7a1af19e7a5a9939f
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, 2008
4 Free Software Foundation, Inc.
6 This file is part of GNU Emacs.
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
23 /* Added by Kevin Gallo */
25 #include <config.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <limits.h>
30 #include <errno.h>
31 #include <math.h>
33 #include "lisp.h"
34 #include "charset.h"
35 #include "dispextern.h"
36 #include "w32term.h"
37 #include "keyboard.h"
38 #include "frame.h"
39 #include "window.h"
40 #include "buffer.h"
41 #include "fontset.h"
42 #include "intervals.h"
43 #include "blockinput.h"
44 #include "epaths.h"
45 #include "w32heap.h"
46 #include "termhooks.h"
47 #include "coding.h"
48 #include "ccl.h"
49 #include "systime.h"
51 #include "bitmaps/gray.xbm"
53 #include <commctrl.h>
54 #include <commdlg.h>
55 #include <shellapi.h>
56 #include <ctype.h>
57 #include <winspool.h>
58 #include <objbase.h>
60 #include <dlgs.h>
61 #define FILE_NAME_TEXT_FIELD edt1
63 void syms_of_w32fns ();
64 void globals_of_w32fns ();
66 extern void free_frame_menubar ();
67 extern double atof ();
68 extern int w32_console_toggle_lock_key P_ ((int, Lisp_Object));
69 extern void w32_menu_display_help P_ ((HWND, HMENU, UINT, UINT));
70 extern void w32_free_menu_strings P_ ((HWND));
71 extern XCharStruct *w32_per_char_metric P_ ((XFontStruct *, wchar_t *, int));
73 extern int quit_char;
75 extern char *lispy_function_keys[];
77 /* The colormap for converting color names to RGB values */
78 Lisp_Object Vw32_color_map;
80 /* Non nil if alt key presses are passed on to Windows. */
81 Lisp_Object Vw32_pass_alt_to_system;
83 /* Non nil if alt key is translated to meta_modifier, nil if it is translated
84 to alt_modifier. */
85 Lisp_Object Vw32_alt_is_meta;
87 /* If non-zero, the windows virtual key code for an alternative quit key. */
88 int w32_quit_key;
90 /* Non nil if left window key events are passed on to Windows (this only
91 affects whether "tapping" the key opens the Start menu). */
92 Lisp_Object Vw32_pass_lwindow_to_system;
94 /* Non nil if right window key events are passed on to Windows (this
95 only affects whether "tapping" the key opens the Start menu). */
96 Lisp_Object Vw32_pass_rwindow_to_system;
98 /* Virtual key code used to generate "phantom" key presses in order
99 to stop system from acting on Windows key events. */
100 Lisp_Object Vw32_phantom_key_code;
102 /* Modifier associated with the left "Windows" key, or nil to act as a
103 normal key. */
104 Lisp_Object Vw32_lwindow_modifier;
106 /* Modifier associated with the right "Windows" key, or nil to act as a
107 normal key. */
108 Lisp_Object Vw32_rwindow_modifier;
110 /* Modifier associated with the "Apps" key, or nil to act as a normal
111 key. */
112 Lisp_Object Vw32_apps_modifier;
114 /* Value is nil if Num Lock acts as a function key. */
115 Lisp_Object Vw32_enable_num_lock;
117 /* Value is nil if Caps Lock acts as a function key. */
118 Lisp_Object Vw32_enable_caps_lock;
120 /* Modifier associated with Scroll Lock, or nil to act as a normal key. */
121 Lisp_Object Vw32_scroll_lock_modifier;
123 /* Switch to control whether we inhibit requests for synthesized bold
124 and italic versions of fonts. */
125 int w32_enable_synthesized_fonts;
127 /* Enable palette management. */
128 Lisp_Object Vw32_enable_palette;
130 /* Control how close left/right button down events must be to
131 be converted to a middle button down event. */
132 int w32_mouse_button_tolerance;
134 /* Minimum interval between mouse movement (and scroll bar drag)
135 events that are passed on to the event loop. */
136 int w32_mouse_move_interval;
138 /* Flag to indicate if XBUTTON events should be passed on to Windows. */
139 static int w32_pass_extra_mouse_buttons_to_system;
141 /* Flag to indicate if media keys should be passed on to Windows. */
142 static int w32_pass_multimedia_buttons_to_system;
144 /* Non nil if no window manager is in use. */
145 Lisp_Object Vx_no_window_manager;
147 /* Non-zero means we're allowed to display a hourglass pointer. */
149 int display_hourglass_p;
151 /* The background and shape of the mouse pointer, and shape when not
152 over text or in the modeline. */
154 Lisp_Object Vx_pointer_shape, Vx_nontext_pointer_shape, Vx_mode_pointer_shape;
155 Lisp_Object Vx_hourglass_pointer_shape, Vx_window_horizontal_drag_shape;
157 /* The shape when over mouse-sensitive text. */
159 Lisp_Object Vx_sensitive_text_pointer_shape;
161 #ifndef IDC_HAND
162 #define IDC_HAND MAKEINTRESOURCE(32649)
163 #endif
165 /* Color of chars displayed in cursor box. */
167 Lisp_Object Vx_cursor_fore_pixel;
169 /* Nonzero if using Windows. */
171 static int w32_in_use;
173 /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'. */
175 Lisp_Object Vx_pixel_size_width_font_regexp;
177 /* Alist of bdf fonts and the files that define them. */
178 Lisp_Object Vw32_bdf_filename_alist;
180 /* A flag to control whether fonts are matched strictly or not. */
181 static int w32_strict_fontnames;
183 /* A flag to control whether we should only repaint if GetUpdateRect
184 indicates there is an update region. */
185 static int w32_strict_painting;
187 /* Associative list linking character set strings to Windows codepages. */
188 static Lisp_Object Vw32_charset_info_alist;
190 /* VIETNAMESE_CHARSET is not defined in some versions of MSVC. */
191 #ifndef VIETNAMESE_CHARSET
192 #define VIETNAMESE_CHARSET 163
193 #endif
195 Lisp_Object Qnone;
196 Lisp_Object Qsuppress_icon;
197 Lisp_Object Qundefined_color;
198 Lisp_Object Qcancel_timer;
199 Lisp_Object Qhyper;
200 Lisp_Object Qsuper;
201 Lisp_Object Qmeta;
202 Lisp_Object Qalt;
203 Lisp_Object Qctrl;
204 Lisp_Object Qcontrol;
205 Lisp_Object Qshift;
207 Lisp_Object Qw32_charset_ansi;
208 Lisp_Object Qw32_charset_default;
209 Lisp_Object Qw32_charset_symbol;
210 Lisp_Object Qw32_charset_shiftjis;
211 Lisp_Object Qw32_charset_hangeul;
212 Lisp_Object Qw32_charset_gb2312;
213 Lisp_Object Qw32_charset_chinesebig5;
214 Lisp_Object Qw32_charset_oem;
216 #ifndef JOHAB_CHARSET
217 #define JOHAB_CHARSET 130
218 #endif
219 #ifdef JOHAB_CHARSET
220 Lisp_Object Qw32_charset_easteurope;
221 Lisp_Object Qw32_charset_turkish;
222 Lisp_Object Qw32_charset_baltic;
223 Lisp_Object Qw32_charset_russian;
224 Lisp_Object Qw32_charset_arabic;
225 Lisp_Object Qw32_charset_greek;
226 Lisp_Object Qw32_charset_hebrew;
227 Lisp_Object Qw32_charset_vietnamese;
228 Lisp_Object Qw32_charset_thai;
229 Lisp_Object Qw32_charset_johab;
230 Lisp_Object Qw32_charset_mac;
231 #endif
233 #ifdef UNICODE_CHARSET
234 Lisp_Object Qw32_charset_unicode;
235 #endif
237 /* The ANSI codepage. */
238 int w32_ansi_code_page;
240 /* Prefix for system colors. */
241 #define SYSTEM_COLOR_PREFIX "System"
242 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
244 /* State variables for emulating a three button mouse. */
245 #define LMOUSE 1
246 #define MMOUSE 2
247 #define RMOUSE 4
249 static int button_state = 0;
250 static W32Msg saved_mouse_button_msg;
251 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
252 static W32Msg saved_mouse_move_msg;
253 static unsigned mouse_move_timer = 0;
255 /* Window that is tracking the mouse. */
256 static HWND track_mouse_window;
258 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
259 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
261 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
262 ClipboardSequence_Proc clipboard_sequence_fn = NULL;
263 extern AppendMenuW_Proc unicode_append_menu;
265 /* W95 mousewheel handler */
266 unsigned int msh_mousewheel = 0;
268 /* Timers */
269 #define MOUSE_BUTTON_ID 1
270 #define MOUSE_MOVE_ID 2
271 #define MENU_FREE_ID 3
272 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
273 is received. */
274 #define MENU_FREE_DELAY 1000
275 static unsigned menu_free_timer = 0;
277 /* The below are defined in frame.c. */
279 extern Lisp_Object Vwindow_system_version;
281 #ifdef GLYPH_DEBUG
282 int image_cache_refcount, dpyinfo_refcount;
283 #endif
286 /* From w32term.c. */
287 extern int w32_num_mouse_buttons;
288 extern Lisp_Object Vw32_recognize_altgr;
290 extern HWND w32_system_caret_hwnd;
292 extern int w32_system_caret_height;
293 extern int w32_system_caret_x;
294 extern int w32_system_caret_y;
295 extern int w32_use_visible_system_caret;
297 static HWND w32_visible_system_caret_hwnd;
299 /* From w32menu.c */
300 extern HMENU current_popup_menu;
301 static int menubar_in_use = 0;
304 /* Error if we are not connected to MS-Windows. */
305 void
306 check_w32 ()
308 if (! w32_in_use)
309 error ("MS-Windows not in use or not initialized");
312 /* Nonzero if we can use mouse menus.
313 You should not call this unless HAVE_MENUS is defined. */
316 have_menus_p ()
318 return w32_in_use;
321 /* Extract a frame as a FRAME_PTR, defaulting to the selected frame
322 and checking validity for W32. */
324 FRAME_PTR
325 check_x_frame (frame)
326 Lisp_Object frame;
328 FRAME_PTR f;
330 if (NILP (frame))
331 frame = selected_frame;
332 CHECK_LIVE_FRAME (frame);
333 f = XFRAME (frame);
334 if (! FRAME_W32_P (f))
335 error ("Non-W32 frame used");
336 return f;
339 /* Let the user specify a display with a frame.
340 nil stands for the selected frame--or, if that is not a w32 frame,
341 the first display on the list. */
343 struct w32_display_info *
344 check_x_display_info (frame)
345 Lisp_Object frame;
347 if (NILP (frame))
349 struct frame *sf = XFRAME (selected_frame);
351 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
352 return FRAME_W32_DISPLAY_INFO (sf);
353 else
354 return &one_w32_display_info;
356 else if (STRINGP (frame))
357 return x_display_info_for_name (frame);
358 else
360 FRAME_PTR f;
362 CHECK_LIVE_FRAME (frame);
363 f = XFRAME (frame);
364 if (! FRAME_W32_P (f))
365 error ("Non-W32 frame used");
366 return FRAME_W32_DISPLAY_INFO (f);
370 /* Return the Emacs frame-object corresponding to an w32 window.
371 It could be the frame's main window or an icon window. */
373 /* This function can be called during GC, so use GC_xxx type test macros. */
375 struct frame *
376 x_window_to_frame (dpyinfo, wdesc)
377 struct w32_display_info *dpyinfo;
378 HWND wdesc;
380 Lisp_Object tail, frame;
381 struct frame *f;
383 for (tail = Vframe_list; GC_CONSP (tail); tail = XCDR (tail))
385 frame = XCAR (tail);
386 if (!GC_FRAMEP (frame))
387 continue;
388 f = XFRAME (frame);
389 if (!FRAME_W32_P (f) || FRAME_W32_DISPLAY_INFO (f) != dpyinfo)
390 continue;
391 if (f->output_data.w32->hourglass_window == wdesc)
392 return f;
394 if (FRAME_W32_WINDOW (f) == wdesc)
395 return f;
397 return 0;
401 static Lisp_Object unwind_create_frame P_ ((Lisp_Object));
402 static Lisp_Object unwind_create_tip_frame P_ ((Lisp_Object));
403 static void my_create_window P_ ((struct frame *));
404 static void my_create_tip_window P_ ((struct frame *));
406 /* TODO: Native Input Method support; see x_create_im. */
407 void x_set_foreground_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
408 void x_set_background_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
409 void x_set_mouse_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
410 void x_set_cursor_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
411 void x_set_border_color P_ ((struct frame *, Lisp_Object, Lisp_Object));
412 void x_set_cursor_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
413 void x_set_icon_type P_ ((struct frame *, Lisp_Object, Lisp_Object));
414 void x_set_icon_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
415 void x_explicitly_set_name P_ ((struct frame *, Lisp_Object, Lisp_Object));
416 void x_set_menu_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
417 void x_set_title P_ ((struct frame *, Lisp_Object, Lisp_Object));
418 void x_set_tool_bar_lines P_ ((struct frame *, Lisp_Object, Lisp_Object));
419 static void x_edge_detection P_ ((struct frame *, struct image *, Lisp_Object,
420 Lisp_Object));
425 /* Store the screen positions of frame F into XPTR and YPTR.
426 These are the positions of the containing window manager window,
427 not Emacs's own window. */
429 void
430 x_real_positions (f, xptr, yptr)
431 FRAME_PTR f;
432 int *xptr, *yptr;
434 POINT pt;
435 RECT rect;
437 /* Get the bounds of the WM window. */
438 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
440 pt.x = 0;
441 pt.y = 0;
443 /* Convert (0, 0) in the client area to screen co-ordinates. */
444 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
446 /* Remember x_pixels_diff and y_pixels_diff. */
447 f->x_pixels_diff = pt.x - rect.left;
448 f->y_pixels_diff = pt.y - rect.top;
450 *xptr = rect.left;
451 *yptr = rect.top;
456 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
457 Sw32_define_rgb_color, 4, 4, 0,
458 doc: /* Convert RGB numbers to a windows color reference and associate with NAME.
459 This adds or updates a named color to `w32-color-map', making it
460 available for use. The original entry's RGB ref is returned, or nil
461 if the entry is new. */)
462 (red, green, blue, name)
463 Lisp_Object red, green, blue, name;
465 Lisp_Object rgb;
466 Lisp_Object oldrgb = Qnil;
467 Lisp_Object entry;
469 CHECK_NUMBER (red);
470 CHECK_NUMBER (green);
471 CHECK_NUMBER (blue);
472 CHECK_STRING (name);
474 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
476 BLOCK_INPUT;
478 /* replace existing entry in w32-color-map or add new entry. */
479 entry = Fassoc (name, Vw32_color_map);
480 if (NILP (entry))
482 entry = Fcons (name, rgb);
483 Vw32_color_map = Fcons (entry, Vw32_color_map);
485 else
487 oldrgb = Fcdr (entry);
488 Fsetcdr (entry, rgb);
491 UNBLOCK_INPUT;
493 return (oldrgb);
496 DEFUN ("w32-load-color-file", Fw32_load_color_file,
497 Sw32_load_color_file, 1, 1, 0,
498 doc: /* Create an alist of color entries from an external file.
499 Assign this value to `w32-color-map' to replace the existing color map.
501 The file should define one named RGB color per line like so:
502 R G B name
503 where R,G,B are numbers between 0 and 255 and name is an arbitrary string. */)
504 (filename)
505 Lisp_Object filename;
507 FILE *fp;
508 Lisp_Object cmap = Qnil;
509 Lisp_Object abspath;
511 CHECK_STRING (filename);
512 abspath = Fexpand_file_name (filename, Qnil);
514 fp = fopen (SDATA (filename), "rt");
515 if (fp)
517 char buf[512];
518 int red, green, blue;
519 int num;
521 BLOCK_INPUT;
523 while (fgets (buf, sizeof (buf), fp) != NULL) {
524 if (sscanf (buf, "%u %u %u %n", &red, &green, &blue, &num) == 3)
526 char *name = buf + num;
527 num = strlen (name) - 1;
528 if (name[num] == '\n')
529 name[num] = 0;
530 cmap = Fcons (Fcons (build_string (name),
531 make_number (RGB (red, green, blue))),
532 cmap);
535 fclose (fp);
537 UNBLOCK_INPUT;
540 return cmap;
543 /* The default colors for the w32 color map */
544 typedef struct colormap_t
546 char *name;
547 COLORREF colorref;
548 } colormap_t;
550 colormap_t w32_color_map[] =
552 {"snow" , PALETTERGB (255,250,250)},
553 {"ghost white" , PALETTERGB (248,248,255)},
554 {"GhostWhite" , PALETTERGB (248,248,255)},
555 {"white smoke" , PALETTERGB (245,245,245)},
556 {"WhiteSmoke" , PALETTERGB (245,245,245)},
557 {"gainsboro" , PALETTERGB (220,220,220)},
558 {"floral white" , PALETTERGB (255,250,240)},
559 {"FloralWhite" , PALETTERGB (255,250,240)},
560 {"old lace" , PALETTERGB (253,245,230)},
561 {"OldLace" , PALETTERGB (253,245,230)},
562 {"linen" , PALETTERGB (250,240,230)},
563 {"antique white" , PALETTERGB (250,235,215)},
564 {"AntiqueWhite" , PALETTERGB (250,235,215)},
565 {"papaya whip" , PALETTERGB (255,239,213)},
566 {"PapayaWhip" , PALETTERGB (255,239,213)},
567 {"blanched almond" , PALETTERGB (255,235,205)},
568 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
569 {"bisque" , PALETTERGB (255,228,196)},
570 {"peach puff" , PALETTERGB (255,218,185)},
571 {"PeachPuff" , PALETTERGB (255,218,185)},
572 {"navajo white" , PALETTERGB (255,222,173)},
573 {"NavajoWhite" , PALETTERGB (255,222,173)},
574 {"moccasin" , PALETTERGB (255,228,181)},
575 {"cornsilk" , PALETTERGB (255,248,220)},
576 {"ivory" , PALETTERGB (255,255,240)},
577 {"lemon chiffon" , PALETTERGB (255,250,205)},
578 {"LemonChiffon" , PALETTERGB (255,250,205)},
579 {"seashell" , PALETTERGB (255,245,238)},
580 {"honeydew" , PALETTERGB (240,255,240)},
581 {"mint cream" , PALETTERGB (245,255,250)},
582 {"MintCream" , PALETTERGB (245,255,250)},
583 {"azure" , PALETTERGB (240,255,255)},
584 {"alice blue" , PALETTERGB (240,248,255)},
585 {"AliceBlue" , PALETTERGB (240,248,255)},
586 {"lavender" , PALETTERGB (230,230,250)},
587 {"lavender blush" , PALETTERGB (255,240,245)},
588 {"LavenderBlush" , PALETTERGB (255,240,245)},
589 {"misty rose" , PALETTERGB (255,228,225)},
590 {"MistyRose" , PALETTERGB (255,228,225)},
591 {"white" , PALETTERGB (255,255,255)},
592 {"black" , PALETTERGB ( 0, 0, 0)},
593 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
594 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
595 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
596 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
597 {"dim gray" , PALETTERGB (105,105,105)},
598 {"DimGray" , PALETTERGB (105,105,105)},
599 {"dim grey" , PALETTERGB (105,105,105)},
600 {"DimGrey" , PALETTERGB (105,105,105)},
601 {"slate gray" , PALETTERGB (112,128,144)},
602 {"SlateGray" , PALETTERGB (112,128,144)},
603 {"slate grey" , PALETTERGB (112,128,144)},
604 {"SlateGrey" , PALETTERGB (112,128,144)},
605 {"light slate gray" , PALETTERGB (119,136,153)},
606 {"LightSlateGray" , PALETTERGB (119,136,153)},
607 {"light slate grey" , PALETTERGB (119,136,153)},
608 {"LightSlateGrey" , PALETTERGB (119,136,153)},
609 {"gray" , PALETTERGB (190,190,190)},
610 {"grey" , PALETTERGB (190,190,190)},
611 {"light grey" , PALETTERGB (211,211,211)},
612 {"LightGrey" , PALETTERGB (211,211,211)},
613 {"light gray" , PALETTERGB (211,211,211)},
614 {"LightGray" , PALETTERGB (211,211,211)},
615 {"midnight blue" , PALETTERGB ( 25, 25,112)},
616 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
617 {"navy" , PALETTERGB ( 0, 0,128)},
618 {"navy blue" , PALETTERGB ( 0, 0,128)},
619 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
620 {"cornflower blue" , PALETTERGB (100,149,237)},
621 {"CornflowerBlue" , PALETTERGB (100,149,237)},
622 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
623 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
624 {"slate blue" , PALETTERGB (106, 90,205)},
625 {"SlateBlue" , PALETTERGB (106, 90,205)},
626 {"medium slate blue" , PALETTERGB (123,104,238)},
627 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
628 {"light slate blue" , PALETTERGB (132,112,255)},
629 {"LightSlateBlue" , PALETTERGB (132,112,255)},
630 {"medium blue" , PALETTERGB ( 0, 0,205)},
631 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
632 {"royal blue" , PALETTERGB ( 65,105,225)},
633 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
634 {"blue" , PALETTERGB ( 0, 0,255)},
635 {"dodger blue" , PALETTERGB ( 30,144,255)},
636 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
637 {"deep sky blue" , PALETTERGB ( 0,191,255)},
638 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
639 {"sky blue" , PALETTERGB (135,206,235)},
640 {"SkyBlue" , PALETTERGB (135,206,235)},
641 {"light sky blue" , PALETTERGB (135,206,250)},
642 {"LightSkyBlue" , PALETTERGB (135,206,250)},
643 {"steel blue" , PALETTERGB ( 70,130,180)},
644 {"SteelBlue" , PALETTERGB ( 70,130,180)},
645 {"light steel blue" , PALETTERGB (176,196,222)},
646 {"LightSteelBlue" , PALETTERGB (176,196,222)},
647 {"light blue" , PALETTERGB (173,216,230)},
648 {"LightBlue" , PALETTERGB (173,216,230)},
649 {"powder blue" , PALETTERGB (176,224,230)},
650 {"PowderBlue" , PALETTERGB (176,224,230)},
651 {"pale turquoise" , PALETTERGB (175,238,238)},
652 {"PaleTurquoise" , PALETTERGB (175,238,238)},
653 {"dark turquoise" , PALETTERGB ( 0,206,209)},
654 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
655 {"medium turquoise" , PALETTERGB ( 72,209,204)},
656 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
657 {"turquoise" , PALETTERGB ( 64,224,208)},
658 {"cyan" , PALETTERGB ( 0,255,255)},
659 {"light cyan" , PALETTERGB (224,255,255)},
660 {"LightCyan" , PALETTERGB (224,255,255)},
661 {"cadet blue" , PALETTERGB ( 95,158,160)},
662 {"CadetBlue" , PALETTERGB ( 95,158,160)},
663 {"medium aquamarine" , PALETTERGB (102,205,170)},
664 {"MediumAquamarine" , PALETTERGB (102,205,170)},
665 {"aquamarine" , PALETTERGB (127,255,212)},
666 {"dark green" , PALETTERGB ( 0,100, 0)},
667 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
668 {"dark olive green" , PALETTERGB ( 85,107, 47)},
669 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
670 {"dark sea green" , PALETTERGB (143,188,143)},
671 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
672 {"sea green" , PALETTERGB ( 46,139, 87)},
673 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
674 {"medium sea green" , PALETTERGB ( 60,179,113)},
675 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
676 {"light sea green" , PALETTERGB ( 32,178,170)},
677 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
678 {"pale green" , PALETTERGB (152,251,152)},
679 {"PaleGreen" , PALETTERGB (152,251,152)},
680 {"spring green" , PALETTERGB ( 0,255,127)},
681 {"SpringGreen" , PALETTERGB ( 0,255,127)},
682 {"lawn green" , PALETTERGB (124,252, 0)},
683 {"LawnGreen" , PALETTERGB (124,252, 0)},
684 {"green" , PALETTERGB ( 0,255, 0)},
685 {"chartreuse" , PALETTERGB (127,255, 0)},
686 {"medium spring green" , PALETTERGB ( 0,250,154)},
687 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
688 {"green yellow" , PALETTERGB (173,255, 47)},
689 {"GreenYellow" , PALETTERGB (173,255, 47)},
690 {"lime green" , PALETTERGB ( 50,205, 50)},
691 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
692 {"yellow green" , PALETTERGB (154,205, 50)},
693 {"YellowGreen" , PALETTERGB (154,205, 50)},
694 {"forest green" , PALETTERGB ( 34,139, 34)},
695 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
696 {"olive drab" , PALETTERGB (107,142, 35)},
697 {"OliveDrab" , PALETTERGB (107,142, 35)},
698 {"dark khaki" , PALETTERGB (189,183,107)},
699 {"DarkKhaki" , PALETTERGB (189,183,107)},
700 {"khaki" , PALETTERGB (240,230,140)},
701 {"pale goldenrod" , PALETTERGB (238,232,170)},
702 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
703 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
704 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
705 {"light yellow" , PALETTERGB (255,255,224)},
706 {"LightYellow" , PALETTERGB (255,255,224)},
707 {"yellow" , PALETTERGB (255,255, 0)},
708 {"gold" , PALETTERGB (255,215, 0)},
709 {"light goldenrod" , PALETTERGB (238,221,130)},
710 {"LightGoldenrod" , PALETTERGB (238,221,130)},
711 {"goldenrod" , PALETTERGB (218,165, 32)},
712 {"dark goldenrod" , PALETTERGB (184,134, 11)},
713 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
714 {"rosy brown" , PALETTERGB (188,143,143)},
715 {"RosyBrown" , PALETTERGB (188,143,143)},
716 {"indian red" , PALETTERGB (205, 92, 92)},
717 {"IndianRed" , PALETTERGB (205, 92, 92)},
718 {"saddle brown" , PALETTERGB (139, 69, 19)},
719 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
720 {"sienna" , PALETTERGB (160, 82, 45)},
721 {"peru" , PALETTERGB (205,133, 63)},
722 {"burlywood" , PALETTERGB (222,184,135)},
723 {"beige" , PALETTERGB (245,245,220)},
724 {"wheat" , PALETTERGB (245,222,179)},
725 {"sandy brown" , PALETTERGB (244,164, 96)},
726 {"SandyBrown" , PALETTERGB (244,164, 96)},
727 {"tan" , PALETTERGB (210,180,140)},
728 {"chocolate" , PALETTERGB (210,105, 30)},
729 {"firebrick" , PALETTERGB (178,34, 34)},
730 {"brown" , PALETTERGB (165,42, 42)},
731 {"dark salmon" , PALETTERGB (233,150,122)},
732 {"DarkSalmon" , PALETTERGB (233,150,122)},
733 {"salmon" , PALETTERGB (250,128,114)},
734 {"light salmon" , PALETTERGB (255,160,122)},
735 {"LightSalmon" , PALETTERGB (255,160,122)},
736 {"orange" , PALETTERGB (255,165, 0)},
737 {"dark orange" , PALETTERGB (255,140, 0)},
738 {"DarkOrange" , PALETTERGB (255,140, 0)},
739 {"coral" , PALETTERGB (255,127, 80)},
740 {"light coral" , PALETTERGB (240,128,128)},
741 {"LightCoral" , PALETTERGB (240,128,128)},
742 {"tomato" , PALETTERGB (255, 99, 71)},
743 {"orange red" , PALETTERGB (255, 69, 0)},
744 {"OrangeRed" , PALETTERGB (255, 69, 0)},
745 {"red" , PALETTERGB (255, 0, 0)},
746 {"hot pink" , PALETTERGB (255,105,180)},
747 {"HotPink" , PALETTERGB (255,105,180)},
748 {"deep pink" , PALETTERGB (255, 20,147)},
749 {"DeepPink" , PALETTERGB (255, 20,147)},
750 {"pink" , PALETTERGB (255,192,203)},
751 {"light pink" , PALETTERGB (255,182,193)},
752 {"LightPink" , PALETTERGB (255,182,193)},
753 {"pale violet red" , PALETTERGB (219,112,147)},
754 {"PaleVioletRed" , PALETTERGB (219,112,147)},
755 {"maroon" , PALETTERGB (176, 48, 96)},
756 {"medium violet red" , PALETTERGB (199, 21,133)},
757 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
758 {"violet red" , PALETTERGB (208, 32,144)},
759 {"VioletRed" , PALETTERGB (208, 32,144)},
760 {"magenta" , PALETTERGB (255, 0,255)},
761 {"violet" , PALETTERGB (238,130,238)},
762 {"plum" , PALETTERGB (221,160,221)},
763 {"orchid" , PALETTERGB (218,112,214)},
764 {"medium orchid" , PALETTERGB (186, 85,211)},
765 {"MediumOrchid" , PALETTERGB (186, 85,211)},
766 {"dark orchid" , PALETTERGB (153, 50,204)},
767 {"DarkOrchid" , PALETTERGB (153, 50,204)},
768 {"dark violet" , PALETTERGB (148, 0,211)},
769 {"DarkViolet" , PALETTERGB (148, 0,211)},
770 {"blue violet" , PALETTERGB (138, 43,226)},
771 {"BlueViolet" , PALETTERGB (138, 43,226)},
772 {"purple" , PALETTERGB (160, 32,240)},
773 {"medium purple" , PALETTERGB (147,112,219)},
774 {"MediumPurple" , PALETTERGB (147,112,219)},
775 {"thistle" , PALETTERGB (216,191,216)},
776 {"gray0" , PALETTERGB ( 0, 0, 0)},
777 {"grey0" , PALETTERGB ( 0, 0, 0)},
778 {"dark grey" , PALETTERGB (169,169,169)},
779 {"DarkGrey" , PALETTERGB (169,169,169)},
780 {"dark gray" , PALETTERGB (169,169,169)},
781 {"DarkGray" , PALETTERGB (169,169,169)},
782 {"dark blue" , PALETTERGB ( 0, 0,139)},
783 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
784 {"dark cyan" , PALETTERGB ( 0,139,139)},
785 {"DarkCyan" , PALETTERGB ( 0,139,139)},
786 {"dark magenta" , PALETTERGB (139, 0,139)},
787 {"DarkMagenta" , PALETTERGB (139, 0,139)},
788 {"dark red" , PALETTERGB (139, 0, 0)},
789 {"DarkRed" , PALETTERGB (139, 0, 0)},
790 {"light green" , PALETTERGB (144,238,144)},
791 {"LightGreen" , PALETTERGB (144,238,144)},
794 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
795 0, 0, 0, doc: /* Return the default color map. */)
798 int i;
799 colormap_t *pc = w32_color_map;
800 Lisp_Object cmap;
802 BLOCK_INPUT;
804 cmap = Qnil;
806 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
807 pc++, i++)
808 cmap = Fcons (Fcons (build_string (pc->name),
809 make_number (pc->colorref)),
810 cmap);
812 UNBLOCK_INPUT;
814 return (cmap);
817 static Lisp_Object
818 w32_to_x_color (rgb)
819 Lisp_Object rgb;
821 Lisp_Object color;
823 CHECK_NUMBER (rgb);
825 BLOCK_INPUT;
827 color = Frassq (rgb, Vw32_color_map);
829 UNBLOCK_INPUT;
831 if (!NILP (color))
832 return (Fcar (color));
833 else
834 return Qnil;
837 static Lisp_Object
838 w32_color_map_lookup (colorname)
839 char *colorname;
841 Lisp_Object tail, ret = Qnil;
843 BLOCK_INPUT;
845 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
847 register Lisp_Object elt, tem;
849 elt = XCAR (tail);
850 if (!CONSP (elt)) continue;
852 tem = Fcar (elt);
854 if (lstrcmpi (SDATA (tem), colorname) == 0)
856 ret = Fcdr (elt);
857 break;
860 QUIT;
864 UNBLOCK_INPUT;
866 return ret;
870 static void
871 add_system_logical_colors_to_map (system_colors)
872 Lisp_Object *system_colors;
874 HKEY colors_key;
876 /* Other registry operations are done with input blocked. */
877 BLOCK_INPUT;
879 /* Look for "Control Panel/Colors" under User and Machine registry
880 settings. */
881 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
882 KEY_READ, &colors_key) == ERROR_SUCCESS
883 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
884 KEY_READ, &colors_key) == ERROR_SUCCESS)
886 /* List all keys. */
887 char color_buffer[64];
888 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
889 int index = 0;
890 DWORD name_size, color_size;
891 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
893 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
894 color_size = sizeof (color_buffer);
896 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
898 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
899 NULL, NULL, color_buffer, &color_size)
900 == ERROR_SUCCESS)
902 int r, g, b;
903 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
904 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
905 make_number (RGB (r, g, b))),
906 *system_colors);
908 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
909 color_size = sizeof (color_buffer);
910 index++;
912 RegCloseKey (colors_key);
915 UNBLOCK_INPUT;
919 static Lisp_Object
920 x_to_w32_color (colorname)
921 char * colorname;
923 register Lisp_Object ret = Qnil;
925 BLOCK_INPUT;
927 if (colorname[0] == '#')
929 /* Could be an old-style RGB Device specification. */
930 char *color;
931 int size;
932 color = colorname + 1;
934 size = strlen (color);
935 if (size == 3 || size == 6 || size == 9 || size == 12)
937 UINT colorval;
938 int i, pos;
939 pos = 0;
940 size /= 3;
941 colorval = 0;
943 for (i = 0; i < 3; i++)
945 char *end;
946 char t;
947 unsigned long value;
949 /* The check for 'x' in the following conditional takes into
950 account the fact that strtol allows a "0x" in front of
951 our numbers, and we don't. */
952 if (!isxdigit (color[0]) || color[1] == 'x')
953 break;
954 t = color[size];
955 color[size] = '\0';
956 value = strtoul (color, &end, 16);
957 color[size] = t;
958 if (errno == ERANGE || end - color != size)
959 break;
960 switch (size)
962 case 1:
963 value = value * 0x10;
964 break;
965 case 2:
966 break;
967 case 3:
968 value /= 0x10;
969 break;
970 case 4:
971 value /= 0x100;
972 break;
974 colorval |= (value << pos);
975 pos += 0x8;
976 if (i == 2)
978 UNBLOCK_INPUT;
979 XSETINT (ret, colorval);
980 return ret;
982 color = end;
986 else if (strnicmp (colorname, "rgb:", 4) == 0)
988 char *color;
989 UINT colorval;
990 int i, pos;
991 pos = 0;
993 colorval = 0;
994 color = colorname + 4;
995 for (i = 0; i < 3; i++)
997 char *end;
998 unsigned long value;
1000 /* The check for 'x' in the following conditional takes into
1001 account the fact that strtol allows a "0x" in front of
1002 our numbers, and we don't. */
1003 if (!isxdigit (color[0]) || color[1] == 'x')
1004 break;
1005 value = strtoul (color, &end, 16);
1006 if (errno == ERANGE)
1007 break;
1008 switch (end - color)
1010 case 1:
1011 value = value * 0x10 + value;
1012 break;
1013 case 2:
1014 break;
1015 case 3:
1016 value /= 0x10;
1017 break;
1018 case 4:
1019 value /= 0x100;
1020 break;
1021 default:
1022 value = ULONG_MAX;
1024 if (value == ULONG_MAX)
1025 break;
1026 colorval |= (value << pos);
1027 pos += 0x8;
1028 if (i == 2)
1030 if (*end != '\0')
1031 break;
1032 UNBLOCK_INPUT;
1033 XSETINT (ret, colorval);
1034 return ret;
1036 if (*end != '/')
1037 break;
1038 color = end + 1;
1041 else if (strnicmp (colorname, "rgbi:", 5) == 0)
1043 /* This is an RGB Intensity specification. */
1044 char *color;
1045 UINT colorval;
1046 int i, pos;
1047 pos = 0;
1049 colorval = 0;
1050 color = colorname + 5;
1051 for (i = 0; i < 3; i++)
1053 char *end;
1054 double value;
1055 UINT val;
1057 value = strtod (color, &end);
1058 if (errno == ERANGE)
1059 break;
1060 if (value < 0.0 || value > 1.0)
1061 break;
1062 val = (UINT)(0x100 * value);
1063 /* We used 0x100 instead of 0xFF to give a continuous
1064 range between 0.0 and 1.0 inclusive. The next statement
1065 fixes the 1.0 case. */
1066 if (val == 0x100)
1067 val = 0xFF;
1068 colorval |= (val << pos);
1069 pos += 0x8;
1070 if (i == 2)
1072 if (*end != '\0')
1073 break;
1074 UNBLOCK_INPUT;
1075 XSETINT (ret, colorval);
1076 return ret;
1078 if (*end != '/')
1079 break;
1080 color = end + 1;
1083 /* I am not going to attempt to handle any of the CIE color schemes
1084 or TekHVC, since I don't know the algorithms for conversion to
1085 RGB. */
1087 /* If we fail to lookup the color name in w32_color_map, then check the
1088 colorname to see if it can be crudely approximated: If the X color
1089 ends in a number (e.g., "darkseagreen2"), strip the number and
1090 return the result of looking up the base color name. */
1091 ret = w32_color_map_lookup (colorname);
1092 if (NILP (ret))
1094 int len = strlen (colorname);
1096 if (isdigit (colorname[len - 1]))
1098 char *ptr, *approx = alloca (len + 1);
1100 strcpy (approx, colorname);
1101 ptr = &approx[len - 1];
1102 while (ptr > approx && isdigit (*ptr))
1103 *ptr-- = '\0';
1105 ret = w32_color_map_lookup (approx);
1109 UNBLOCK_INPUT;
1110 return ret;
1113 void
1114 w32_regenerate_palette (FRAME_PTR f)
1116 struct w32_palette_entry * list;
1117 LOGPALETTE * log_palette;
1118 HPALETTE new_palette;
1119 int i;
1121 /* don't bother trying to create palette if not supported */
1122 if (! FRAME_W32_DISPLAY_INFO (f)->has_palette)
1123 return;
1125 log_palette = (LOGPALETTE *)
1126 alloca (sizeof (LOGPALETTE) +
1127 FRAME_W32_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1128 log_palette->palVersion = 0x300;
1129 log_palette->palNumEntries = FRAME_W32_DISPLAY_INFO (f)->num_colors;
1131 list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1132 for (i = 0;
1133 i < FRAME_W32_DISPLAY_INFO (f)->num_colors;
1134 i++, list = list->next)
1135 log_palette->palPalEntry[i] = list->entry;
1137 new_palette = CreatePalette (log_palette);
1139 enter_crit ();
1141 if (FRAME_W32_DISPLAY_INFO (f)->palette)
1142 DeleteObject (FRAME_W32_DISPLAY_INFO (f)->palette);
1143 FRAME_W32_DISPLAY_INFO (f)->palette = new_palette;
1145 /* Realize display palette and garbage all frames. */
1146 release_frame_dc (f, get_frame_dc (f));
1148 leave_crit ();
1151 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1152 #define SET_W32_COLOR(pe, color) \
1153 do \
1155 pe.peRed = GetRValue (color); \
1156 pe.peGreen = GetGValue (color); \
1157 pe.peBlue = GetBValue (color); \
1158 pe.peFlags = 0; \
1159 } while (0)
1161 #if 0
1162 /* Keep these around in case we ever want to track color usage. */
1163 void
1164 w32_map_color (FRAME_PTR f, COLORREF color)
1166 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1168 if (NILP (Vw32_enable_palette))
1169 return;
1171 /* check if color is already mapped */
1172 while (list)
1174 if (W32_COLOR (list->entry) == color)
1176 ++list->refcount;
1177 return;
1179 list = list->next;
1182 /* not already mapped, so add to list and recreate Windows palette */
1183 list = (struct w32_palette_entry *)
1184 xmalloc (sizeof (struct w32_palette_entry));
1185 SET_W32_COLOR (list->entry, color);
1186 list->refcount = 1;
1187 list->next = FRAME_W32_DISPLAY_INFO (f)->color_list;
1188 FRAME_W32_DISPLAY_INFO (f)->color_list = list;
1189 FRAME_W32_DISPLAY_INFO (f)->num_colors++;
1191 /* set flag that palette must be regenerated */
1192 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1195 void
1196 w32_unmap_color (FRAME_PTR f, COLORREF color)
1198 struct w32_palette_entry * list = FRAME_W32_DISPLAY_INFO (f)->color_list;
1199 struct w32_palette_entry **prev = &FRAME_W32_DISPLAY_INFO (f)->color_list;
1201 if (NILP (Vw32_enable_palette))
1202 return;
1204 /* check if color is already mapped */
1205 while (list)
1207 if (W32_COLOR (list->entry) == color)
1209 if (--list->refcount == 0)
1211 *prev = list->next;
1212 xfree (list);
1213 FRAME_W32_DISPLAY_INFO (f)->num_colors--;
1214 break;
1216 else
1217 return;
1219 prev = &list->next;
1220 list = list->next;
1223 /* set flag that palette must be regenerated */
1224 FRAME_W32_DISPLAY_INFO (f)->regen_palette = TRUE;
1226 #endif
1229 /* Gamma-correct COLOR on frame F. */
1231 void
1232 gamma_correct (f, color)
1233 struct frame *f;
1234 COLORREF *color;
1236 if (f->gamma)
1238 *color = PALETTERGB (
1239 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1240 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1241 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1246 /* Decide if color named COLOR is valid for the display associated with
1247 the selected frame; if so, return the rgb values in COLOR_DEF.
1248 If ALLOC is nonzero, allocate a new colormap cell. */
1251 w32_defined_color (f, color, color_def, alloc)
1252 FRAME_PTR f;
1253 char *color;
1254 XColor *color_def;
1255 int alloc;
1257 register Lisp_Object tem;
1258 COLORREF w32_color_ref;
1260 tem = x_to_w32_color (color);
1262 if (!NILP (tem))
1264 if (f)
1266 /* Apply gamma correction. */
1267 w32_color_ref = XUINT (tem);
1268 gamma_correct (f, &w32_color_ref);
1269 XSETINT (tem, w32_color_ref);
1272 /* Map this color to the palette if it is enabled. */
1273 if (!NILP (Vw32_enable_palette))
1275 struct w32_palette_entry * entry =
1276 one_w32_display_info.color_list;
1277 struct w32_palette_entry ** prev =
1278 &one_w32_display_info.color_list;
1280 /* check if color is already mapped */
1281 while (entry)
1283 if (W32_COLOR (entry->entry) == XUINT (tem))
1284 break;
1285 prev = &entry->next;
1286 entry = entry->next;
1289 if (entry == NULL && alloc)
1291 /* not already mapped, so add to list */
1292 entry = (struct w32_palette_entry *)
1293 xmalloc (sizeof (struct w32_palette_entry));
1294 SET_W32_COLOR (entry->entry, XUINT (tem));
1295 entry->next = NULL;
1296 *prev = entry;
1297 one_w32_display_info.num_colors++;
1299 /* set flag that palette must be regenerated */
1300 one_w32_display_info.regen_palette = TRUE;
1303 /* Ensure COLORREF value is snapped to nearest color in (default)
1304 palette by simulating the PALETTERGB macro. This works whether
1305 or not the display device has a palette. */
1306 w32_color_ref = XUINT (tem) | 0x2000000;
1308 color_def->pixel = w32_color_ref;
1309 color_def->red = GetRValue (w32_color_ref) * 256;
1310 color_def->green = GetGValue (w32_color_ref) * 256;
1311 color_def->blue = GetBValue (w32_color_ref) * 256;
1313 return 1;
1315 else
1317 return 0;
1321 /* Given a string ARG naming a color, compute a pixel value from it
1322 suitable for screen F.
1323 If F is not a color screen, return DEF (default) regardless of what
1324 ARG says. */
1327 x_decode_color (f, arg, def)
1328 FRAME_PTR f;
1329 Lisp_Object arg;
1330 int def;
1332 XColor cdef;
1334 CHECK_STRING (arg);
1336 if (strcmp (SDATA (arg), "black") == 0)
1337 return BLACK_PIX_DEFAULT (f);
1338 else if (strcmp (SDATA (arg), "white") == 0)
1339 return WHITE_PIX_DEFAULT (f);
1341 if ((FRAME_W32_DISPLAY_INFO (f)->n_planes * FRAME_W32_DISPLAY_INFO (f)->n_cbits) == 1)
1342 return def;
1344 /* w32_defined_color is responsible for coping with failures
1345 by looking for a near-miss. */
1346 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1347 return cdef.pixel;
1349 /* defined_color failed; return an ultimate default. */
1350 return def;
1355 /* Functions called only from `x_set_frame_param'
1356 to set individual parameters.
1358 If FRAME_W32_WINDOW (f) is 0,
1359 the frame is being created and its window does not exist yet.
1360 In that case, just record the parameter's new value
1361 in the standard place; do not attempt to change the window. */
1363 void
1364 x_set_foreground_color (f, arg, oldval)
1365 struct frame *f;
1366 Lisp_Object arg, oldval;
1368 struct w32_output *x = f->output_data.w32;
1369 PIX_TYPE fg, old_fg;
1371 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1372 old_fg = FRAME_FOREGROUND_PIXEL (f);
1373 FRAME_FOREGROUND_PIXEL (f) = fg;
1375 if (FRAME_W32_WINDOW (f) != 0)
1377 if (x->cursor_pixel == old_fg)
1378 x->cursor_pixel = fg;
1380 update_face_from_frame_parameter (f, Qforeground_color, arg);
1381 if (FRAME_VISIBLE_P (f))
1382 redraw_frame (f);
1386 void
1387 x_set_background_color (f, arg, oldval)
1388 struct frame *f;
1389 Lisp_Object arg, oldval;
1391 FRAME_BACKGROUND_PIXEL (f)
1392 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1394 if (FRAME_W32_WINDOW (f) != 0)
1396 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1397 FRAME_BACKGROUND_PIXEL (f));
1399 update_face_from_frame_parameter (f, Qbackground_color, arg);
1401 if (FRAME_VISIBLE_P (f))
1402 redraw_frame (f);
1406 void
1407 x_set_mouse_color (f, arg, oldval)
1408 struct frame *f;
1409 Lisp_Object arg, oldval;
1411 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1412 int count;
1413 int mask_color;
1415 if (!EQ (Qnil, arg))
1416 f->output_data.w32->mouse_pixel
1417 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1418 mask_color = FRAME_BACKGROUND_PIXEL (f);
1420 /* Don't let pointers be invisible. */
1421 if (mask_color == f->output_data.w32->mouse_pixel
1422 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1423 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1425 #if 0 /* TODO : cursor changes */
1426 BLOCK_INPUT;
1428 /* It's not okay to crash if the user selects a screwy cursor. */
1429 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1431 if (!EQ (Qnil, Vx_pointer_shape))
1433 CHECK_NUMBER (Vx_pointer_shape);
1434 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1436 else
1437 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1438 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1440 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1442 CHECK_NUMBER (Vx_nontext_pointer_shape);
1443 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1444 XINT (Vx_nontext_pointer_shape));
1446 else
1447 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1448 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1450 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1452 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1453 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1454 XINT (Vx_hourglass_pointer_shape));
1456 else
1457 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1458 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1460 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1461 if (!EQ (Qnil, Vx_mode_pointer_shape))
1463 CHECK_NUMBER (Vx_mode_pointer_shape);
1464 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1465 XINT (Vx_mode_pointer_shape));
1467 else
1468 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1469 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1471 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1473 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1474 hand_cursor
1475 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1476 XINT (Vx_sensitive_text_pointer_shape));
1478 else
1479 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1481 if (!NILP (Vx_window_horizontal_drag_shape))
1483 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1484 horizontal_drag_cursor
1485 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1486 XINT (Vx_window_horizontal_drag_shape));
1488 else
1489 horizontal_drag_cursor
1490 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1492 /* Check and report errors with the above calls. */
1493 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1494 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1497 XColor fore_color, back_color;
1499 fore_color.pixel = f->output_data.w32->mouse_pixel;
1500 back_color.pixel = mask_color;
1501 XQueryColor (FRAME_W32_DISPLAY (f),
1502 DefaultColormap (FRAME_W32_DISPLAY (f),
1503 DefaultScreen (FRAME_W32_DISPLAY (f))),
1504 &fore_color);
1505 XQueryColor (FRAME_W32_DISPLAY (f),
1506 DefaultColormap (FRAME_W32_DISPLAY (f),
1507 DefaultScreen (FRAME_W32_DISPLAY (f))),
1508 &back_color);
1509 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1510 &fore_color, &back_color);
1511 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1512 &fore_color, &back_color);
1513 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1514 &fore_color, &back_color);
1515 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1516 &fore_color, &back_color);
1517 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1518 &fore_color, &back_color);
1521 if (FRAME_W32_WINDOW (f) != 0)
1522 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1524 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1525 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1526 f->output_data.w32->text_cursor = cursor;
1528 if (nontext_cursor != f->output_data.w32->nontext_cursor
1529 && f->output_data.w32->nontext_cursor != 0)
1530 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1531 f->output_data.w32->nontext_cursor = nontext_cursor;
1533 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1534 && f->output_data.w32->hourglass_cursor != 0)
1535 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1536 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1538 if (mode_cursor != f->output_data.w32->modeline_cursor
1539 && f->output_data.w32->modeline_cursor != 0)
1540 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1541 f->output_data.w32->modeline_cursor = mode_cursor;
1543 if (hand_cursor != f->output_data.w32->hand_cursor
1544 && f->output_data.w32->hand_cursor != 0)
1545 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1546 f->output_data.w32->hand_cursor = hand_cursor;
1548 XFlush (FRAME_W32_DISPLAY (f));
1549 UNBLOCK_INPUT;
1551 update_face_from_frame_parameter (f, Qmouse_color, arg);
1552 #endif /* TODO */
1555 void
1556 x_set_cursor_color (f, arg, oldval)
1557 struct frame *f;
1558 Lisp_Object arg, oldval;
1560 unsigned long fore_pixel, pixel;
1562 if (!NILP (Vx_cursor_fore_pixel))
1563 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1564 WHITE_PIX_DEFAULT (f));
1565 else
1566 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1568 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1570 /* Make sure that the cursor color differs from the background color. */
1571 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1573 pixel = f->output_data.w32->mouse_pixel;
1574 if (pixel == fore_pixel)
1575 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1578 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1579 f->output_data.w32->cursor_pixel = pixel;
1581 if (FRAME_W32_WINDOW (f) != 0)
1583 BLOCK_INPUT;
1584 /* Update frame's cursor_gc. */
1585 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1586 f->output_data.w32->cursor_gc->background = pixel;
1588 UNBLOCK_INPUT;
1590 if (FRAME_VISIBLE_P (f))
1592 x_update_cursor (f, 0);
1593 x_update_cursor (f, 1);
1597 update_face_from_frame_parameter (f, Qcursor_color, arg);
1600 /* Set the border-color of frame F to pixel value PIX.
1601 Note that this does not fully take effect if done before
1602 F has a window. */
1604 void
1605 x_set_border_pixel (f, pix)
1606 struct frame *f;
1607 int pix;
1610 f->output_data.w32->border_pixel = pix;
1612 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1614 if (FRAME_VISIBLE_P (f))
1615 redraw_frame (f);
1619 /* Set the border-color of frame F to value described by ARG.
1620 ARG can be a string naming a color.
1621 The border-color is used for the border that is drawn by the server.
1622 Note that this does not fully take effect if done before
1623 F has a window; it must be redone when the window is created. */
1625 void
1626 x_set_border_color (f, arg, oldval)
1627 struct frame *f;
1628 Lisp_Object arg, oldval;
1630 int pix;
1632 CHECK_STRING (arg);
1633 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1634 x_set_border_pixel (f, pix);
1635 update_face_from_frame_parameter (f, Qborder_color, arg);
1639 void
1640 x_set_cursor_type (f, arg, oldval)
1641 FRAME_PTR f;
1642 Lisp_Object arg, oldval;
1644 set_frame_cursor_types (f, arg);
1646 /* Make sure the cursor gets redrawn. */
1647 cursor_type_changed = 1;
1650 void
1651 x_set_icon_type (f, arg, oldval)
1652 struct frame *f;
1653 Lisp_Object arg, oldval;
1655 int result;
1657 if (NILP (arg) && NILP (oldval))
1658 return;
1660 if (STRINGP (arg) && STRINGP (oldval)
1661 && EQ (Fstring_equal (oldval, arg), Qt))
1662 return;
1664 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1665 return;
1667 BLOCK_INPUT;
1669 result = x_bitmap_icon (f, arg);
1670 if (result)
1672 UNBLOCK_INPUT;
1673 error ("No icon window available");
1676 UNBLOCK_INPUT;
1679 void
1680 x_set_icon_name (f, arg, oldval)
1681 struct frame *f;
1682 Lisp_Object arg, oldval;
1684 if (STRINGP (arg))
1686 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1687 return;
1689 else if (!NILP (arg) || NILP (oldval))
1690 return;
1692 f->icon_name = arg;
1694 #if 0
1695 if (f->output_data.w32->icon_bitmap != 0)
1696 return;
1698 BLOCK_INPUT;
1700 result = x_text_icon (f,
1701 (char *) SDATA ((!NILP (f->icon_name)
1702 ? f->icon_name
1703 : !NILP (f->title)
1704 ? f->title
1705 : f->name)));
1707 if (result)
1709 UNBLOCK_INPUT;
1710 error ("No icon window available");
1713 /* If the window was unmapped (and its icon was mapped),
1714 the new icon is not mapped, so map the window in its stead. */
1715 if (FRAME_VISIBLE_P (f))
1717 #ifdef USE_X_TOOLKIT
1718 XtPopup (f->output_data.w32->widget, XtGrabNone);
1719 #endif
1720 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1723 XFlush (FRAME_W32_DISPLAY (f));
1724 UNBLOCK_INPUT;
1725 #endif
1729 void
1730 x_set_menu_bar_lines (f, value, oldval)
1731 struct frame *f;
1732 Lisp_Object value, oldval;
1734 int nlines;
1735 int olines = FRAME_MENU_BAR_LINES (f);
1737 /* Right now, menu bars don't work properly in minibuf-only frames;
1738 most of the commands try to apply themselves to the minibuffer
1739 frame itself, and get an error because you can't switch buffers
1740 in or split the minibuffer window. */
1741 if (FRAME_MINIBUF_ONLY_P (f))
1742 return;
1744 if (INTEGERP (value))
1745 nlines = XINT (value);
1746 else
1747 nlines = 0;
1749 FRAME_MENU_BAR_LINES (f) = 0;
1750 if (nlines)
1751 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1752 else
1754 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1755 free_frame_menubar (f);
1756 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1758 /* Adjust the frame size so that the client (text) dimensions
1759 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1760 set correctly. */
1761 x_set_window_size (f, 0, FRAME_COLS (f), FRAME_LINES (f));
1762 do_pending_window_change (0);
1764 adjust_glyphs (f);
1768 /* Set the number of lines used for the tool bar of frame F to VALUE.
1769 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL
1770 is the old number of tool bar lines. This function changes the
1771 height of all windows on frame F to match the new tool bar height.
1772 The frame's height doesn't change. */
1774 void
1775 x_set_tool_bar_lines (f, value, oldval)
1776 struct frame *f;
1777 Lisp_Object value, oldval;
1779 int delta, nlines, root_height;
1780 Lisp_Object root_window;
1782 /* Treat tool bars like menu bars. */
1783 if (FRAME_MINIBUF_ONLY_P (f))
1784 return;
1786 /* Use VALUE only if an integer >= 0. */
1787 if (INTEGERP (value) && XINT (value) >= 0)
1788 nlines = XFASTINT (value);
1789 else
1790 nlines = 0;
1792 /* Make sure we redisplay all windows in this frame. */
1793 ++windows_or_buffers_changed;
1795 delta = nlines - FRAME_TOOL_BAR_LINES (f);
1797 /* Don't resize the tool-bar to more than we have room for. */
1798 root_window = FRAME_ROOT_WINDOW (f);
1799 root_height = WINDOW_TOTAL_LINES (XWINDOW (root_window));
1800 if (root_height - delta < 1)
1802 delta = root_height - 1;
1803 nlines = FRAME_TOOL_BAR_LINES (f) + delta;
1806 FRAME_TOOL_BAR_LINES (f) = nlines;
1807 change_window_heights (root_window, delta);
1808 adjust_glyphs (f);
1810 /* We also have to make sure that the internal border at the top of
1811 the frame, below the menu bar or tool bar, is redrawn when the
1812 tool bar disappears. This is so because the internal border is
1813 below the tool bar if one is displayed, but is below the menu bar
1814 if there isn't a tool bar. The tool bar draws into the area
1815 below the menu bar. */
1816 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_LINES (f) == 0)
1818 clear_frame (f);
1819 clear_current_matrices (f);
1822 /* If the tool bar gets smaller, the internal border below it
1823 has to be cleared. It was formerly part of the display
1824 of the larger tool bar, and updating windows won't clear it. */
1825 if (delta < 0)
1827 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1828 int width = FRAME_PIXEL_WIDTH (f);
1829 int y = nlines * FRAME_LINE_HEIGHT (f);
1831 BLOCK_INPUT;
1833 HDC hdc = get_frame_dc (f);
1834 w32_clear_area (f, hdc, 0, y, width, height);
1835 release_frame_dc (f, hdc);
1837 UNBLOCK_INPUT;
1839 if (WINDOWP (f->tool_bar_window))
1840 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1845 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1846 w32_id_name.
1848 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1849 name; if NAME is a string, set F's name to NAME and set
1850 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1852 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1853 suggesting a new name, which lisp code should override; if
1854 F->explicit_name is set, ignore the new name; otherwise, set it. */
1856 void
1857 x_set_name (f, name, explicit)
1858 struct frame *f;
1859 Lisp_Object name;
1860 int explicit;
1862 /* Make sure that requests from lisp code override requests from
1863 Emacs redisplay code. */
1864 if (explicit)
1866 /* If we're switching from explicit to implicit, we had better
1867 update the mode lines and thereby update the title. */
1868 if (f->explicit_name && NILP (name))
1869 update_mode_lines = 1;
1871 f->explicit_name = ! NILP (name);
1873 else if (f->explicit_name)
1874 return;
1876 /* If NAME is nil, set the name to the w32_id_name. */
1877 if (NILP (name))
1879 /* Check for no change needed in this very common case
1880 before we do any consing. */
1881 if (!strcmp (FRAME_W32_DISPLAY_INFO (f)->w32_id_name,
1882 SDATA (f->name)))
1883 return;
1884 name = build_string (FRAME_W32_DISPLAY_INFO (f)->w32_id_name);
1886 else
1887 CHECK_STRING (name);
1889 /* Don't change the name if it's already NAME. */
1890 if (! NILP (Fstring_equal (name, f->name)))
1891 return;
1893 f->name = name;
1895 /* For setting the frame title, the title parameter should override
1896 the name parameter. */
1897 if (! NILP (f->title))
1898 name = f->title;
1900 if (FRAME_W32_WINDOW (f))
1902 if (STRING_MULTIBYTE (name))
1903 name = ENCODE_SYSTEM (name);
1905 BLOCK_INPUT;
1906 SetWindowText (FRAME_W32_WINDOW (f), SDATA (name));
1907 UNBLOCK_INPUT;
1911 /* This function should be called when the user's lisp code has
1912 specified a name for the frame; the name will override any set by the
1913 redisplay code. */
1914 void
1915 x_explicitly_set_name (f, arg, oldval)
1916 FRAME_PTR f;
1917 Lisp_Object arg, oldval;
1919 x_set_name (f, arg, 1);
1922 /* This function should be called by Emacs redisplay code to set the
1923 name; names set this way will never override names set by the user's
1924 lisp code. */
1925 void
1926 x_implicitly_set_name (f, arg, oldval)
1927 FRAME_PTR f;
1928 Lisp_Object arg, oldval;
1930 x_set_name (f, arg, 0);
1933 /* Change the title of frame F to NAME.
1934 If NAME is nil, use the frame name as the title. */
1936 void
1937 x_set_title (f, name, old_name)
1938 struct frame *f;
1939 Lisp_Object name, old_name;
1941 /* Don't change the title if it's already NAME. */
1942 if (EQ (name, f->title))
1943 return;
1945 update_mode_lines = 1;
1947 f->title = name;
1949 if (NILP (name))
1950 name = f->name;
1952 if (FRAME_W32_WINDOW (f))
1954 if (STRING_MULTIBYTE (name))
1955 name = ENCODE_SYSTEM (name);
1957 BLOCK_INPUT;
1958 SetWindowText (FRAME_W32_WINDOW (f), SDATA (name));
1959 UNBLOCK_INPUT;
1964 void x_set_scroll_bar_default_width (f)
1965 struct frame *f;
1967 int wid = FRAME_COLUMN_WIDTH (f);
1969 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1970 FRAME_CONFIG_SCROLL_BAR_COLS (f) = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) +
1971 wid - 1) / wid;
1975 /* Subroutines of creating a frame. */
1978 /* Return the value of parameter PARAM.
1980 First search ALIST, then Vdefault_frame_alist, then the X defaults
1981 database, using ATTRIBUTE as the attribute name and CLASS as its class.
1983 Convert the resource to the type specified by desired_type.
1985 If no default is specified, return Qunbound. If you call
1986 w32_get_arg, make sure you deal with Qunbound in a reasonable way,
1987 and don't let it get stored in any Lisp-visible variables! */
1989 static Lisp_Object
1990 w32_get_arg (alist, param, attribute, class, type)
1991 Lisp_Object alist, param;
1992 char *attribute;
1993 char *class;
1994 enum resource_types type;
1996 return x_get_arg (check_x_display_info (Qnil),
1997 alist, param, attribute, class, type);
2001 Cursor
2002 w32_load_cursor (LPCTSTR name)
2004 /* Try first to load cursor from application resource. */
2005 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
2006 name, IMAGE_CURSOR, 0, 0,
2007 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2008 if (!cursor)
2010 /* Then try to load a shared predefined cursor. */
2011 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
2012 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2014 return cursor;
2017 extern LRESULT CALLBACK w32_wnd_proc ();
2019 static BOOL
2020 w32_init_class (hinst)
2021 HINSTANCE hinst;
2023 WNDCLASS wc;
2025 wc.style = CS_HREDRAW | CS_VREDRAW;
2026 wc.lpfnWndProc = (WNDPROC) w32_wnd_proc;
2027 wc.cbClsExtra = 0;
2028 wc.cbWndExtra = WND_EXTRA_BYTES;
2029 wc.hInstance = hinst;
2030 wc.hIcon = LoadIcon (hinst, EMACS_CLASS);
2031 wc.hCursor = w32_load_cursor (IDC_ARROW);
2032 wc.hbrBackground = NULL; /* GetStockObject (WHITE_BRUSH); */
2033 wc.lpszMenuName = NULL;
2034 wc.lpszClassName = EMACS_CLASS;
2036 return (RegisterClass (&wc));
2039 static HWND
2040 w32_createscrollbar (f, bar)
2041 struct frame *f;
2042 struct scroll_bar * bar;
2044 return (CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2045 /* Position and size of scroll bar. */
2046 XINT (bar->left) + VERTICAL_SCROLL_BAR_WIDTH_TRIM,
2047 XINT (bar->top),
2048 XINT (bar->width) - VERTICAL_SCROLL_BAR_WIDTH_TRIM * 2,
2049 XINT (bar->height),
2050 FRAME_W32_WINDOW (f),
2051 NULL,
2052 hinst,
2053 NULL));
2056 static void
2057 w32_createwindow (f)
2058 struct frame *f;
2060 HWND hwnd;
2061 RECT rect;
2062 Lisp_Object top = Qunbound;
2063 Lisp_Object left = Qunbound;
2065 rect.left = rect.top = 0;
2066 rect.right = FRAME_PIXEL_WIDTH (f);
2067 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2069 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2070 FRAME_EXTERNAL_MENU_BAR (f));
2072 /* Do first time app init */
2074 if (!hprevinst)
2076 w32_init_class (hinst);
2079 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2081 XSETINT (left, f->left_pos);
2082 XSETINT (top, f->top_pos);
2084 else if (EQ (left, Qunbound) && EQ (top, Qunbound))
2086 /* When called with RES_TYPE_NUMBER, w32_get_arg will return zero
2087 for anything that is not a number and is not Qunbound. */
2088 left = w32_get_arg (Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
2089 top = w32_get_arg (Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
2092 FRAME_W32_WINDOW (f) = hwnd
2093 = CreateWindow (EMACS_CLASS,
2094 f->namebuf,
2095 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2096 EQ (left, Qunbound) ? CW_USEDEFAULT : XINT (left),
2097 EQ (top, Qunbound) ? CW_USEDEFAULT : XINT (top),
2098 rect.right - rect.left,
2099 rect.bottom - rect.top,
2100 NULL,
2101 NULL,
2102 hinst,
2103 NULL);
2105 if (hwnd)
2107 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2108 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2109 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2110 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, f->scroll_bar_actual_width);
2111 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2113 /* Enable drag-n-drop. */
2114 DragAcceptFiles (hwnd, TRUE);
2116 /* Do this to discard the default setting specified by our parent. */
2117 ShowWindow (hwnd, SW_HIDE);
2119 /* Update frame positions. */
2120 GetWindowRect (hwnd, &rect);
2121 f->left_pos = rect.left;
2122 f->top_pos = rect.top;
2126 static void
2127 my_post_msg (wmsg, hwnd, msg, wParam, lParam)
2128 W32Msg * wmsg;
2129 HWND hwnd;
2130 UINT msg;
2131 WPARAM wParam;
2132 LPARAM lParam;
2134 wmsg->msg.hwnd = hwnd;
2135 wmsg->msg.message = msg;
2136 wmsg->msg.wParam = wParam;
2137 wmsg->msg.lParam = lParam;
2138 wmsg->msg.time = GetMessageTime ();
2140 post_msg (wmsg);
2143 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2144 between left and right keys as advertised. We test for this
2145 support dynamically, and set a flag when the support is absent. If
2146 absent, we keep track of the left and right control and alt keys
2147 ourselves. This is particularly necessary on keyboards that rely
2148 upon the AltGr key, which is represented as having the left control
2149 and right alt keys pressed. For these keyboards, we need to know
2150 when the left alt key has been pressed in addition to the AltGr key
2151 so that we can properly support M-AltGr-key sequences (such as M-@
2152 on Swedish keyboards). */
2154 #define EMACS_LCONTROL 0
2155 #define EMACS_RCONTROL 1
2156 #define EMACS_LMENU 2
2157 #define EMACS_RMENU 3
2159 static int modifiers[4];
2160 static int modifiers_recorded;
2161 static int modifier_key_support_tested;
2163 static void
2164 test_modifier_support (unsigned int wparam)
2166 unsigned int l, r;
2168 if (wparam != VK_CONTROL && wparam != VK_MENU)
2169 return;
2170 if (wparam == VK_CONTROL)
2172 l = VK_LCONTROL;
2173 r = VK_RCONTROL;
2175 else
2177 l = VK_LMENU;
2178 r = VK_RMENU;
2180 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2181 modifiers_recorded = 1;
2182 else
2183 modifiers_recorded = 0;
2184 modifier_key_support_tested = 1;
2187 static void
2188 record_keydown (unsigned int wparam, unsigned int lparam)
2190 int i;
2192 if (!modifier_key_support_tested)
2193 test_modifier_support (wparam);
2195 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2196 return;
2198 if (wparam == VK_CONTROL)
2199 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2200 else
2201 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2203 modifiers[i] = 1;
2206 static void
2207 record_keyup (unsigned int wparam, unsigned int lparam)
2209 int i;
2211 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2212 return;
2214 if (wparam == VK_CONTROL)
2215 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2216 else
2217 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2219 modifiers[i] = 0;
2222 /* Emacs can lose focus while a modifier key has been pressed. When
2223 it regains focus, be conservative and clear all modifiers since
2224 we cannot reconstruct the left and right modifier state. */
2225 static void
2226 reset_modifiers ()
2228 SHORT ctrl, alt;
2230 if (GetFocus () == NULL)
2231 /* Emacs doesn't have keyboard focus. Do nothing. */
2232 return;
2234 ctrl = GetAsyncKeyState (VK_CONTROL);
2235 alt = GetAsyncKeyState (VK_MENU);
2237 if (!(ctrl & 0x08000))
2238 /* Clear any recorded control modifier state. */
2239 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2241 if (!(alt & 0x08000))
2242 /* Clear any recorded alt modifier state. */
2243 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2245 /* Update the state of all modifier keys, because modifiers used in
2246 hot-key combinations can get stuck on if Emacs loses focus as a
2247 result of a hot-key being pressed. */
2249 BYTE keystate[256];
2251 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2253 GetKeyboardState (keystate);
2254 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2255 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2256 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2257 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2258 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2259 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2260 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2261 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2262 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2263 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2264 SetKeyboardState (keystate);
2268 /* Synchronize modifier state with what is reported with the current
2269 keystroke. Even if we cannot distinguish between left and right
2270 modifier keys, we know that, if no modifiers are set, then neither
2271 the left or right modifier should be set. */
2272 static void
2273 sync_modifiers ()
2275 if (!modifiers_recorded)
2276 return;
2278 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2279 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2281 if (!(GetKeyState (VK_MENU) & 0x8000))
2282 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2285 static int
2286 modifier_set (int vkey)
2288 if (vkey == VK_CAPITAL || vkey == VK_SCROLL)
2289 return (GetKeyState (vkey) & 0x1);
2290 if (!modifiers_recorded)
2291 return (GetKeyState (vkey) & 0x8000);
2293 switch (vkey)
2295 case VK_LCONTROL:
2296 return modifiers[EMACS_LCONTROL];
2297 case VK_RCONTROL:
2298 return modifiers[EMACS_RCONTROL];
2299 case VK_LMENU:
2300 return modifiers[EMACS_LMENU];
2301 case VK_RMENU:
2302 return modifiers[EMACS_RMENU];
2304 return (GetKeyState (vkey) & 0x8000);
2307 /* Convert between the modifier bits W32 uses and the modifier bits
2308 Emacs uses. */
2310 unsigned int
2311 w32_key_to_modifier (int key)
2313 Lisp_Object key_mapping;
2315 switch (key)
2317 case VK_LWIN:
2318 key_mapping = Vw32_lwindow_modifier;
2319 break;
2320 case VK_RWIN:
2321 key_mapping = Vw32_rwindow_modifier;
2322 break;
2323 case VK_APPS:
2324 key_mapping = Vw32_apps_modifier;
2325 break;
2326 case VK_SCROLL:
2327 key_mapping = Vw32_scroll_lock_modifier;
2328 break;
2329 default:
2330 key_mapping = Qnil;
2333 /* NB. This code runs in the input thread, asychronously to the lisp
2334 thread, so we must be careful to ensure access to lisp data is
2335 thread-safe. The following code is safe because the modifier
2336 variable values are updated atomically from lisp and symbols are
2337 not relocated by GC. Also, we don't have to worry about seeing GC
2338 markbits here. */
2339 if (EQ (key_mapping, Qhyper))
2340 return hyper_modifier;
2341 if (EQ (key_mapping, Qsuper))
2342 return super_modifier;
2343 if (EQ (key_mapping, Qmeta))
2344 return meta_modifier;
2345 if (EQ (key_mapping, Qalt))
2346 return alt_modifier;
2347 if (EQ (key_mapping, Qctrl))
2348 return ctrl_modifier;
2349 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2350 return ctrl_modifier;
2351 if (EQ (key_mapping, Qshift))
2352 return shift_modifier;
2354 /* Don't generate any modifier if not explicitly requested. */
2355 return 0;
2358 static unsigned int
2359 w32_get_modifiers ()
2361 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2362 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2363 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2364 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2365 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2366 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2367 (modifier_set (VK_MENU) ?
2368 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2371 /* We map the VK_* modifiers into console modifier constants
2372 so that we can use the same routines to handle both console
2373 and window input. */
2375 static int
2376 construct_console_modifiers ()
2378 int mods;
2380 mods = 0;
2381 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2382 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2383 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2384 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2385 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2386 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2387 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2388 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2389 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2390 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2391 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2393 return mods;
2396 static int
2397 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2399 int mods;
2401 /* Convert to emacs modifiers. */
2402 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2404 return mods;
2407 unsigned int
2408 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2410 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2411 return virt_key;
2413 if (virt_key == VK_RETURN)
2414 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2416 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2417 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2419 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2420 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2422 if (virt_key == VK_CLEAR)
2423 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2425 return virt_key;
2428 /* List of special key combinations which w32 would normally capture,
2429 but Emacs should grab instead. Not directly visible to lisp, to
2430 simplify synchronization. Each item is an integer encoding a virtual
2431 key code and modifier combination to capture. */
2432 static Lisp_Object w32_grabbed_keys;
2434 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2435 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2436 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2437 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2439 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2440 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2441 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2443 /* Register hot-keys for reserved key combinations when Emacs has
2444 keyboard focus, since this is the only way Emacs can receive key
2445 combinations like Alt-Tab which are used by the system. */
2447 static void
2448 register_hot_keys (hwnd)
2449 HWND hwnd;
2451 Lisp_Object keylist;
2453 /* Use GC_CONSP, since we are called asynchronously. */
2454 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2456 Lisp_Object key = XCAR (keylist);
2458 /* Deleted entries get set to nil. */
2459 if (!INTEGERP (key))
2460 continue;
2462 RegisterHotKey (hwnd, HOTKEY_ID (key),
2463 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2467 static void
2468 unregister_hot_keys (hwnd)
2469 HWND hwnd;
2471 Lisp_Object keylist;
2473 /* Use GC_CONSP, since we are called asynchronously. */
2474 for (keylist = w32_grabbed_keys; GC_CONSP (keylist); keylist = XCDR (keylist))
2476 Lisp_Object key = XCAR (keylist);
2478 if (!INTEGERP (key))
2479 continue;
2481 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2485 /* Main message dispatch loop. */
2487 static void
2488 w32_msg_pump (deferred_msg * msg_buf)
2490 MSG msg;
2491 int result;
2492 HWND focus_window;
2494 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2496 while (GetMessage (&msg, NULL, 0, 0))
2498 if (msg.hwnd == NULL)
2500 switch (msg.message)
2502 case WM_NULL:
2503 /* Produced by complete_deferred_msg; just ignore. */
2504 break;
2505 case WM_EMACS_CREATEWINDOW:
2506 /* Initialize COM for this window. Even though we don't use it,
2507 some third party shell extensions can cause it to be used in
2508 system dialogs, which causes a crash if it is not initialized.
2509 This is a known bug in Windows, which was fixed long ago, but
2510 the patch for XP is not publically available until XP SP3,
2511 and older versions will never be patched. */
2512 CoInitialize (NULL);
2513 w32_createwindow ((struct frame *) msg.wParam);
2514 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2515 abort ();
2516 break;
2517 case WM_EMACS_SETLOCALE:
2518 SetThreadLocale (msg.wParam);
2519 /* Reply is not expected. */
2520 break;
2521 case WM_EMACS_SETKEYBOARDLAYOUT:
2522 result = (int) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2523 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2524 result, 0))
2525 abort ();
2526 break;
2527 case WM_EMACS_REGISTER_HOT_KEY:
2528 focus_window = GetFocus ();
2529 if (focus_window != NULL)
2530 RegisterHotKey (focus_window,
2531 RAW_HOTKEY_ID (msg.wParam),
2532 RAW_HOTKEY_MODIFIERS (msg.wParam),
2533 RAW_HOTKEY_VK_CODE (msg.wParam));
2534 /* Reply is not expected. */
2535 break;
2536 case WM_EMACS_UNREGISTER_HOT_KEY:
2537 focus_window = GetFocus ();
2538 if (focus_window != NULL)
2539 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2540 /* Mark item as erased. NB: this code must be
2541 thread-safe. The next line is okay because the cons
2542 cell is never made into garbage and is not relocated by
2543 GC. */
2544 XSETCAR ((Lisp_Object) ((EMACS_INT) msg.lParam), Qnil);
2545 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2546 abort ();
2547 break;
2548 case WM_EMACS_TOGGLE_LOCK_KEY:
2550 int vk_code = (int) msg.wParam;
2551 int cur_state = (GetKeyState (vk_code) & 1);
2552 Lisp_Object new_state = (Lisp_Object) ((EMACS_INT) msg.lParam);
2554 /* NB: This code must be thread-safe. It is safe to
2555 call NILP because symbols are not relocated by GC,
2556 and pointer here is not touched by GC (so the markbit
2557 can't be set). Numbers are safe because they are
2558 immediate values. */
2559 if (NILP (new_state)
2560 || (NUMBERP (new_state)
2561 && ((XUINT (new_state)) & 1) != cur_state))
2563 one_w32_display_info.faked_key = vk_code;
2565 keybd_event ((BYTE) vk_code,
2566 (BYTE) MapVirtualKey (vk_code, 0),
2567 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2568 keybd_event ((BYTE) vk_code,
2569 (BYTE) MapVirtualKey (vk_code, 0),
2570 KEYEVENTF_EXTENDEDKEY | 0, 0);
2571 keybd_event ((BYTE) vk_code,
2572 (BYTE) MapVirtualKey (vk_code, 0),
2573 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2574 cur_state = !cur_state;
2576 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2577 cur_state, 0))
2578 abort ();
2580 break;
2581 default:
2582 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2585 else
2587 DispatchMessage (&msg);
2590 /* Exit nested loop when our deferred message has completed. */
2591 if (msg_buf->completed)
2592 break;
2596 deferred_msg * deferred_msg_head;
2598 static deferred_msg *
2599 find_deferred_msg (HWND hwnd, UINT msg)
2601 deferred_msg * item;
2603 /* Don't actually need synchronization for read access, since
2604 modification of single pointer is always atomic. */
2605 /* enter_crit (); */
2607 for (item = deferred_msg_head; item != NULL; item = item->next)
2608 if (item->w32msg.msg.hwnd == hwnd
2609 && item->w32msg.msg.message == msg)
2610 break;
2612 /* leave_crit (); */
2614 return item;
2617 static LRESULT
2618 send_deferred_msg (deferred_msg * msg_buf,
2619 HWND hwnd,
2620 UINT msg,
2621 WPARAM wParam,
2622 LPARAM lParam)
2624 /* Only input thread can send deferred messages. */
2625 if (GetCurrentThreadId () != dwWindowsThreadId)
2626 abort ();
2628 /* It is an error to send a message that is already deferred. */
2629 if (find_deferred_msg (hwnd, msg) != NULL)
2630 abort ();
2632 /* Enforced synchronization is not needed because this is the only
2633 function that alters deferred_msg_head, and the following critical
2634 section is guaranteed to only be serially reentered (since only the
2635 input thread can call us). */
2637 /* enter_crit (); */
2639 msg_buf->completed = 0;
2640 msg_buf->next = deferred_msg_head;
2641 deferred_msg_head = msg_buf;
2642 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2644 /* leave_crit (); */
2646 /* Start a new nested message loop to process other messages until
2647 this one is completed. */
2648 w32_msg_pump (msg_buf);
2650 deferred_msg_head = msg_buf->next;
2652 return msg_buf->result;
2655 void
2656 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2658 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2660 if (msg_buf == NULL)
2661 /* Message may have been cancelled, so don't abort. */
2662 return;
2664 msg_buf->result = result;
2665 msg_buf->completed = 1;
2667 /* Ensure input thread is woken so it notices the completion. */
2668 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2671 static void
2672 cancel_all_deferred_msgs ()
2674 deferred_msg * item;
2676 /* Don't actually need synchronization for read access, since
2677 modification of single pointer is always atomic. */
2678 /* enter_crit (); */
2680 for (item = deferred_msg_head; item != NULL; item = item->next)
2682 item->result = 0;
2683 item->completed = 1;
2686 /* leave_crit (); */
2688 /* Ensure input thread is woken so it notices the completion. */
2689 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2692 DWORD WINAPI
2693 w32_msg_worker (void *arg)
2695 MSG msg;
2696 deferred_msg dummy_buf;
2698 /* Ensure our message queue is created */
2700 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2702 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2703 abort ();
2705 memset (&dummy_buf, 0, sizeof (dummy_buf));
2706 dummy_buf.w32msg.msg.hwnd = NULL;
2707 dummy_buf.w32msg.msg.message = WM_NULL;
2709 /* This is the inital message loop which should only exit when the
2710 application quits. */
2711 w32_msg_pump (&dummy_buf);
2713 return 0;
2716 static void
2717 signal_user_input ()
2719 /* Interrupt any lisp that wants to be interrupted by input. */
2720 if (!NILP (Vthrow_on_input))
2722 Vquit_flag = Vthrow_on_input;
2723 /* If we're inside a function that wants immediate quits,
2724 do it now. */
2725 if (immediate_quit && NILP (Vinhibit_quit))
2727 immediate_quit = 0;
2728 QUIT;
2734 static void
2735 post_character_message (hwnd, msg, wParam, lParam, modifiers)
2736 HWND hwnd;
2737 UINT msg;
2738 WPARAM wParam;
2739 LPARAM lParam;
2740 DWORD modifiers;
2743 W32Msg wmsg;
2745 wmsg.dwModifiers = modifiers;
2747 /* Detect quit_char and set quit-flag directly. Note that we
2748 still need to post a message to ensure the main thread will be
2749 woken up if blocked in sys_select, but we do NOT want to post
2750 the quit_char message itself (because it will usually be as if
2751 the user had typed quit_char twice). Instead, we post a dummy
2752 message that has no particular effect. */
2754 int c = wParam;
2755 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2756 c = make_ctrl_char (c) & 0377;
2757 if (c == quit_char
2758 || (wmsg.dwModifiers == 0 &&
2759 w32_quit_key && wParam == w32_quit_key))
2761 Vquit_flag = Qt;
2763 /* The choice of message is somewhat arbitrary, as long as
2764 the main thread handler just ignores it. */
2765 msg = WM_NULL;
2767 /* Interrupt any blocking system calls. */
2768 signal_quit ();
2770 /* As a safety precaution, forcibly complete any deferred
2771 messages. This is a kludge, but I don't see any particularly
2772 clean way to handle the situation where a deferred message is
2773 "dropped" in the lisp thread, and will thus never be
2774 completed, eg. by the user trying to activate the menubar
2775 when the lisp thread is busy, and then typing C-g when the
2776 menubar doesn't open promptly (with the result that the
2777 menubar never responds at all because the deferred
2778 WM_INITMENU message is never completed). Another problem
2779 situation is when the lisp thread calls SendMessage (to send
2780 a window manager command) when a message has been deferred;
2781 the lisp thread gets blocked indefinitely waiting for the
2782 deferred message to be completed, which itself is waiting for
2783 the lisp thread to respond.
2785 Note that we don't want to block the input thread waiting for
2786 a reponse from the lisp thread (although that would at least
2787 solve the deadlock problem above), because we want to be able
2788 to receive C-g to interrupt the lisp thread. */
2789 cancel_all_deferred_msgs ();
2791 else
2792 signal_user_input ();
2795 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2798 /* Main window procedure */
2800 LRESULT CALLBACK
2801 w32_wnd_proc (hwnd, msg, wParam, lParam)
2802 HWND hwnd;
2803 UINT msg;
2804 WPARAM wParam;
2805 LPARAM lParam;
2807 struct frame *f;
2808 struct w32_display_info *dpyinfo = &one_w32_display_info;
2809 W32Msg wmsg;
2810 int windows_translate;
2811 int key;
2813 /* Note that it is okay to call x_window_to_frame, even though we are
2814 not running in the main lisp thread, because frame deletion
2815 requires the lisp thread to synchronize with this thread. Thus, if
2816 a frame struct is returned, it can be used without concern that the
2817 lisp thread might make it disappear while we are using it.
2819 NB. Walking the frame list in this thread is safe (as long as
2820 writes of Lisp_Object slots are atomic, which they are on Windows).
2821 Although delete-frame can destructively modify the frame list while
2822 we are walking it, a garbage collection cannot occur until after
2823 delete-frame has synchronized with this thread.
2825 It is also safe to use functions that make GDI calls, such as
2826 w32_clear_rect, because these functions must obtain a DC handle
2827 from the frame struct using get_frame_dc which is thread-aware. */
2829 switch (msg)
2831 case WM_ERASEBKGND:
2832 f = x_window_to_frame (dpyinfo, hwnd);
2833 if (f)
2835 HDC hdc = get_frame_dc (f);
2836 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2837 w32_clear_rect (f, hdc, &wmsg.rect);
2838 release_frame_dc (f, hdc);
2840 #if defined (W32_DEBUG_DISPLAY)
2841 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2843 wmsg.rect.left, wmsg.rect.top,
2844 wmsg.rect.right, wmsg.rect.bottom));
2845 #endif /* W32_DEBUG_DISPLAY */
2847 return 1;
2848 case WM_PALETTECHANGED:
2849 /* ignore our own changes */
2850 if ((HWND)wParam != hwnd)
2852 f = x_window_to_frame (dpyinfo, hwnd);
2853 if (f)
2854 /* get_frame_dc will realize our palette and force all
2855 frames to be redrawn if needed. */
2856 release_frame_dc (f, get_frame_dc (f));
2858 return 0;
2859 case WM_PAINT:
2861 PAINTSTRUCT paintStruct;
2862 RECT update_rect;
2863 bzero (&update_rect, sizeof (update_rect));
2865 f = x_window_to_frame (dpyinfo, hwnd);
2866 if (f == 0)
2868 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2869 return 0;
2872 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2873 fails. Apparently this can happen under some
2874 circumstances. */
2875 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2877 enter_crit ();
2878 BeginPaint (hwnd, &paintStruct);
2880 /* The rectangles returned by GetUpdateRect and BeginPaint
2881 do not always match. Play it safe by assuming both areas
2882 are invalid. */
2883 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2885 #if defined (W32_DEBUG_DISPLAY)
2886 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2888 wmsg.rect.left, wmsg.rect.top,
2889 wmsg.rect.right, wmsg.rect.bottom));
2890 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2891 update_rect.left, update_rect.top,
2892 update_rect.right, update_rect.bottom));
2893 #endif
2894 EndPaint (hwnd, &paintStruct);
2895 leave_crit ();
2897 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2899 return 0;
2902 /* If GetUpdateRect returns 0 (meaning there is no update
2903 region), assume the whole window needs to be repainted. */
2904 GetClientRect (hwnd, &wmsg.rect);
2905 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2906 return 0;
2909 case WM_INPUTLANGCHANGE:
2910 /* Inform lisp thread of keyboard layout changes. */
2911 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2913 /* Clear dead keys in the keyboard state; for simplicity only
2914 preserve modifier key states. */
2916 int i;
2917 BYTE keystate[256];
2919 GetKeyboardState (keystate);
2920 for (i = 0; i < 256; i++)
2921 if (1
2922 && i != VK_SHIFT
2923 && i != VK_LSHIFT
2924 && i != VK_RSHIFT
2925 && i != VK_CAPITAL
2926 && i != VK_NUMLOCK
2927 && i != VK_SCROLL
2928 && i != VK_CONTROL
2929 && i != VK_LCONTROL
2930 && i != VK_RCONTROL
2931 && i != VK_MENU
2932 && i != VK_LMENU
2933 && i != VK_RMENU
2934 && i != VK_LWIN
2935 && i != VK_RWIN)
2936 keystate[i] = 0;
2937 SetKeyboardState (keystate);
2939 goto dflt;
2941 case WM_HOTKEY:
2942 /* Synchronize hot keys with normal input. */
2943 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2944 return (0);
2946 case WM_KEYUP:
2947 case WM_SYSKEYUP:
2948 record_keyup (wParam, lParam);
2949 goto dflt;
2951 case WM_KEYDOWN:
2952 case WM_SYSKEYDOWN:
2953 /* Ignore keystrokes we fake ourself; see below. */
2954 if (dpyinfo->faked_key == wParam)
2956 dpyinfo->faked_key = 0;
2957 /* Make sure TranslateMessage sees them though (as long as
2958 they don't produce WM_CHAR messages). This ensures that
2959 indicator lights are toggled promptly on Windows 9x, for
2960 example. */
2961 if (wParam < 256 && lispy_function_keys[wParam])
2963 windows_translate = 1;
2964 goto translate;
2966 return 0;
2969 /* Synchronize modifiers with current keystroke. */
2970 sync_modifiers ();
2971 record_keydown (wParam, lParam);
2972 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2974 windows_translate = 0;
2976 switch (wParam)
2978 case VK_LWIN:
2979 if (NILP (Vw32_pass_lwindow_to_system))
2981 /* Prevent system from acting on keyup (which opens the
2982 Start menu if no other key was pressed) by simulating a
2983 press of Space which we will ignore. */
2984 if (GetAsyncKeyState (wParam) & 1)
2986 if (NUMBERP (Vw32_phantom_key_code))
2987 key = XUINT (Vw32_phantom_key_code) & 255;
2988 else
2989 key = VK_SPACE;
2990 dpyinfo->faked_key = key;
2991 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2994 if (!NILP (Vw32_lwindow_modifier))
2995 return 0;
2996 break;
2997 case VK_RWIN:
2998 if (NILP (Vw32_pass_rwindow_to_system))
3000 if (GetAsyncKeyState (wParam) & 1)
3002 if (NUMBERP (Vw32_phantom_key_code))
3003 key = XUINT (Vw32_phantom_key_code) & 255;
3004 else
3005 key = VK_SPACE;
3006 dpyinfo->faked_key = key;
3007 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3010 if (!NILP (Vw32_rwindow_modifier))
3011 return 0;
3012 break;
3013 case VK_APPS:
3014 if (!NILP (Vw32_apps_modifier))
3015 return 0;
3016 break;
3017 case VK_MENU:
3018 if (NILP (Vw32_pass_alt_to_system))
3019 /* Prevent DefWindowProc from activating the menu bar if an
3020 Alt key is pressed and released by itself. */
3021 return 0;
3022 windows_translate = 1;
3023 break;
3024 case VK_CAPITAL:
3025 /* Decide whether to treat as modifier or function key. */
3026 if (NILP (Vw32_enable_caps_lock))
3027 goto disable_lock_key;
3028 windows_translate = 1;
3029 break;
3030 case VK_NUMLOCK:
3031 /* Decide whether to treat as modifier or function key. */
3032 if (NILP (Vw32_enable_num_lock))
3033 goto disable_lock_key;
3034 windows_translate = 1;
3035 break;
3036 case VK_SCROLL:
3037 /* Decide whether to treat as modifier or function key. */
3038 if (NILP (Vw32_scroll_lock_modifier))
3039 goto disable_lock_key;
3040 windows_translate = 1;
3041 break;
3042 disable_lock_key:
3043 /* Ensure the appropriate lock key state (and indicator light)
3044 remains in the same state. We do this by faking another
3045 press of the relevant key. Apparently, this really is the
3046 only way to toggle the state of the indicator lights. */
3047 dpyinfo->faked_key = wParam;
3048 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3049 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3050 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3051 KEYEVENTF_EXTENDEDKEY | 0, 0);
3052 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3053 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3054 /* Ensure indicator lights are updated promptly on Windows 9x
3055 (TranslateMessage apparently does this), after forwarding
3056 input event. */
3057 post_character_message (hwnd, msg, wParam, lParam,
3058 w32_get_key_modifiers (wParam, lParam));
3059 windows_translate = 1;
3060 break;
3061 case VK_CONTROL:
3062 case VK_SHIFT:
3063 case VK_PROCESSKEY: /* Generated by IME. */
3064 windows_translate = 1;
3065 break;
3066 case VK_CANCEL:
3067 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3068 which is confusing for purposes of key binding; convert
3069 VK_CANCEL events into VK_PAUSE events. */
3070 wParam = VK_PAUSE;
3071 break;
3072 case VK_PAUSE:
3073 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3074 for purposes of key binding; convert these back into
3075 VK_NUMLOCK events, at least when we want to see NumLock key
3076 presses. (Note that there is never any possibility that
3077 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3078 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3079 wParam = VK_NUMLOCK;
3080 break;
3081 default:
3082 /* If not defined as a function key, change it to a WM_CHAR message. */
3083 if (wParam > 255 || !lispy_function_keys[wParam])
3085 DWORD modifiers = construct_console_modifiers ();
3087 if (!NILP (Vw32_recognize_altgr)
3088 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3090 /* Always let TranslateMessage handle AltGr key chords;
3091 for some reason, ToAscii doesn't always process AltGr
3092 chords correctly. */
3093 windows_translate = 1;
3095 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3097 /* Handle key chords including any modifiers other
3098 than shift directly, in order to preserve as much
3099 modifier information as possible. */
3100 if ('A' <= wParam && wParam <= 'Z')
3102 /* Don't translate modified alphabetic keystrokes,
3103 so the user doesn't need to constantly switch
3104 layout to type control or meta keystrokes when
3105 the normal layout translates alphabetic
3106 characters to non-ascii characters. */
3107 if (!modifier_set (VK_SHIFT))
3108 wParam += ('a' - 'A');
3109 msg = WM_CHAR;
3111 else
3113 /* Try to handle other keystrokes by determining the
3114 base character (ie. translating the base key plus
3115 shift modifier). */
3116 int add;
3117 int isdead = 0;
3118 KEY_EVENT_RECORD key;
3120 key.bKeyDown = TRUE;
3121 key.wRepeatCount = 1;
3122 key.wVirtualKeyCode = wParam;
3123 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3124 key.uChar.AsciiChar = 0;
3125 key.dwControlKeyState = modifiers;
3127 add = w32_kbd_patch_key (&key);
3128 /* 0 means an unrecognised keycode, negative means
3129 dead key. Ignore both. */
3130 while (--add >= 0)
3132 /* Forward asciified character sequence. */
3133 post_character_message
3134 (hwnd, WM_CHAR,
3135 (unsigned char) key.uChar.AsciiChar, lParam,
3136 w32_get_key_modifiers (wParam, lParam));
3137 w32_kbd_patch_key (&key);
3139 return 0;
3142 else
3144 /* Let TranslateMessage handle everything else. */
3145 windows_translate = 1;
3150 translate:
3151 if (windows_translate)
3153 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3155 windows_msg.time = GetMessageTime ();
3156 TranslateMessage (&windows_msg);
3157 goto dflt;
3160 /* Fall through */
3162 case WM_SYSCHAR:
3163 case WM_CHAR:
3164 post_character_message (hwnd, msg, wParam, lParam,
3165 w32_get_key_modifiers (wParam, lParam));
3166 break;
3168 /* Simulate middle mouse button events when left and right buttons
3169 are used together, but only if user has two button mouse. */
3170 case WM_LBUTTONDOWN:
3171 case WM_RBUTTONDOWN:
3172 if (w32_num_mouse_buttons > 2)
3173 goto handle_plain_button;
3176 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3177 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3179 if (button_state & this)
3180 return 0;
3182 if (button_state == 0)
3183 SetCapture (hwnd);
3185 button_state |= this;
3187 if (button_state & other)
3189 if (mouse_button_timer)
3191 KillTimer (hwnd, mouse_button_timer);
3192 mouse_button_timer = 0;
3194 /* Generate middle mouse event instead. */
3195 msg = WM_MBUTTONDOWN;
3196 button_state |= MMOUSE;
3198 else if (button_state & MMOUSE)
3200 /* Ignore button event if we've already generated a
3201 middle mouse down event. This happens if the
3202 user releases and press one of the two buttons
3203 after we've faked a middle mouse event. */
3204 return 0;
3206 else
3208 /* Flush out saved message. */
3209 post_msg (&saved_mouse_button_msg);
3211 wmsg.dwModifiers = w32_get_modifiers ();
3212 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3213 signal_user_input ();
3215 /* Clear message buffer. */
3216 saved_mouse_button_msg.msg.hwnd = 0;
3218 else
3220 /* Hold onto message for now. */
3221 mouse_button_timer =
3222 SetTimer (hwnd, MOUSE_BUTTON_ID,
3223 w32_mouse_button_tolerance, NULL);
3224 saved_mouse_button_msg.msg.hwnd = hwnd;
3225 saved_mouse_button_msg.msg.message = msg;
3226 saved_mouse_button_msg.msg.wParam = wParam;
3227 saved_mouse_button_msg.msg.lParam = lParam;
3228 saved_mouse_button_msg.msg.time = GetMessageTime ();
3229 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3232 return 0;
3234 case WM_LBUTTONUP:
3235 case WM_RBUTTONUP:
3236 if (w32_num_mouse_buttons > 2)
3237 goto handle_plain_button;
3240 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3241 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3243 if ((button_state & this) == 0)
3244 return 0;
3246 button_state &= ~this;
3248 if (button_state & MMOUSE)
3250 /* Only generate event when second button is released. */
3251 if ((button_state & other) == 0)
3253 msg = WM_MBUTTONUP;
3254 button_state &= ~MMOUSE;
3256 if (button_state) abort ();
3258 else
3259 return 0;
3261 else
3263 /* Flush out saved message if necessary. */
3264 if (saved_mouse_button_msg.msg.hwnd)
3266 post_msg (&saved_mouse_button_msg);
3269 wmsg.dwModifiers = w32_get_modifiers ();
3270 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3271 signal_user_input ();
3273 /* Always clear message buffer and cancel timer. */
3274 saved_mouse_button_msg.msg.hwnd = 0;
3275 KillTimer (hwnd, mouse_button_timer);
3276 mouse_button_timer = 0;
3278 if (button_state == 0)
3279 ReleaseCapture ();
3281 return 0;
3283 case WM_XBUTTONDOWN:
3284 case WM_XBUTTONUP:
3285 if (w32_pass_extra_mouse_buttons_to_system)
3286 goto dflt;
3287 /* else fall through and process them. */
3288 case WM_MBUTTONDOWN:
3289 case WM_MBUTTONUP:
3290 handle_plain_button:
3292 BOOL up;
3293 int button;
3295 /* Ignore middle and extra buttons as long as the menu is active. */
3296 f = x_window_to_frame (dpyinfo, hwnd);
3297 if (f && f->output_data.w32->menubar_active)
3298 return 0;
3300 if (parse_button (msg, HIWORD (wParam), &button, &up))
3302 if (up) ReleaseCapture ();
3303 else SetCapture (hwnd);
3304 button = (button == 0) ? LMOUSE :
3305 ((button == 1) ? MMOUSE : RMOUSE);
3306 if (up)
3307 button_state &= ~button;
3308 else
3309 button_state |= button;
3313 wmsg.dwModifiers = w32_get_modifiers ();
3314 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3315 signal_user_input ();
3317 /* Need to return true for XBUTTON messages, false for others,
3318 to indicate that we processed the message. */
3319 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3321 case WM_MOUSEMOVE:
3322 /* Ignore mouse movements as long as the menu is active. These
3323 movements are processed by the window manager anyway, and
3324 it's wrong to handle them as if they happened on the
3325 underlying frame. */
3326 f = x_window_to_frame (dpyinfo, hwnd);
3327 if (f && f->output_data.w32->menubar_active)
3328 return 0;
3330 /* If the mouse has just moved into the frame, start tracking
3331 it, so we will be notified when it leaves the frame. Mouse
3332 tracking only works under W98 and NT4 and later. On earlier
3333 versions, there is no way of telling when the mouse leaves the
3334 frame, so we just have to put up with help-echo and mouse
3335 highlighting remaining while the frame is not active. */
3336 if (track_mouse_event_fn && !track_mouse_window)
3338 TRACKMOUSEEVENT tme;
3339 tme.cbSize = sizeof (tme);
3340 tme.dwFlags = TME_LEAVE;
3341 tme.hwndTrack = hwnd;
3343 track_mouse_event_fn (&tme);
3344 track_mouse_window = hwnd;
3346 case WM_VSCROLL:
3347 if (w32_mouse_move_interval <= 0
3348 || (msg == WM_MOUSEMOVE && button_state == 0))
3350 wmsg.dwModifiers = w32_get_modifiers ();
3351 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3352 return 0;
3355 /* Hang onto mouse move and scroll messages for a bit, to avoid
3356 sending such events to Emacs faster than it can process them.
3357 If we get more events before the timer from the first message
3358 expires, we just replace the first message. */
3360 if (saved_mouse_move_msg.msg.hwnd == 0)
3361 mouse_move_timer =
3362 SetTimer (hwnd, MOUSE_MOVE_ID,
3363 w32_mouse_move_interval, NULL);
3365 /* Hold onto message for now. */
3366 saved_mouse_move_msg.msg.hwnd = hwnd;
3367 saved_mouse_move_msg.msg.message = msg;
3368 saved_mouse_move_msg.msg.wParam = wParam;
3369 saved_mouse_move_msg.msg.lParam = lParam;
3370 saved_mouse_move_msg.msg.time = GetMessageTime ();
3371 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3373 return 0;
3375 case WM_MOUSEWHEEL:
3376 case WM_DROPFILES:
3377 wmsg.dwModifiers = w32_get_modifiers ();
3378 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3379 signal_user_input ();
3380 return 0;
3382 case WM_APPCOMMAND:
3383 if (w32_pass_multimedia_buttons_to_system)
3384 goto dflt;
3385 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3386 case WM_MOUSEHWHEEL:
3387 wmsg.dwModifiers = w32_get_modifiers ();
3388 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3389 signal_user_input ();
3390 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3391 handled, to prevent the system trying to handle it by faking
3392 scroll bar events. */
3393 return 1;
3395 case WM_TIMER:
3396 /* Flush out saved messages if necessary. */
3397 if (wParam == mouse_button_timer)
3399 if (saved_mouse_button_msg.msg.hwnd)
3401 post_msg (&saved_mouse_button_msg);
3402 signal_user_input ();
3403 saved_mouse_button_msg.msg.hwnd = 0;
3405 KillTimer (hwnd, mouse_button_timer);
3406 mouse_button_timer = 0;
3408 else if (wParam == mouse_move_timer)
3410 if (saved_mouse_move_msg.msg.hwnd)
3412 post_msg (&saved_mouse_move_msg);
3413 saved_mouse_move_msg.msg.hwnd = 0;
3415 KillTimer (hwnd, mouse_move_timer);
3416 mouse_move_timer = 0;
3418 else if (wParam == menu_free_timer)
3420 KillTimer (hwnd, menu_free_timer);
3421 menu_free_timer = 0;
3422 f = x_window_to_frame (dpyinfo, hwnd);
3423 /* If a popup menu is active, don't wipe its strings. */
3424 if (menubar_in_use
3425 && current_popup_menu == NULL)
3427 /* Free memory used by owner-drawn and help-echo strings. */
3428 w32_free_menu_strings (hwnd);
3429 f->output_data.w32->menubar_active = 0;
3430 menubar_in_use = 0;
3433 return 0;
3435 case WM_NCACTIVATE:
3436 /* Windows doesn't send us focus messages when putting up and
3437 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3438 The only indication we get that something happened is receiving
3439 this message afterwards. So this is a good time to reset our
3440 keyboard modifiers' state. */
3441 reset_modifiers ();
3442 goto dflt;
3444 case WM_INITMENU:
3445 button_state = 0;
3446 ReleaseCapture ();
3447 /* We must ensure menu bar is fully constructed and up to date
3448 before allowing user interaction with it. To achieve this
3449 we send this message to the lisp thread and wait for a
3450 reply (whose value is not actually needed) to indicate that
3451 the menu bar is now ready for use, so we can now return.
3453 To remain responsive in the meantime, we enter a nested message
3454 loop that can process all other messages.
3456 However, we skip all this if the message results from calling
3457 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3458 thread a message because it is blocked on us at this point. We
3459 set menubar_active before calling TrackPopupMenu to indicate
3460 this (there is no possibility of confusion with real menubar
3461 being active). */
3463 f = x_window_to_frame (dpyinfo, hwnd);
3464 if (f
3465 && (f->output_data.w32->menubar_active
3466 /* We can receive this message even in the absence of a
3467 menubar (ie. when the system menu is activated) - in this
3468 case we do NOT want to forward the message, otherwise it
3469 will cause the menubar to suddenly appear when the user
3470 had requested it to be turned off! */
3471 || f->output_data.w32->menubar_widget == NULL))
3472 return 0;
3475 deferred_msg msg_buf;
3477 /* Detect if message has already been deferred; in this case
3478 we cannot return any sensible value to ignore this. */
3479 if (find_deferred_msg (hwnd, msg) != NULL)
3480 abort ();
3482 menubar_in_use = 1;
3484 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3487 case WM_EXITMENULOOP:
3488 f = x_window_to_frame (dpyinfo, hwnd);
3490 /* If a menu is still active, check again after a short delay,
3491 since Windows often (always?) sends the WM_EXITMENULOOP
3492 before the corresponding WM_COMMAND message.
3493 Don't do this if a popup menu is active, since it is only
3494 menubar menus that require cleaning up in this way.
3496 if (f && menubar_in_use && current_popup_menu == NULL)
3497 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3498 goto dflt;
3500 case WM_MENUSELECT:
3501 /* Direct handling of help_echo in menus. Should be safe now
3502 that we generate the help_echo by placing a help event in the
3503 keyboard buffer. */
3505 HMENU menu = (HMENU) lParam;
3506 UINT menu_item = (UINT) LOWORD (wParam);
3507 UINT flags = (UINT) HIWORD (wParam);
3509 w32_menu_display_help (hwnd, menu, menu_item, flags);
3511 return 0;
3513 case WM_MEASUREITEM:
3514 f = x_window_to_frame (dpyinfo, hwnd);
3515 if (f)
3517 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3519 if (pMis->CtlType == ODT_MENU)
3521 /* Work out dimensions for popup menu titles. */
3522 char * title = (char *) pMis->itemData;
3523 HDC hdc = GetDC (hwnd);
3524 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3525 LOGFONT menu_logfont;
3526 HFONT old_font;
3527 SIZE size;
3529 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3530 menu_logfont.lfWeight = FW_BOLD;
3531 menu_font = CreateFontIndirect (&menu_logfont);
3532 old_font = SelectObject (hdc, menu_font);
3534 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3535 if (title)
3537 if (unicode_append_menu)
3538 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3539 wcslen ((WCHAR *) title),
3540 &size);
3541 else
3542 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3544 pMis->itemWidth = size.cx;
3545 if (pMis->itemHeight < size.cy)
3546 pMis->itemHeight = size.cy;
3548 else
3549 pMis->itemWidth = 0;
3551 SelectObject (hdc, old_font);
3552 DeleteObject (menu_font);
3553 ReleaseDC (hwnd, hdc);
3554 return TRUE;
3557 return 0;
3559 case WM_DRAWITEM:
3560 f = x_window_to_frame (dpyinfo, hwnd);
3561 if (f)
3563 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3565 if (pDis->CtlType == ODT_MENU)
3567 /* Draw popup menu title. */
3568 char * title = (char *) pDis->itemData;
3569 if (title)
3571 HDC hdc = pDis->hDC;
3572 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3573 LOGFONT menu_logfont;
3574 HFONT old_font;
3576 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3577 menu_logfont.lfWeight = FW_BOLD;
3578 menu_font = CreateFontIndirect (&menu_logfont);
3579 old_font = SelectObject (hdc, menu_font);
3581 /* Always draw title as if not selected. */
3582 if (unicode_append_menu)
3583 ExtTextOutW (hdc,
3584 pDis->rcItem.left
3585 + GetSystemMetrics (SM_CXMENUCHECK),
3586 pDis->rcItem.top,
3587 ETO_OPAQUE, &pDis->rcItem,
3588 (WCHAR *) title,
3589 wcslen ((WCHAR *) title), NULL);
3590 else
3591 ExtTextOut (hdc,
3592 pDis->rcItem.left
3593 + GetSystemMetrics (SM_CXMENUCHECK),
3594 pDis->rcItem.top,
3595 ETO_OPAQUE, &pDis->rcItem,
3596 title, strlen (title), NULL);
3598 SelectObject (hdc, old_font);
3599 DeleteObject (menu_font);
3601 return TRUE;
3604 return 0;
3606 #if 0
3607 /* Still not right - can't distinguish between clicks in the
3608 client area of the frame from clicks forwarded from the scroll
3609 bars - may have to hook WM_NCHITTEST to remember the mouse
3610 position and then check if it is in the client area ourselves. */
3611 case WM_MOUSEACTIVATE:
3612 /* Discard the mouse click that activates a frame, allowing the
3613 user to click anywhere without changing point (or worse!).
3614 Don't eat mouse clicks on scrollbars though!! */
3615 if (LOWORD (lParam) == HTCLIENT )
3616 return MA_ACTIVATEANDEAT;
3617 goto dflt;
3618 #endif
3620 case WM_MOUSELEAVE:
3621 /* No longer tracking mouse. */
3622 track_mouse_window = NULL;
3624 case WM_ACTIVATEAPP:
3625 case WM_ACTIVATE:
3626 case WM_WINDOWPOSCHANGED:
3627 case WM_SHOWWINDOW:
3628 /* Inform lisp thread that a frame might have just been obscured
3629 or exposed, so should recheck visibility of all frames. */
3630 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3631 goto dflt;
3633 case WM_SETFOCUS:
3634 dpyinfo->faked_key = 0;
3635 reset_modifiers ();
3636 register_hot_keys (hwnd);
3637 goto command;
3638 case WM_KILLFOCUS:
3639 unregister_hot_keys (hwnd);
3640 button_state = 0;
3641 ReleaseCapture ();
3642 /* Relinquish the system caret. */
3643 if (w32_system_caret_hwnd)
3645 w32_visible_system_caret_hwnd = NULL;
3646 w32_system_caret_hwnd = NULL;
3647 DestroyCaret ();
3649 goto command;
3650 case WM_COMMAND:
3651 menubar_in_use = 0;
3652 f = x_window_to_frame (dpyinfo, hwnd);
3653 if (f && HIWORD (wParam) == 0)
3655 if (menu_free_timer)
3657 KillTimer (hwnd, menu_free_timer);
3658 menu_free_timer = 0;
3661 case WM_MOVE:
3662 case WM_SIZE:
3663 command:
3664 wmsg.dwModifiers = w32_get_modifiers ();
3665 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3666 goto dflt;
3668 case WM_DESTROY:
3669 CoUninitialize ();
3670 return 0;
3672 case WM_CLOSE:
3673 wmsg.dwModifiers = w32_get_modifiers ();
3674 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3675 return 0;
3677 case WM_WINDOWPOSCHANGING:
3678 /* Don't restrict the sizing of tip frames. */
3679 if (hwnd == tip_window)
3680 return 0;
3682 WINDOWPLACEMENT wp;
3683 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3685 wp.length = sizeof (WINDOWPLACEMENT);
3686 GetWindowPlacement (hwnd, &wp);
3688 if (wp.showCmd != SW_SHOWMINIMIZED && (lppos->flags & SWP_NOSIZE) == 0)
3690 RECT rect;
3691 int wdiff;
3692 int hdiff;
3693 DWORD font_width;
3694 DWORD line_height;
3695 DWORD internal_border;
3696 DWORD scrollbar_extra;
3697 RECT wr;
3699 wp.length = sizeof (wp);
3700 GetWindowRect (hwnd, &wr);
3702 enter_crit ();
3704 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3705 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3706 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3707 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3709 leave_crit ();
3711 memset (&rect, 0, sizeof (rect));
3712 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3713 GetMenu (hwnd) != NULL);
3715 /* Force width and height of client area to be exact
3716 multiples of the character cell dimensions. */
3717 wdiff = (lppos->cx - (rect.right - rect.left)
3718 - 2 * internal_border - scrollbar_extra)
3719 % font_width;
3720 hdiff = (lppos->cy - (rect.bottom - rect.top)
3721 - 2 * internal_border)
3722 % line_height;
3724 if (wdiff || hdiff)
3726 /* For right/bottom sizing we can just fix the sizes.
3727 However for top/left sizing we will need to fix the X
3728 and Y positions as well. */
3730 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3731 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3733 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3734 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3736 if (wp.showCmd != SW_SHOWMAXIMIZED
3737 && (lppos->flags & SWP_NOMOVE) == 0)
3739 if (lppos->x != wr.left || lppos->y != wr.top)
3741 lppos->x += wdiff;
3742 lppos->y += hdiff;
3744 else
3746 lppos->flags |= SWP_NOMOVE;
3750 return 0;
3755 goto dflt;
3757 case WM_GETMINMAXINFO:
3758 /* Hack to allow resizing the Emacs frame above the screen size.
3759 Note that Windows 9x limits coordinates to 16-bits. */
3760 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3761 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3762 return 0;
3764 case WM_SETCURSOR:
3765 if (LOWORD (lParam) == HTCLIENT)
3766 return 0;
3768 goto dflt;
3770 case WM_EMACS_SETCURSOR:
3772 Cursor cursor = (Cursor) wParam;
3773 if (cursor)
3774 SetCursor (cursor);
3775 return 0;
3778 case WM_EMACS_CREATESCROLLBAR:
3779 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3780 (struct scroll_bar *) lParam);
3782 case WM_EMACS_SHOWWINDOW:
3783 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3785 case WM_EMACS_SETFOREGROUND:
3787 HWND foreground_window;
3788 DWORD foreground_thread, retval;
3790 /* On NT 5.0, and apparently Windows 98, it is necessary to
3791 attach to the thread that currently has focus in order to
3792 pull the focus away from it. */
3793 foreground_window = GetForegroundWindow ();
3794 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3795 if (!foreground_window
3796 || foreground_thread == GetCurrentThreadId ()
3797 || !AttachThreadInput (GetCurrentThreadId (),
3798 foreground_thread, TRUE))
3799 foreground_thread = 0;
3801 retval = SetForegroundWindow ((HWND) wParam);
3803 /* Detach from the previous foreground thread. */
3804 if (foreground_thread)
3805 AttachThreadInput (GetCurrentThreadId (),
3806 foreground_thread, FALSE);
3808 return retval;
3811 case WM_EMACS_SETWINDOWPOS:
3813 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3814 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3815 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3818 case WM_EMACS_DESTROYWINDOW:
3819 DragAcceptFiles ((HWND) wParam, FALSE);
3820 return DestroyWindow ((HWND) wParam);
3822 case WM_EMACS_HIDE_CARET:
3823 return HideCaret (hwnd);
3825 case WM_EMACS_SHOW_CARET:
3826 return ShowCaret (hwnd);
3828 case WM_EMACS_DESTROY_CARET:
3829 w32_system_caret_hwnd = NULL;
3830 w32_visible_system_caret_hwnd = NULL;
3831 return DestroyCaret ();
3833 case WM_EMACS_TRACK_CARET:
3834 /* If there is currently no system caret, create one. */
3835 if (w32_system_caret_hwnd == NULL)
3837 /* Use the default caret width, and avoid changing it
3838 unneccesarily, as it confuses screen reader software. */
3839 w32_system_caret_hwnd = hwnd;
3840 CreateCaret (hwnd, NULL, 0,
3841 w32_system_caret_height);
3844 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3845 return 0;
3846 /* Ensure visible caret gets turned on when requested. */
3847 else if (w32_use_visible_system_caret
3848 && w32_visible_system_caret_hwnd != hwnd)
3850 w32_visible_system_caret_hwnd = hwnd;
3851 return ShowCaret (hwnd);
3853 /* Ensure visible caret gets turned off when requested. */
3854 else if (!w32_use_visible_system_caret
3855 && w32_visible_system_caret_hwnd)
3857 w32_visible_system_caret_hwnd = NULL;
3858 return HideCaret (hwnd);
3860 else
3861 return 1;
3863 case WM_EMACS_TRACKPOPUPMENU:
3865 UINT flags;
3866 POINT *pos;
3867 int retval;
3868 pos = (POINT *)lParam;
3869 flags = TPM_CENTERALIGN;
3870 if (button_state & LMOUSE)
3871 flags |= TPM_LEFTBUTTON;
3872 else if (button_state & RMOUSE)
3873 flags |= TPM_RIGHTBUTTON;
3875 /* Remember we did a SetCapture on the initial mouse down event,
3876 so for safety, we make sure the capture is cancelled now. */
3877 ReleaseCapture ();
3878 button_state = 0;
3880 /* Use menubar_active to indicate that WM_INITMENU is from
3881 TrackPopupMenu below, and should be ignored. */
3882 f = x_window_to_frame (dpyinfo, hwnd);
3883 if (f)
3884 f->output_data.w32->menubar_active = 1;
3886 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
3887 0, hwnd, NULL))
3889 MSG amsg;
3890 /* Eat any mouse messages during popupmenu */
3891 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
3892 PM_REMOVE));
3893 /* Get the menu selection, if any */
3894 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
3896 retval = LOWORD (amsg.wParam);
3898 else
3900 retval = 0;
3903 else
3905 retval = -1;
3908 return retval;
3911 default:
3912 /* Check for messages registered at runtime. */
3913 if (msg == msh_mousewheel)
3915 wmsg.dwModifiers = w32_get_modifiers ();
3916 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3917 signal_user_input ();
3918 return 0;
3921 dflt:
3922 return DefWindowProc (hwnd, msg, wParam, lParam);
3926 /* The most common default return code for handled messages is 0. */
3927 return 0;
3930 static void
3931 my_create_window (f)
3932 struct frame * f;
3934 MSG msg;
3936 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
3937 abort ();
3938 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
3942 /* Create a tooltip window. Unlike my_create_window, we do not do this
3943 indirectly via the Window thread, as we do not need to process Window
3944 messages for the tooltip. Creating tooltips indirectly also creates
3945 deadlocks when tooltips are created for menu items. */
3946 static void
3947 my_create_tip_window (f)
3948 struct frame *f;
3950 RECT rect;
3952 rect.left = rect.top = 0;
3953 rect.right = FRAME_PIXEL_WIDTH (f);
3954 rect.bottom = FRAME_PIXEL_HEIGHT (f);
3956 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
3957 FRAME_EXTERNAL_MENU_BAR (f));
3959 tip_window = FRAME_W32_WINDOW (f)
3960 = CreateWindow (EMACS_CLASS,
3961 f->namebuf,
3962 f->output_data.w32->dwStyle,
3963 f->left_pos,
3964 f->top_pos,
3965 rect.right - rect.left,
3966 rect.bottom - rect.top,
3967 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
3968 NULL,
3969 hinst,
3970 NULL);
3972 if (tip_window)
3974 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
3975 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
3976 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
3977 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
3979 /* Tip frames have no scrollbars. */
3980 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
3982 /* Do this to discard the default setting specified by our parent. */
3983 ShowWindow (tip_window, SW_HIDE);
3988 /* Create and set up the w32 window for frame F. */
3990 static void
3991 w32_window (f, window_prompting, minibuffer_only)
3992 struct frame *f;
3993 long window_prompting;
3994 int minibuffer_only;
3996 BLOCK_INPUT;
3998 /* Use the resource name as the top-level window name
3999 for looking up resources. Make a non-Lisp copy
4000 for the window manager, so GC relocation won't bother it.
4002 Elsewhere we specify the window name for the window manager. */
4005 char *str = (char *) SDATA (Vx_resource_name);
4006 f->namebuf = (char *) xmalloc (strlen (str) + 1);
4007 strcpy (f->namebuf, str);
4010 my_create_window (f);
4012 validate_x_resource_name ();
4014 /* x_set_name normally ignores requests to set the name if the
4015 requested name is the same as the current name. This is the one
4016 place where that assumption isn't correct; f->name is set, but
4017 the server hasn't been told. */
4019 Lisp_Object name;
4020 int explicit = f->explicit_name;
4022 f->explicit_name = 0;
4023 name = f->name;
4024 f->name = Qnil;
4025 x_set_name (f, name, explicit);
4028 UNBLOCK_INPUT;
4030 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4031 initialize_frame_menubar (f);
4033 if (FRAME_W32_WINDOW (f) == 0)
4034 error ("Unable to create window");
4037 /* Handle the icon stuff for this window. Perhaps later we might
4038 want an x_set_icon_position which can be called interactively as
4039 well. */
4041 static void
4042 x_icon (f, parms)
4043 struct frame *f;
4044 Lisp_Object parms;
4046 Lisp_Object icon_x, icon_y;
4048 /* Set the position of the icon. Note that Windows 95 groups all
4049 icons in the tray. */
4050 icon_x = w32_get_arg (parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4051 icon_y = w32_get_arg (parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4052 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4054 CHECK_NUMBER (icon_x);
4055 CHECK_NUMBER (icon_y);
4057 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4058 error ("Both left and top icon corners of icon must be specified");
4060 BLOCK_INPUT;
4062 if (! EQ (icon_x, Qunbound))
4063 x_wm_set_icon_position (f, XINT (icon_x), XINT (icon_y));
4065 #if 0 /* TODO */
4066 /* Start up iconic or window? */
4067 x_wm_set_window_state
4068 (f, (EQ (w32_get_arg (parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4069 ? IconicState
4070 : NormalState));
4072 x_text_icon (f, (char *) SDATA ((!NILP (f->icon_name)
4073 ? f->icon_name
4074 : f->name)));
4075 #endif
4077 UNBLOCK_INPUT;
4081 static void
4082 x_make_gc (f)
4083 struct frame *f;
4085 XGCValues gc_values;
4087 BLOCK_INPUT;
4089 /* Create the GC's of this frame.
4090 Note that many default values are used. */
4092 /* Normal video */
4093 gc_values.font = FRAME_FONT (f);
4095 /* Cursor has cursor-color background, background-color foreground. */
4096 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4097 gc_values.background = f->output_data.w32->cursor_pixel;
4098 f->output_data.w32->cursor_gc
4099 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4100 (GCFont | GCForeground | GCBackground),
4101 &gc_values);
4103 /* Reliefs. */
4104 f->output_data.w32->white_relief.gc = 0;
4105 f->output_data.w32->black_relief.gc = 0;
4107 UNBLOCK_INPUT;
4111 /* Handler for signals raised during x_create_frame and
4112 x_create_top_frame. FRAME is the frame which is partially
4113 constructed. */
4115 static Lisp_Object
4116 unwind_create_frame (frame)
4117 Lisp_Object frame;
4119 struct frame *f = XFRAME (frame);
4121 /* If frame is ``official'', nothing to do. */
4122 if (!CONSP (Vframe_list) || !EQ (XCAR (Vframe_list), frame))
4124 #ifdef GLYPH_DEBUG
4125 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4126 #endif
4128 x_free_frame_resources (f);
4130 /* Check that reference counts are indeed correct. */
4131 xassert (dpyinfo->reference_count == dpyinfo_refcount);
4132 xassert (dpyinfo->image_cache->refcount == image_cache_refcount);
4134 return Qt;
4137 return Qnil;
4141 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4142 1, 1, 0,
4143 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4144 Return an Emacs frame object.
4145 PARAMETERS is an alist of frame parameters.
4146 If the parameters specify that the frame should not have a minibuffer,
4147 and do not specify a specific minibuffer window to use,
4148 then `default-minibuffer-frame' must be a frame whose minibuffer can
4149 be shared by the new frame.
4151 This function is an internal primitive--use `make-frame' instead. */)
4152 (parameters)
4153 Lisp_Object parameters;
4155 struct frame *f;
4156 Lisp_Object frame, tem;
4157 Lisp_Object name;
4158 int minibuffer_only = 0;
4159 long window_prompting = 0;
4160 int width, height;
4161 int count = SPECPDL_INDEX ();
4162 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4163 Lisp_Object display;
4164 struct w32_display_info *dpyinfo = NULL;
4165 Lisp_Object parent;
4166 struct kboard *kb;
4168 check_w32 ();
4170 /* Make copy of frame parameters because the original is in pure
4171 storage now. */
4172 parameters = Fcopy_alist (parameters);
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->terminal->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->terminal = dpyinfo->terminal;
4232 f->terminal->reference_count++;
4234 f->output_method = output_w32;
4235 f->output_data.w32 =
4236 (struct w32_output *) xmalloc (sizeof (struct w32_output));
4237 bzero (f->output_data.w32, sizeof (struct w32_output));
4238 FRAME_FONTSET (f) = -1;
4239 record_unwind_protect (unwind_create_frame, frame);
4241 f->icon_name
4242 = w32_get_arg (parameters, Qicon_name, "iconName", "Title", RES_TYPE_STRING);
4243 if (! STRINGP (f->icon_name))
4244 f->icon_name = Qnil;
4246 /* FRAME_W32_DISPLAY_INFO (f) = dpyinfo; */
4247 #ifdef MULTI_KBOARD
4248 FRAME_KBOARD (f) = kb;
4249 #endif
4251 /* Specify the parent under which to make this window. */
4253 if (!NILP (parent))
4255 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4256 f->output_data.w32->explicit_parent = 1;
4258 else
4260 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4261 f->output_data.w32->explicit_parent = 0;
4264 /* Set the name; the functions to which we pass f expect the name to
4265 be set. */
4266 if (EQ (name, Qunbound) || NILP (name))
4268 f->name = build_string (dpyinfo->w32_id_name);
4269 f->explicit_name = 0;
4271 else
4273 f->name = name;
4274 f->explicit_name = 1;
4275 /* use the frame's title when getting resources for this frame. */
4276 specbind (Qx_resource_name, name);
4279 /* Extract the window parameters from the supplied values
4280 that are needed to determine window geometry. */
4282 Lisp_Object font;
4284 font = w32_get_arg (parameters, Qfont, "font", "Font", RES_TYPE_STRING);
4286 BLOCK_INPUT;
4287 /* First, try whatever font the caller has specified. */
4288 if (STRINGP (font))
4290 tem = Fquery_fontset (font, Qnil);
4291 if (STRINGP (tem))
4292 font = x_new_fontset (f, SDATA (tem));
4293 else
4294 font = x_new_font (f, SDATA (font));
4296 /* Try out a font which we hope has bold and italic variations. */
4297 if (!STRINGP (font))
4298 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
4299 if (! STRINGP (font))
4300 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
4301 /* If those didn't work, look for something which will at least work. */
4302 if (! STRINGP (font))
4303 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
4304 UNBLOCK_INPUT;
4305 if (! STRINGP (font))
4306 font = build_string ("Fixedsys");
4308 x_default_parameter (f, parameters, Qfont, font,
4309 "font", "Font", RES_TYPE_STRING);
4312 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4313 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4314 /* This defaults to 2 in order to match xterm. We recognize either
4315 internalBorderWidth or internalBorder (which is what xterm calls
4316 it). */
4317 if (NILP (Fassq (Qinternal_border_width, parameters)))
4319 Lisp_Object value;
4321 value = w32_get_arg (parameters, Qinternal_border_width,
4322 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4323 if (! EQ (value, Qunbound))
4324 parameters = Fcons (Fcons (Qinternal_border_width, value),
4325 parameters);
4327 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4328 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4329 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4330 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4331 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4333 /* Also do the stuff which must be set before the window exists. */
4334 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4335 "foreground", "Foreground", RES_TYPE_STRING);
4336 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4337 "background", "Background", RES_TYPE_STRING);
4338 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4339 "pointerColor", "Foreground", RES_TYPE_STRING);
4340 x_default_parameter (f, parameters, Qcursor_color, build_string ("black"),
4341 "cursorColor", "Foreground", RES_TYPE_STRING);
4342 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4343 "borderColor", "BorderColor", RES_TYPE_STRING);
4344 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4345 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4346 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4347 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4348 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4349 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4350 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4351 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4354 /* Init faces before x_default_parameter is called for scroll-bar
4355 parameters because that function calls x_set_scroll_bar_width,
4356 which calls change_frame_size, which calls Fset_window_buffer,
4357 which runs hooks, which call Fvertical_motion. At the end, we
4358 end up in init_iterator with a null face cache, which should not
4359 happen. */
4360 init_frame_faces (f);
4362 x_default_parameter (f, parameters, Qmenu_bar_lines, make_number (1),
4363 "menuBar", "MenuBar", RES_TYPE_NUMBER);
4364 x_default_parameter (f, parameters, Qtool_bar_lines, make_number (1),
4365 "toolBar", "ToolBar", RES_TYPE_NUMBER);
4367 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4368 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4369 x_default_parameter (f, parameters, Qtitle, Qnil,
4370 "title", "Title", RES_TYPE_STRING);
4371 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4372 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4374 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4375 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
4377 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4378 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4379 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4380 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4381 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4382 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4384 window_prompting = x_figure_window_size (f, parameters, 1);
4386 tem = w32_get_arg (parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4387 f->no_split = minibuffer_only || EQ (tem, Qt);
4389 w32_window (f, window_prompting, minibuffer_only);
4390 x_icon (f, parameters);
4392 x_make_gc (f);
4394 /* Now consider the frame official. */
4395 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
4396 Vframe_list = Fcons (frame, Vframe_list);
4398 /* We need to do this after creating the window, so that the
4399 icon-creation functions can say whose icon they're describing. */
4400 x_default_parameter (f, parameters, Qicon_type, Qnil,
4401 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4403 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4404 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4405 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4406 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4407 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4408 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4409 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4410 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4412 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4413 Change will not be effected unless different from the current
4414 FRAME_LINES (f). */
4415 width = FRAME_COLS (f);
4416 height = FRAME_LINES (f);
4418 FRAME_LINES (f) = 0;
4419 SET_FRAME_COLS (f, 0);
4420 change_frame_size (f, height, width, 1, 0, 0);
4422 /* Tell the server what size and position, etc, we want, and how
4423 badly we want them. This should be done after we have the menu
4424 bar so that its size can be taken into account. */
4425 BLOCK_INPUT;
4426 x_wm_set_size_hint (f, window_prompting, 0);
4427 UNBLOCK_INPUT;
4429 /* Make the window appear on the frame and enable display, unless
4430 the caller says not to. However, with explicit parent, Emacs
4431 cannot control visibility, so don't try. */
4432 if (! f->output_data.w32->explicit_parent)
4434 Lisp_Object visibility;
4436 visibility = w32_get_arg (parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4437 if (EQ (visibility, Qunbound))
4438 visibility = Qt;
4440 if (EQ (visibility, Qicon))
4441 x_iconify_frame (f);
4442 else if (! NILP (visibility))
4443 x_make_frame_visible (f);
4444 else
4445 /* Must have been Qnil. */
4449 /* Initialize `default-minibuffer-frame' in case this is the first
4450 frame on this terminal. */
4451 if (FRAME_HAS_MINIBUF_P (f)
4452 && (!FRAMEP (kb->Vdefault_minibuffer_frame)
4453 || !FRAME_LIVE_P (XFRAME (kb->Vdefault_minibuffer_frame))))
4454 kb->Vdefault_minibuffer_frame = frame;
4456 /* All remaining specified parameters, which have not been "used"
4457 by x_get_arg and friends, now go in the misc. alist of the frame. */
4458 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4459 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4460 f->param_alist = Fcons (XCAR (tem), f->param_alist);
4462 UNGCPRO;
4464 /* Make sure windows on this frame appear in calls to next-window
4465 and similar functions. */
4466 Vwindow_list = Qnil;
4468 return unbind_to (count, frame);
4471 /* FRAME is used only to get a handle on the X display. We don't pass the
4472 display info directly because we're called from frame.c, which doesn't
4473 know about that structure. */
4474 Lisp_Object
4475 x_get_focus_frame (frame)
4476 struct frame *frame;
4478 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (frame);
4479 Lisp_Object xfocus;
4480 if (! dpyinfo->w32_focus_frame)
4481 return Qnil;
4483 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4484 return xfocus;
4487 DEFUN ("x-focus-frame", Fx_focus_frame, Sx_focus_frame, 1, 1, 0,
4488 doc: /* Give FRAME input focus, raising to foreground if necessary. */)
4489 (frame)
4490 Lisp_Object frame;
4492 x_focus_on_frame (check_x_frame (frame));
4493 return Qnil;
4497 /* Return the charset portion of a font name. */
4498 char *
4499 xlfd_charset_of_font (char * fontname)
4501 char *charset, *encoding;
4503 encoding = strrchr (fontname, '-');
4504 if (!encoding || encoding == fontname)
4505 return NULL;
4507 for (charset = encoding - 1; charset >= fontname; charset--)
4508 if (*charset == '-')
4509 break;
4511 if (charset == fontname || strcmp (charset, "-*-*") == 0)
4512 return NULL;
4514 return charset + 1;
4517 struct font_info *w32_load_bdf_font (struct frame *f, char *fontname,
4518 int size, char* filename);
4519 static Lisp_Object w32_list_bdf_fonts (Lisp_Object pattern, int max_names);
4520 static BOOL w32_to_x_font (LOGFONT * lplf, char * lpxstr, int len,
4521 char * charset);
4522 static BOOL x_to_w32_font (char *lpxstr, LOGFONT *lplogfont);
4524 static struct font_info *
4525 w32_load_system_font (f, fontname, size)
4526 struct frame *f;
4527 char * fontname;
4528 int size;
4530 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4531 Lisp_Object font_names;
4533 /* Get a list of all the fonts that match this name. Once we
4534 have a list of matching fonts, we compare them against the fonts
4535 we already have loaded by comparing names. */
4536 font_names = w32_list_fonts (f, build_string (fontname), size, 100);
4538 if (!NILP (font_names))
4540 Lisp_Object tail;
4541 int i;
4543 /* First check if any are already loaded, as that is cheaper
4544 than loading another one. */
4545 for (i = 0; i < dpyinfo->n_fonts; i++)
4546 for (tail = font_names; CONSP (tail); tail = XCDR (tail))
4547 if (dpyinfo->font_table[i].name
4548 && (!strcmp (dpyinfo->font_table[i].name,
4549 SDATA (XCAR (tail)))
4550 || !strcmp (dpyinfo->font_table[i].full_name,
4551 SDATA (XCAR (tail)))))
4552 return (dpyinfo->font_table + i);
4554 fontname = (char *) SDATA (XCAR (font_names));
4556 else if (w32_strict_fontnames)
4558 /* If EnumFontFamiliesEx was available, we got a full list of
4559 fonts back so stop now to avoid the possibility of loading a
4560 random font. If we had to fall back to EnumFontFamilies, the
4561 list is incomplete, so continue whether the font we want was
4562 listed or not. */
4563 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
4564 FARPROC enum_font_families_ex
4565 = GetProcAddress (gdi32, "EnumFontFamiliesExA");
4566 if (enum_font_families_ex)
4567 return NULL;
4570 /* Load the font and add it to the table. */
4572 char *full_name, *encoding, *charset;
4573 XFontStruct *font;
4574 struct font_info *fontp;
4575 LOGFONT lf;
4576 BOOL ok;
4577 int codepage;
4578 int i;
4580 if (!fontname || !x_to_w32_font (fontname, &lf))
4581 return (NULL);
4583 if (!*lf.lfFaceName)
4584 /* If no name was specified for the font, we get a random font
4585 from CreateFontIndirect - this is not particularly
4586 desirable, especially since CreateFontIndirect does not
4587 fill out the missing name in lf, so we never know what we
4588 ended up with. */
4589 return NULL;
4591 lf.lfQuality = DEFAULT_QUALITY;
4593 font = (XFontStruct *) xmalloc (sizeof (XFontStruct));
4594 bzero (font, sizeof (*font));
4596 /* Set bdf to NULL to indicate that this is a Windows font. */
4597 font->bdf = NULL;
4599 BLOCK_INPUT;
4601 font->hfont = CreateFontIndirect (&lf);
4603 if (font->hfont == NULL)
4605 ok = FALSE;
4607 else
4609 HDC hdc;
4610 HANDLE oldobj;
4612 codepage = w32_codepage_for_font (fontname);
4614 hdc = GetDC (dpyinfo->root_window);
4615 oldobj = SelectObject (hdc, font->hfont);
4617 ok = GetTextMetrics (hdc, &font->tm);
4618 if (codepage == CP_UNICODE)
4619 font->double_byte_p = 1;
4620 else
4622 /* Unfortunately, some fonts (eg. MingLiU, a big5 ttf font)
4623 don't report themselves as double byte fonts, when
4624 patently they are. So instead of trusting
4625 GetFontLanguageInfo, we check the properties of the
4626 codepage directly, since that is ultimately what we are
4627 working from anyway. */
4628 /* font->double_byte_p = GetFontLanguageInfo (hdc) & GCP_DBCS; */
4629 CPINFO cpi = {0};
4630 GetCPInfo (codepage, &cpi);
4631 font->double_byte_p = cpi.MaxCharSize > 1;
4634 SelectObject (hdc, oldobj);
4635 ReleaseDC (dpyinfo->root_window, hdc);
4636 /* Fill out details in lf according to the font that was
4637 actually loaded. */
4638 lf.lfHeight = font->tm.tmInternalLeading - font->tm.tmHeight;
4639 lf.lfWidth = font->tm.tmMaxCharWidth;
4640 lf.lfWeight = font->tm.tmWeight;
4641 lf.lfItalic = font->tm.tmItalic;
4642 lf.lfCharSet = font->tm.tmCharSet;
4643 lf.lfPitchAndFamily = ((font->tm.tmPitchAndFamily & TMPF_FIXED_PITCH)
4644 ? VARIABLE_PITCH : FIXED_PITCH);
4645 lf.lfOutPrecision = ((font->tm.tmPitchAndFamily & TMPF_VECTOR)
4646 ? OUT_STROKE_PRECIS : OUT_STRING_PRECIS);
4648 w32_cache_char_metrics (font);
4651 UNBLOCK_INPUT;
4653 if (!ok)
4655 w32_unload_font (dpyinfo, font);
4656 return (NULL);
4659 /* Find a free slot in the font table. */
4660 for (i = 0; i < dpyinfo->n_fonts; ++i)
4661 if (dpyinfo->font_table[i].name == NULL)
4662 break;
4664 /* If no free slot found, maybe enlarge the font table. */
4665 if (i == dpyinfo->n_fonts
4666 && dpyinfo->n_fonts == dpyinfo->font_table_size)
4668 int sz;
4669 dpyinfo->font_table_size = max (16, 2 * dpyinfo->font_table_size);
4670 sz = dpyinfo->font_table_size * sizeof *dpyinfo->font_table;
4671 dpyinfo->font_table
4672 = (struct font_info *) xrealloc (dpyinfo->font_table, sz);
4675 fontp = dpyinfo->font_table + i;
4676 if (i == dpyinfo->n_fonts)
4677 ++dpyinfo->n_fonts;
4679 /* Now fill in the slots of *FONTP. */
4680 BLOCK_INPUT;
4681 bzero (fontp, sizeof (*fontp));
4682 fontp->font = font;
4683 fontp->font_idx = i;
4684 fontp->name = (char *) xmalloc (strlen (fontname) + 1);
4685 bcopy (fontname, fontp->name, strlen (fontname) + 1);
4687 if (lf.lfPitchAndFamily == FIXED_PITCH)
4689 /* Fixed width font. */
4690 fontp->average_width = fontp->space_width = FONT_WIDTH (font);
4692 else
4694 wchar_t space = 32;
4695 XCharStruct* pcm;
4696 pcm = w32_per_char_metric (font, &space, ANSI_FONT);
4697 if (pcm)
4698 fontp->space_width = pcm->width;
4699 else
4700 fontp->space_width = FONT_WIDTH (font);
4702 fontp->average_width = font->tm.tmAveCharWidth;
4705 charset = xlfd_charset_of_font (fontname);
4707 /* Cache the W32 codepage for a font. This makes w32_encode_char
4708 (called for every glyph during redisplay) much faster. */
4709 fontp->codepage = codepage;
4711 /* Work out the font's full name. */
4712 full_name = (char *)xmalloc (100);
4713 if (full_name && w32_to_x_font (&lf, full_name, 100, charset))
4714 fontp->full_name = full_name;
4715 else
4717 /* If all else fails - just use the name we used to load it. */
4718 xfree (full_name);
4719 fontp->full_name = fontp->name;
4722 fontp->size = FONT_WIDTH (font);
4723 fontp->height = FONT_HEIGHT (font);
4725 /* The slot `encoding' specifies how to map a character
4726 code-points (0x20..0x7F or 0x2020..0x7F7F) of each charset to
4727 the font code-points (0:0x20..0x7F, 1:0xA0..0xFF), or
4728 (0:0x20..0x7F, 1:0xA0..0xFF,
4729 (0:0x2020..0x7F7F, 1:0xA0A0..0xFFFF, 3:0x20A0..0x7FFF,
4730 2:0xA020..0xFF7F). For the moment, we don't know which charset
4731 uses this font. So, we set information in fontp->encoding[1]
4732 which is never used by any charset. If mapping can't be
4733 decided, set FONT_ENCODING_NOT_DECIDED. */
4735 /* SJIS fonts need to be set to type 4, all others seem to work as
4736 type FONT_ENCODING_NOT_DECIDED. */
4737 encoding = strrchr (fontp->name, '-');
4738 if (encoding && strnicmp (encoding+1, "sjis", 4) == 0)
4739 fontp->encoding[1] = 4;
4740 else
4741 fontp->encoding[1] = FONT_ENCODING_NOT_DECIDED;
4743 /* The following three values are set to 0 under W32, which is
4744 what they get set to if XGetFontProperty fails under X. */
4745 fontp->baseline_offset = 0;
4746 fontp->relative_compose = 0;
4747 fontp->default_ascent = 0;
4749 /* Set global flag fonts_changed_p to non-zero if the font loaded
4750 has a character with a smaller width than any other character
4751 before, or if the font loaded has a smaller height than any
4752 other font loaded before. If this happens, it will make a
4753 glyph matrix reallocation necessary. */
4754 fonts_changed_p |= x_compute_min_glyph_bounds (f);
4755 UNBLOCK_INPUT;
4756 return fontp;
4760 /* Load font named FONTNAME of size SIZE for frame F, and return a
4761 pointer to the structure font_info while allocating it dynamically.
4762 If loading fails, return NULL. */
4763 struct font_info *
4764 w32_load_font (f, fontname, size)
4765 struct frame *f;
4766 char * fontname;
4767 int size;
4769 Lisp_Object bdf_fonts;
4770 struct font_info *retval = NULL;
4771 struct w32_display_info *dpyinfo = FRAME_W32_DISPLAY_INFO (f);
4773 bdf_fonts = w32_list_bdf_fonts (build_string (fontname), 1);
4775 while (!retval && CONSP (bdf_fonts))
4777 char *bdf_name, *bdf_file;
4778 Lisp_Object bdf_pair;
4779 int i;
4781 bdf_name = SDATA (XCAR (bdf_fonts));
4782 bdf_pair = Fassoc (XCAR (bdf_fonts), Vw32_bdf_filename_alist);
4783 bdf_file = SDATA (XCDR (bdf_pair));
4785 // If the font is already loaded, do not load it again.
4786 for (i = 0; i < dpyinfo->n_fonts; i++)
4788 if ((dpyinfo->font_table[i].name
4789 && !strcmp (dpyinfo->font_table[i].name, bdf_name))
4790 || (dpyinfo->font_table[i].full_name
4791 && !strcmp (dpyinfo->font_table[i].full_name, bdf_name)))
4792 return dpyinfo->font_table + i;
4795 retval = w32_load_bdf_font (f, bdf_name, size, bdf_file);
4797 bdf_fonts = XCDR (bdf_fonts);
4800 if (retval)
4801 return retval;
4803 return w32_load_system_font (f, fontname, size);
4807 void
4808 w32_unload_font (dpyinfo, font)
4809 struct w32_display_info *dpyinfo;
4810 XFontStruct * font;
4812 if (font)
4814 if (font->per_char) xfree (font->per_char);
4815 if (font->bdf) w32_free_bdf_font (font->bdf);
4817 if (font->hfont) DeleteObject (font->hfont);
4818 xfree (font);
4822 /* The font conversion stuff between x and w32 */
4824 /* X font string is as follows (from faces.el)
4825 * (let ((- "[-?]")
4826 * (foundry "[^-]+")
4827 * (family "[^-]+")
4828 * (weight "\\(bold\\|demibold\\|medium\\)") ; 1
4829 * (weight\? "\\([^-]*\\)") ; 1
4830 * (slant "\\([ior]\\)") ; 2
4831 * (slant\? "\\([^-]?\\)") ; 2
4832 * (swidth "\\([^-]*\\)") ; 3
4833 * (adstyle "[^-]*") ; 4
4834 * (pixelsize "[0-9]+")
4835 * (pointsize "[0-9][0-9]+")
4836 * (resx "[0-9][0-9]+")
4837 * (resy "[0-9][0-9]+")
4838 * (spacing "[cmp?*]")
4839 * (avgwidth "[0-9]+")
4840 * (registry "[^-]+")
4841 * (encoding "[^-]+")
4845 static LONG
4846 x_to_w32_weight (lpw)
4847 char * lpw;
4849 if (!lpw) return (FW_DONTCARE);
4851 if (stricmp (lpw, "heavy") == 0) return FW_HEAVY;
4852 else if (stricmp (lpw, "extrabold") == 0) return FW_EXTRABOLD;
4853 else if (stricmp (lpw, "bold") == 0) return FW_BOLD;
4854 else if (stricmp (lpw, "demibold") == 0) return FW_SEMIBOLD;
4855 else if (stricmp (lpw, "semibold") == 0) return FW_SEMIBOLD;
4856 else if (stricmp (lpw, "medium") == 0) return FW_MEDIUM;
4857 else if (stricmp (lpw, "normal") == 0) return FW_NORMAL;
4858 else if (stricmp (lpw, "light") == 0) return FW_LIGHT;
4859 else if (stricmp (lpw, "extralight") == 0) return FW_EXTRALIGHT;
4860 else if (stricmp (lpw, "thin") == 0) return FW_THIN;
4861 else
4862 return FW_DONTCARE;
4866 static char *
4867 w32_to_x_weight (fnweight)
4868 int fnweight;
4870 if (fnweight >= FW_HEAVY) return "heavy";
4871 if (fnweight >= FW_EXTRABOLD) return "extrabold";
4872 if (fnweight >= FW_BOLD) return "bold";
4873 if (fnweight >= FW_SEMIBOLD) return "demibold";
4874 if (fnweight >= FW_MEDIUM) return "medium";
4875 if (fnweight >= FW_NORMAL) return "normal";
4876 if (fnweight >= FW_LIGHT) return "light";
4877 if (fnweight >= FW_EXTRALIGHT) return "extralight";
4878 if (fnweight >= FW_THIN) return "thin";
4879 else
4880 return "*";
4883 static LONG
4884 x_to_w32_charset (lpcs)
4885 char * lpcs;
4887 Lisp_Object this_entry, w32_charset;
4888 char *charset;
4889 int len = strlen (lpcs);
4891 /* Support "*-#nnn" format for unknown charsets. */
4892 if (strncmp (lpcs, "*-#", 3) == 0)
4893 return atoi (lpcs + 3);
4895 /* Handle wildcards by ignoring them; eg. treat "big5*-*" as "big5". */
4896 charset = alloca (len + 1);
4897 strcpy (charset, lpcs);
4898 lpcs = strchr (charset, '*');
4899 if (lpcs)
4900 *lpcs = 0;
4902 /* Look through w32-charset-info-alist for the character set.
4903 Format of each entry is
4904 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
4906 this_entry = Fassoc (build_string (charset), Vw32_charset_info_alist);
4908 if (NILP (this_entry))
4910 /* At startup, we want iso8859-1 fonts to come up properly. */
4911 if (stricmp (charset, "iso8859-1") == 0)
4912 return ANSI_CHARSET;
4913 else
4914 return DEFAULT_CHARSET;
4917 w32_charset = Fcar (Fcdr (this_entry));
4919 /* Translate Lisp symbol to number. */
4920 if (EQ (w32_charset, Qw32_charset_ansi))
4921 return ANSI_CHARSET;
4922 if (EQ (w32_charset, Qw32_charset_symbol))
4923 return SYMBOL_CHARSET;
4924 if (EQ (w32_charset, Qw32_charset_shiftjis))
4925 return SHIFTJIS_CHARSET;
4926 if (EQ (w32_charset, Qw32_charset_hangeul))
4927 return HANGEUL_CHARSET;
4928 if (EQ (w32_charset, Qw32_charset_chinesebig5))
4929 return CHINESEBIG5_CHARSET;
4930 if (EQ (w32_charset, Qw32_charset_gb2312))
4931 return GB2312_CHARSET;
4932 if (EQ (w32_charset, Qw32_charset_oem))
4933 return OEM_CHARSET;
4934 #ifdef JOHAB_CHARSET
4935 if (EQ (w32_charset, Qw32_charset_johab))
4936 return JOHAB_CHARSET;
4937 if (EQ (w32_charset, Qw32_charset_easteurope))
4938 return EASTEUROPE_CHARSET;
4939 if (EQ (w32_charset, Qw32_charset_turkish))
4940 return TURKISH_CHARSET;
4941 if (EQ (w32_charset, Qw32_charset_baltic))
4942 return BALTIC_CHARSET;
4943 if (EQ (w32_charset, Qw32_charset_russian))
4944 return RUSSIAN_CHARSET;
4945 if (EQ (w32_charset, Qw32_charset_arabic))
4946 return ARABIC_CHARSET;
4947 if (EQ (w32_charset, Qw32_charset_greek))
4948 return GREEK_CHARSET;
4949 if (EQ (w32_charset, Qw32_charset_hebrew))
4950 return HEBREW_CHARSET;
4951 if (EQ (w32_charset, Qw32_charset_vietnamese))
4952 return VIETNAMESE_CHARSET;
4953 if (EQ (w32_charset, Qw32_charset_thai))
4954 return THAI_CHARSET;
4955 if (EQ (w32_charset, Qw32_charset_mac))
4956 return MAC_CHARSET;
4957 #endif /* JOHAB_CHARSET */
4958 #ifdef UNICODE_CHARSET
4959 if (EQ (w32_charset, Qw32_charset_unicode))
4960 return UNICODE_CHARSET;
4961 #endif
4963 return DEFAULT_CHARSET;
4967 static char *
4968 w32_to_x_charset (fncharset)
4969 int fncharset;
4971 static char buf[32];
4972 Lisp_Object charset_type;
4974 switch (fncharset)
4976 case ANSI_CHARSET:
4977 /* Handle startup case of w32-charset-info-alist not
4978 being set up yet. */
4979 if (NILP (Vw32_charset_info_alist))
4980 return "iso8859-1";
4981 charset_type = Qw32_charset_ansi;
4982 break;
4983 case DEFAULT_CHARSET:
4984 charset_type = Qw32_charset_default;
4985 break;
4986 case SYMBOL_CHARSET:
4987 charset_type = Qw32_charset_symbol;
4988 break;
4989 case SHIFTJIS_CHARSET:
4990 charset_type = Qw32_charset_shiftjis;
4991 break;
4992 case HANGEUL_CHARSET:
4993 charset_type = Qw32_charset_hangeul;
4994 break;
4995 case GB2312_CHARSET:
4996 charset_type = Qw32_charset_gb2312;
4997 break;
4998 case CHINESEBIG5_CHARSET:
4999 charset_type = Qw32_charset_chinesebig5;
5000 break;
5001 case OEM_CHARSET:
5002 charset_type = Qw32_charset_oem;
5003 break;
5005 /* More recent versions of Windows (95 and NT4.0) define more
5006 character sets. */
5007 #ifdef EASTEUROPE_CHARSET
5008 case EASTEUROPE_CHARSET:
5009 charset_type = Qw32_charset_easteurope;
5010 break;
5011 case TURKISH_CHARSET:
5012 charset_type = Qw32_charset_turkish;
5013 break;
5014 case BALTIC_CHARSET:
5015 charset_type = Qw32_charset_baltic;
5016 break;
5017 case RUSSIAN_CHARSET:
5018 charset_type = Qw32_charset_russian;
5019 break;
5020 case ARABIC_CHARSET:
5021 charset_type = Qw32_charset_arabic;
5022 break;
5023 case GREEK_CHARSET:
5024 charset_type = Qw32_charset_greek;
5025 break;
5026 case HEBREW_CHARSET:
5027 charset_type = Qw32_charset_hebrew;
5028 break;
5029 case VIETNAMESE_CHARSET:
5030 charset_type = Qw32_charset_vietnamese;
5031 break;
5032 case THAI_CHARSET:
5033 charset_type = Qw32_charset_thai;
5034 break;
5035 case MAC_CHARSET:
5036 charset_type = Qw32_charset_mac;
5037 break;
5038 case JOHAB_CHARSET:
5039 charset_type = Qw32_charset_johab;
5040 break;
5041 #endif
5043 #ifdef UNICODE_CHARSET
5044 case UNICODE_CHARSET:
5045 charset_type = Qw32_charset_unicode;
5046 break;
5047 #endif
5048 default:
5049 /* Encode numerical value of unknown charset. */
5050 sprintf (buf, "*-#%u", fncharset);
5051 return buf;
5055 Lisp_Object rest;
5056 char * best_match = NULL;
5058 /* Look through w32-charset-info-alist for the character set.
5059 Prefer ISO codepages, and prefer lower numbers in the ISO
5060 range. Only return charsets for codepages which are installed.
5062 Format of each entry is
5063 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5065 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5067 char * x_charset;
5068 Lisp_Object w32_charset;
5069 Lisp_Object codepage;
5071 Lisp_Object this_entry = XCAR (rest);
5073 /* Skip invalid entries in alist. */
5074 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5075 || !CONSP (XCDR (this_entry))
5076 || !SYMBOLP (XCAR (XCDR (this_entry))))
5077 continue;
5079 x_charset = SDATA (XCAR (this_entry));
5080 w32_charset = XCAR (XCDR (this_entry));
5081 codepage = XCDR (XCDR (this_entry));
5083 /* Look for Same charset and a valid codepage (or non-int
5084 which means ignore). */
5085 if (EQ (w32_charset, charset_type)
5086 && (!INTEGERP (codepage) || XINT (codepage) == CP_DEFAULT
5087 || IsValidCodePage (XINT (codepage))))
5089 /* If we don't have a match already, then this is the
5090 best. */
5091 if (!best_match)
5092 best_match = x_charset;
5093 /* If this is an ISO codepage, and the best so far isn't,
5094 then this is better. */
5095 else if (strnicmp (best_match, "iso", 3) != 0
5096 && strnicmp (x_charset, "iso", 3) == 0)
5097 best_match = x_charset;
5098 /* If both are ISO8859 codepages, choose the one with the
5099 lowest number in the encoding field. */
5100 else if (strnicmp (best_match, "iso8859-", 8) == 0
5101 && strnicmp (x_charset, "iso8859-", 8) == 0)
5103 int best_enc = atoi (best_match + 8);
5104 int this_enc = atoi (x_charset + 8);
5105 if (this_enc > 0 && this_enc < best_enc)
5106 best_match = x_charset;
5111 /* If no match, encode the numeric value. */
5112 if (!best_match)
5114 sprintf (buf, "*-#%u", fncharset);
5115 return buf;
5118 strncpy (buf, best_match, 31);
5119 buf[31] = '\0';
5120 return buf;
5125 /* Return all the X charsets that map to a font. */
5126 static Lisp_Object
5127 w32_to_all_x_charsets (fncharset)
5128 int fncharset;
5130 static char buf[32];
5131 Lisp_Object charset_type;
5132 Lisp_Object retval = Qnil;
5134 switch (fncharset)
5136 case ANSI_CHARSET:
5137 /* Handle startup case of w32-charset-info-alist not
5138 being set up yet. */
5139 if (NILP (Vw32_charset_info_alist))
5140 return Fcons (build_string ("iso8859-1"), Qnil);
5142 charset_type = Qw32_charset_ansi;
5143 break;
5144 case DEFAULT_CHARSET:
5145 charset_type = Qw32_charset_default;
5146 break;
5147 case SYMBOL_CHARSET:
5148 charset_type = Qw32_charset_symbol;
5149 break;
5150 case SHIFTJIS_CHARSET:
5151 charset_type = Qw32_charset_shiftjis;
5152 break;
5153 case HANGEUL_CHARSET:
5154 charset_type = Qw32_charset_hangeul;
5155 break;
5156 case GB2312_CHARSET:
5157 charset_type = Qw32_charset_gb2312;
5158 break;
5159 case CHINESEBIG5_CHARSET:
5160 charset_type = Qw32_charset_chinesebig5;
5161 break;
5162 case OEM_CHARSET:
5163 charset_type = Qw32_charset_oem;
5164 break;
5166 /* More recent versions of Windows (95 and NT4.0) define more
5167 character sets. */
5168 #ifdef EASTEUROPE_CHARSET
5169 case EASTEUROPE_CHARSET:
5170 charset_type = Qw32_charset_easteurope;
5171 break;
5172 case TURKISH_CHARSET:
5173 charset_type = Qw32_charset_turkish;
5174 break;
5175 case BALTIC_CHARSET:
5176 charset_type = Qw32_charset_baltic;
5177 break;
5178 case RUSSIAN_CHARSET:
5179 charset_type = Qw32_charset_russian;
5180 break;
5181 case ARABIC_CHARSET:
5182 charset_type = Qw32_charset_arabic;
5183 break;
5184 case GREEK_CHARSET:
5185 charset_type = Qw32_charset_greek;
5186 break;
5187 case HEBREW_CHARSET:
5188 charset_type = Qw32_charset_hebrew;
5189 break;
5190 case VIETNAMESE_CHARSET:
5191 charset_type = Qw32_charset_vietnamese;
5192 break;
5193 case THAI_CHARSET:
5194 charset_type = Qw32_charset_thai;
5195 break;
5196 case MAC_CHARSET:
5197 charset_type = Qw32_charset_mac;
5198 break;
5199 case JOHAB_CHARSET:
5200 charset_type = Qw32_charset_johab;
5201 break;
5202 #endif
5204 #ifdef UNICODE_CHARSET
5205 case UNICODE_CHARSET:
5206 charset_type = Qw32_charset_unicode;
5207 break;
5208 #endif
5209 default:
5210 /* Encode numerical value of unknown charset. */
5211 sprintf (buf, "*-#%u", fncharset);
5212 return Fcons (build_string (buf), Qnil);
5216 Lisp_Object rest;
5217 /* Look through w32-charset-info-alist for the character set.
5218 Only return charsets for codepages which are installed.
5220 Format of each entry in Vw32_charset_info_alist is
5221 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE)).
5223 for (rest = Vw32_charset_info_alist; CONSP (rest); rest = XCDR (rest))
5225 Lisp_Object x_charset;
5226 Lisp_Object w32_charset;
5227 Lisp_Object codepage;
5229 Lisp_Object this_entry = XCAR (rest);
5231 /* Skip invalid entries in alist. */
5232 if (!CONSP (this_entry) || !STRINGP (XCAR (this_entry))
5233 || !CONSP (XCDR (this_entry))
5234 || !SYMBOLP (XCAR (XCDR (this_entry))))
5235 continue;
5237 x_charset = XCAR (this_entry);
5238 w32_charset = XCAR (XCDR (this_entry));
5239 codepage = XCDR (XCDR (this_entry));
5241 /* Look for Same charset and a valid codepage (or non-int
5242 which means ignore). */
5243 if (EQ (w32_charset, charset_type)
5244 && (!INTEGERP (codepage) || XINT (codepage) == CP_DEFAULT
5245 || IsValidCodePage (XINT (codepage))))
5247 retval = Fcons (x_charset, retval);
5251 /* If no match, encode the numeric value. */
5252 if (NILP (retval))
5254 sprintf (buf, "*-#%u", fncharset);
5255 return Fcons (build_string (buf), Qnil);
5258 return retval;
5262 /* Get the Windows codepage corresponding to the specified font. The
5263 charset info in the font name is used to look up
5264 w32-charset-to-codepage-alist. */
5266 w32_codepage_for_font (char *fontname)
5268 Lisp_Object codepage, entry;
5269 char *charset_str, *charset, *end;
5271 if (NILP (Vw32_charset_info_alist))
5272 return CP_DEFAULT;
5274 /* Extract charset part of font string. */
5275 charset = xlfd_charset_of_font (fontname);
5277 if (!charset)
5278 return CP_UNKNOWN;
5280 charset_str = (char *) alloca (strlen (charset) + 1);
5281 strcpy (charset_str, charset);
5283 #if 0
5284 /* Remove leading "*-". */
5285 if (strncmp ("*-", charset_str, 2) == 0)
5286 charset = charset_str + 2;
5287 else
5288 #endif
5289 charset = charset_str;
5291 /* Stop match at wildcard (including preceding '-'). */
5292 if (end = strchr (charset, '*'))
5294 if (end > charset && *(end-1) == '-')
5295 end--;
5296 *end = '\0';
5299 entry = Fassoc (build_string (charset), Vw32_charset_info_alist);
5300 if (NILP (entry))
5301 return CP_UNKNOWN;
5303 codepage = Fcdr (Fcdr (entry));
5305 if (NILP (codepage))
5306 return CP_8BIT;
5307 else if (XFASTINT (codepage) == XFASTINT (Qt))
5308 return CP_UNICODE;
5309 else if (INTEGERP (codepage))
5310 return XINT (codepage);
5311 else
5312 return CP_UNKNOWN;
5316 static BOOL
5317 w32_to_x_font (lplogfont, lpxstr, len, specific_charset)
5318 LOGFONT * lplogfont;
5319 char * lpxstr;
5320 int len;
5321 char * specific_charset;
5323 char* fonttype;
5324 char *fontname;
5325 char height_pixels[8];
5326 char height_dpi[8];
5327 char width_pixels[8];
5328 char *fontname_dash;
5329 int display_resy = (int) one_w32_display_info.resy;
5330 int display_resx = (int) one_w32_display_info.resx;
5331 int bufsz;
5332 struct coding_system coding;
5334 if (!lpxstr) abort ();
5336 if (!lplogfont)
5337 return FALSE;
5339 if (lplogfont->lfOutPrecision == OUT_STRING_PRECIS)
5340 fonttype = "raster";
5341 else if (lplogfont->lfOutPrecision == OUT_STROKE_PRECIS)
5342 fonttype = "outline";
5343 else
5344 fonttype = "unknown";
5346 setup_coding_system (Fcheck_coding_system (Vlocale_coding_system),
5347 &coding);
5348 coding.src_multibyte = 0;
5349 coding.dst_multibyte = 1;
5350 coding.mode |= CODING_MODE_LAST_BLOCK;
5351 /* We explicitely disable composition handling because selection
5352 data should not contain any composition sequence. */
5353 coding.composing = COMPOSITION_DISABLED;
5354 bufsz = decoding_buffer_size (&coding, LF_FACESIZE);
5356 fontname = alloca (sizeof (*fontname) * bufsz);
5357 decode_coding (&coding, lplogfont->lfFaceName, fontname,
5358 strlen (lplogfont->lfFaceName), bufsz - 1);
5359 *(fontname + coding.produced) = '\0';
5361 /* Replace dashes with underscores so the dashes are not
5362 misinterpreted. */
5363 fontname_dash = fontname;
5364 while (fontname_dash = strchr (fontname_dash, '-'))
5365 *fontname_dash = '_';
5367 if (lplogfont->lfHeight)
5369 sprintf (height_pixels, "%u", eabs (lplogfont->lfHeight));
5370 sprintf (height_dpi, "%u",
5371 eabs (lplogfont->lfHeight) * 720 / display_resy);
5373 else
5375 strcpy (height_pixels, "*");
5376 strcpy (height_dpi, "*");
5379 #if 0 /* Never put the width in the xfld. It fails on fonts with
5380 double-width characters. */
5381 if (lplogfont->lfWidth)
5382 sprintf (width_pixels, "%u", lplogfont->lfWidth * 10);
5383 else
5384 #endif
5385 strcpy (width_pixels, "*");
5387 _snprintf (lpxstr, len - 1,
5388 "-%s-%s-%s-%c-normal-normal-%s-%s-%d-%d-%c-%s-%s",
5389 fonttype, /* foundry */
5390 fontname, /* family */
5391 w32_to_x_weight (lplogfont->lfWeight), /* weight */
5392 lplogfont->lfItalic?'i':'r', /* slant */
5393 /* setwidth name */
5394 /* add style name */
5395 height_pixels, /* pixel size */
5396 height_dpi, /* point size */
5397 display_resx, /* resx */
5398 display_resy, /* resy */
5399 ((lplogfont->lfPitchAndFamily & 0x3) == VARIABLE_PITCH)
5400 ? 'p' : 'c', /* spacing */
5401 width_pixels, /* avg width */
5402 specific_charset ? specific_charset
5403 : w32_to_x_charset (lplogfont->lfCharSet)
5404 /* charset registry and encoding */
5407 lpxstr[len - 1] = 0; /* just to be sure */
5408 return (TRUE);
5411 static BOOL
5412 x_to_w32_font (lpxstr, lplogfont)
5413 char * lpxstr;
5414 LOGFONT * lplogfont;
5416 struct coding_system coding;
5418 if (!lplogfont) return (FALSE);
5420 memset (lplogfont, 0, sizeof (*lplogfont));
5422 /* Set default value for each field. */
5423 #if 1
5424 lplogfont->lfOutPrecision = OUT_DEFAULT_PRECIS;
5425 lplogfont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
5426 lplogfont->lfQuality = DEFAULT_QUALITY;
5427 #else
5428 /* go for maximum quality */
5429 lplogfont->lfOutPrecision = OUT_STROKE_PRECIS;
5430 lplogfont->lfClipPrecision = CLIP_STROKE_PRECIS;
5431 lplogfont->lfQuality = PROOF_QUALITY;
5432 #endif
5434 lplogfont->lfCharSet = DEFAULT_CHARSET;
5435 lplogfont->lfWeight = FW_DONTCARE;
5436 lplogfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
5438 if (!lpxstr)
5439 return FALSE;
5441 /* Provide a simple escape mechanism for specifying Windows font names
5442 * directly -- if font spec does not beginning with '-', assume this
5443 * format:
5444 * "<font name>[:height in pixels[:width in pixels[:weight]]]"
5447 if (*lpxstr == '-')
5449 int fields, tem;
5450 char name[50], weight[20], slant, pitch, pixels[10], height[10],
5451 width[10], resy[10], remainder[50];
5452 char * encoding;
5453 int dpi = (int) one_w32_display_info.resy;
5455 fields = sscanf (lpxstr,
5456 "-%*[^-]-%49[^-]-%19[^-]-%c-%*[^-]-%*[^-]-%9[^-]-%9[^-]-%*[^-]-%9[^-]-%c-%9[^-]-%49s",
5457 name, weight, &slant, pixels, height, resy, &pitch, width, remainder);
5458 if (fields == EOF)
5459 return (FALSE);
5461 /* In the general case when wildcards cover more than one field,
5462 we don't know which field is which, so don't fill any in.
5463 However, we need to cope with this particular form, which is
5464 generated by font_list_1 (invoked by try_font_list):
5465 "-raster-6x10-*-gb2312*-*"
5466 and make sure to correctly parse the charset field. */
5467 if (fields == 3)
5469 fields = sscanf (lpxstr,
5470 "-%*[^-]-%49[^-]-*-%49s",
5471 name, remainder);
5473 else if (fields < 9)
5475 fields = 0;
5476 remainder[0] = 0;
5479 if (fields > 0 && name[0] != '*')
5481 int bufsize;
5482 unsigned char *buf;
5484 setup_coding_system
5485 (Fcheck_coding_system (Vlocale_coding_system), &coding);
5486 coding.src_multibyte = 1;
5487 coding.dst_multibyte = 0;
5488 /* Need to set COMPOSITION_DISABLED, otherwise Emacs crashes in
5489 encode_coding_iso2022 trying to dereference a null pointer. */
5490 coding.composing = COMPOSITION_DISABLED;
5491 if (coding.type == coding_type_iso2022)
5492 coding.flags |= CODING_FLAG_ISO_SAFE;
5493 bufsize = encoding_buffer_size (&coding, strlen (name));
5494 buf = (unsigned char *) alloca (bufsize);
5495 coding.mode |= CODING_MODE_LAST_BLOCK;
5496 encode_coding (&coding, name, buf, strlen (name), bufsize);
5497 if (coding.produced >= LF_FACESIZE)
5498 coding.produced = LF_FACESIZE - 1;
5499 buf[coding.produced] = 0;
5500 strcpy (lplogfont->lfFaceName, buf);
5502 else
5504 lplogfont->lfFaceName[0] = '\0';
5507 fields--;
5509 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5511 fields--;
5513 lplogfont->lfItalic = (fields > 0 && slant == 'i');
5515 fields--;
5517 if (fields > 0 && pixels[0] != '*')
5518 lplogfont->lfHeight = atoi (pixels);
5520 fields--;
5521 fields--;
5522 if (fields > 0 && resy[0] != '*')
5524 tem = atoi (resy);
5525 if (tem > 0) dpi = tem;
5528 if (fields > -1 && lplogfont->lfHeight == 0 && height[0] != '*')
5529 lplogfont->lfHeight = atoi (height) * dpi / 720;
5531 if (fields > 0)
5532 lplogfont->lfPitchAndFamily =
5533 (fields > 0 && pitch == 'p') ? VARIABLE_PITCH : FIXED_PITCH;
5535 fields--;
5537 if (fields > 0 && width[0] != '*')
5538 lplogfont->lfWidth = atoi (width) / 10;
5540 fields--;
5542 /* Strip the trailing '-' if present. (it shouldn't be, as it
5543 fails the test against xlfd-tight-regexp in fontset.el). */
5545 int len = strlen (remainder);
5546 if (len > 0 && remainder[len-1] == '-')
5547 remainder[len-1] = 0;
5549 encoding = remainder;
5550 #if 0
5551 if (strncmp (encoding, "*-", 2) == 0)
5552 encoding += 2;
5553 #endif
5554 lplogfont->lfCharSet = x_to_w32_charset (encoding);
5556 else
5558 int fields;
5559 char name[100], height[10], width[10], weight[20];
5561 fields = sscanf (lpxstr,
5562 "%99[^:]:%9[^:]:%9[^:]:%19s",
5563 name, height, width, weight);
5565 if (fields == EOF) return (FALSE);
5567 if (fields > 0)
5569 strncpy (lplogfont->lfFaceName, name, LF_FACESIZE);
5570 lplogfont->lfFaceName[LF_FACESIZE-1] = 0;
5572 else
5574 lplogfont->lfFaceName[0] = 0;
5577 fields--;
5579 if (fields > 0)
5580 lplogfont->lfHeight = atoi (height);
5582 fields--;
5584 if (fields > 0)
5585 lplogfont->lfWidth = atoi (width);
5587 fields--;
5589 lplogfont->lfWeight = x_to_w32_weight ((fields > 0 ? weight : ""));
5592 /* This makes TrueType fonts work better. */
5593 lplogfont->lfHeight = - eabs (lplogfont->lfHeight);
5595 return (TRUE);
5598 /* Strip the pixel height and point height from the given xlfd, and
5599 return the pixel height. If no pixel height is specified, calculate
5600 one from the point height, or if that isn't defined either, return
5601 0 (which usually signifies a scalable font).
5603 static int
5604 xlfd_strip_height (char *fontname)
5606 int pixel_height, field_number;
5607 char *read_from, *write_to;
5609 xassert (fontname);
5611 pixel_height = field_number = 0;
5612 write_to = NULL;
5614 /* Look for height fields. */
5615 for (read_from = fontname; *read_from; read_from++)
5617 if (*read_from == '-')
5619 field_number++;
5620 if (field_number == 7) /* Pixel height. */
5622 read_from++;
5623 write_to = read_from;
5625 /* Find end of field. */
5626 for (;*read_from && *read_from != '-'; read_from++)
5629 /* Split the fontname at end of field. */
5630 if (*read_from)
5632 *read_from = '\0';
5633 read_from++;
5635 pixel_height = atoi (write_to);
5636 /* Blank out field. */
5637 if (read_from > write_to)
5639 *write_to = '-';
5640 write_to++;
5642 /* If the pixel height field is at the end (partial xlfd),
5643 return now. */
5644 else
5645 return pixel_height;
5647 /* If we got a pixel height, the point height can be
5648 ignored. Just blank it out and break now. */
5649 if (pixel_height)
5651 /* Find end of point size field. */
5652 for (; *read_from && *read_from != '-'; read_from++)
5655 if (*read_from)
5656 read_from++;
5658 /* Blank out the point size field. */
5659 if (read_from > write_to)
5661 *write_to = '-';
5662 write_to++;
5664 else
5665 return pixel_height;
5667 break;
5669 /* If the point height is already blank, break now. */
5670 if (*read_from == '-')
5672 read_from++;
5673 break;
5676 else if (field_number == 8)
5678 /* If we didn't get a pixel height, try to get the point
5679 height and convert that. */
5680 int point_size;
5681 char *point_size_start = read_from++;
5683 /* Find end of field. */
5684 for (; *read_from && *read_from != '-'; read_from++)
5687 if (*read_from)
5689 *read_from = '\0';
5690 read_from++;
5693 point_size = atoi (point_size_start);
5695 /* Convert to pixel height. */
5696 pixel_height = point_size
5697 * one_w32_display_info.height_in / 720;
5699 /* Blank out this field and break. */
5700 *write_to = '-';
5701 write_to++;
5702 break;
5707 /* Shift the rest of the font spec into place. */
5708 if (write_to && read_from > write_to)
5710 for (; *read_from; read_from++, write_to++)
5711 *write_to = *read_from;
5712 *write_to = '\0';
5715 return pixel_height;
5718 /* Assume parameter 1 is fully qualified, no wildcards. */
5719 static BOOL
5720 w32_font_match (fontname, pattern)
5721 char * fontname;
5722 char * pattern;
5724 char *ptr;
5725 char *font_name_copy;
5726 char *regex = alloca (strlen (pattern) * 2 + 3);
5728 font_name_copy = alloca (strlen (fontname) + 1);
5729 strcpy (font_name_copy, fontname);
5731 ptr = regex;
5732 *ptr++ = '^';
5734 /* Turn pattern into a regexp and do a regexp match. */
5735 for (; *pattern; pattern++)
5737 if (*pattern == '?')
5738 *ptr++ = '.';
5739 else if (*pattern == '*')
5741 *ptr++ = '.';
5742 *ptr++ = '*';
5744 else
5745 *ptr++ = *pattern;
5747 *ptr = '$';
5748 *(ptr + 1) = '\0';
5750 /* Strip out font heights and compare them seperately, since
5751 rounding error can cause mismatches. This also allows a
5752 comparison between a font that declares only a pixel height and a
5753 pattern that declares the point height.
5756 int font_height, pattern_height;
5758 font_height = xlfd_strip_height (font_name_copy);
5759 pattern_height = xlfd_strip_height (regex);
5761 /* Compare now, and don't bother doing expensive regexp matching
5762 if the heights differ. */
5763 if (font_height && pattern_height && (font_height != pattern_height))
5764 return FALSE;
5767 return (fast_string_match_ignore_case (build_string (regex),
5768 build_string (font_name_copy)) >= 0);
5771 /* Callback functions, and a structure holding info they need, for
5772 listing system fonts on W32. We need one set of functions to do the
5773 job properly, but these don't work on NT 3.51 and earlier, so we
5774 have a second set which don't handle character sets properly to
5775 fall back on.
5777 In both cases, there are two passes made. The first pass gets one
5778 font from each family, the second pass lists all the fonts from
5779 each family. */
5781 typedef struct enumfont_t
5783 HDC hdc;
5784 int numFonts;
5785 LOGFONT logfont;
5786 XFontStruct *size_ref;
5787 Lisp_Object pattern;
5788 Lisp_Object list;
5789 } enumfont_t;
5792 static void
5793 enum_font_maybe_add_to_list (enumfont_t *, LOGFONT *, char *, Lisp_Object);
5796 static int CALLBACK
5797 enum_font_cb2 (lplf, lptm, FontType, lpef)
5798 ENUMLOGFONT * lplf;
5799 NEWTEXTMETRIC * lptm;
5800 int FontType;
5801 enumfont_t * lpef;
5803 /* Ignore struck out and underlined versions of fonts. */
5804 if (lplf->elfLogFont.lfStrikeOut || lplf->elfLogFont.lfUnderline)
5805 return 1;
5807 /* Only return fonts with names starting with @ if they were
5808 explicitly specified, since Microsoft uses an initial @ to
5809 denote fonts for vertical writing, without providing a more
5810 convenient way of identifying them. */
5811 if (lplf->elfLogFont.lfFaceName[0] == '@'
5812 && lpef->logfont.lfFaceName[0] != '@')
5813 return 1;
5815 /* Check that the character set matches if it was specified */
5816 if (lpef->logfont.lfCharSet != DEFAULT_CHARSET &&
5817 lplf->elfLogFont.lfCharSet != lpef->logfont.lfCharSet)
5818 return 1;
5820 if (FontType == RASTER_FONTTYPE)
5822 /* DBCS raster fonts have problems displaying, so skip them. */
5823 int charset = lplf->elfLogFont.lfCharSet;
5824 if (charset == SHIFTJIS_CHARSET
5825 || charset == HANGEUL_CHARSET
5826 || charset == CHINESEBIG5_CHARSET
5827 || charset == GB2312_CHARSET
5828 #ifdef JOHAB_CHARSET
5829 || charset == JOHAB_CHARSET
5830 #endif
5832 return 1;
5836 char buf[100];
5837 Lisp_Object width = Qnil;
5838 Lisp_Object charset_list = Qnil;
5839 char *charset = NULL;
5841 /* Truetype fonts do not report their true metrics until loaded */
5842 if (FontType != RASTER_FONTTYPE)
5844 if (!NILP (lpef->pattern))
5846 /* Scalable fonts are as big as you want them to be. */
5847 lplf->elfLogFont.lfHeight = lpef->logfont.lfHeight;
5848 lplf->elfLogFont.lfWidth = lpef->logfont.lfWidth;
5849 width = make_number (lpef->logfont.lfWidth);
5851 else
5853 lplf->elfLogFont.lfHeight = 0;
5854 lplf->elfLogFont.lfWidth = 0;
5858 /* Make sure the height used here is the same as everywhere
5859 else (ie character height, not cell height). */
5860 if (lplf->elfLogFont.lfHeight > 0)
5862 /* lptm can be trusted for RASTER fonts, but not scalable ones. */
5863 if (FontType == RASTER_FONTTYPE)
5864 lplf->elfLogFont.lfHeight = lptm->tmInternalLeading - lptm->tmHeight;
5865 else
5866 lplf->elfLogFont.lfHeight = -lplf->elfLogFont.lfHeight;
5869 if (!NILP (lpef->pattern))
5871 charset = xlfd_charset_of_font (SDATA (lpef->pattern));
5873 /* We already checked charsets above, but DEFAULT_CHARSET
5874 slipped through. So only allow exact matches for DEFAULT_CHARSET. */
5875 if (charset
5876 && strncmp (charset, "*-*", 3) != 0
5877 && lpef->logfont.lfCharSet == DEFAULT_CHARSET
5878 && strcmp (charset, w32_to_x_charset (DEFAULT_CHARSET)) != 0)
5879 return 1;
5882 if (charset)
5883 charset_list = Fcons (build_string (charset), Qnil);
5884 else
5885 charset_list = w32_to_all_x_charsets (lplf->elfLogFont.lfCharSet);
5887 /* Loop through the charsets. */
5888 for ( ; CONSP (charset_list); charset_list = Fcdr (charset_list))
5890 Lisp_Object this_charset = Fcar (charset_list);
5891 charset = SDATA (this_charset);
5893 /* List bold and italic variations if w32-enable-synthesized-fonts
5894 is non-nil and this is a plain font. */
5895 if (w32_enable_synthesized_fonts
5896 && lplf->elfLogFont.lfWeight == FW_NORMAL
5897 && lplf->elfLogFont.lfItalic == FALSE)
5899 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5900 charset, width);
5901 /* bold. */
5902 lplf->elfLogFont.lfWeight = FW_BOLD;
5903 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5904 charset, width);
5905 /* bold italic. */
5906 lplf->elfLogFont.lfItalic = TRUE;
5907 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5908 charset, width);
5909 /* italic. */
5910 lplf->elfLogFont.lfWeight = FW_NORMAL;
5911 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5912 charset, width);
5914 else
5915 enum_font_maybe_add_to_list (lpef, &(lplf->elfLogFont),
5916 charset, width);
5920 return 1;
5923 static void
5924 enum_font_maybe_add_to_list (lpef, logfont, match_charset, width)
5925 enumfont_t * lpef;
5926 LOGFONT * logfont;
5927 char * match_charset;
5928 Lisp_Object width;
5930 char buf[100];
5932 if (!w32_to_x_font (logfont, buf, 100, match_charset))
5933 return;
5935 if (NILP (lpef->pattern)
5936 || w32_font_match (buf, SDATA (lpef->pattern)))
5938 /* Check if we already listed this font. This may happen if
5939 w32_enable_synthesized_fonts is non-nil, and there are real
5940 bold and italic versions of the font. */
5941 Lisp_Object font_name = build_string (buf);
5942 if (NILP (Fmember (font_name, lpef->list)))
5944 Lisp_Object entry = Fcons (font_name, width);
5945 lpef->list = Fcons (entry, lpef->list);
5946 lpef->numFonts++;
5952 static int CALLBACK
5953 enum_font_cb1 (lplf, lptm, FontType, lpef)
5954 ENUMLOGFONT * lplf;
5955 NEWTEXTMETRIC * lptm;
5956 int FontType;
5957 enumfont_t * lpef;
5959 return EnumFontFamilies (lpef->hdc,
5960 lplf->elfLogFont.lfFaceName,
5961 (FONTENUMPROC) enum_font_cb2,
5962 (LPARAM) lpef);
5966 static int CALLBACK
5967 enum_fontex_cb2 (lplf, lptm, font_type, lpef)
5968 ENUMLOGFONTEX * lplf;
5969 NEWTEXTMETRICEX * lptm;
5970 int font_type;
5971 enumfont_t * lpef;
5973 /* We are not interested in the extra info we get back from the 'Ex
5974 version - only the fact that we get character set variations
5975 enumerated seperately. */
5976 return enum_font_cb2 ((ENUMLOGFONT *) lplf, (NEWTEXTMETRIC *) lptm,
5977 font_type, lpef);
5980 static int CALLBACK
5981 enum_fontex_cb1 (lplf, lptm, font_type, lpef)
5982 ENUMLOGFONTEX * lplf;
5983 NEWTEXTMETRICEX * lptm;
5984 int font_type;
5985 enumfont_t * lpef;
5987 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
5988 FARPROC enum_font_families_ex
5989 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
5990 /* We don't really expect EnumFontFamiliesEx to disappear once we
5991 get here, so don't bother handling it gracefully. */
5992 if (enum_font_families_ex == NULL)
5993 error ("gdi32.dll has disappeared!");
5994 return enum_font_families_ex (lpef->hdc,
5995 &lplf->elfLogFont,
5996 (FONTENUMPROC) enum_fontex_cb2,
5997 (LPARAM) lpef, 0);
6000 /* Interface to fontset handler. (adapted from mw32font.c in Meadow
6001 and xterm.c in Emacs 20.3) */
6003 static Lisp_Object
6004 w32_list_bdf_fonts (Lisp_Object pattern, int max_names)
6006 char *fontname, *ptnstr;
6007 Lisp_Object list, tem, newlist = Qnil;
6008 int n_fonts = 0;
6010 list = Vw32_bdf_filename_alist;
6011 ptnstr = SDATA (pattern);
6013 for ( ; CONSP (list); list = XCDR (list))
6015 tem = XCAR (list);
6016 if (CONSP (tem))
6017 fontname = SDATA (XCAR (tem));
6018 else if (STRINGP (tem))
6019 fontname = SDATA (tem);
6020 else
6021 continue;
6023 if (w32_font_match (fontname, ptnstr))
6025 newlist = Fcons (XCAR (tem), newlist);
6026 n_fonts++;
6027 if (max_names >= 0 && n_fonts >= max_names)
6028 break;
6032 return newlist;
6036 /* Return a list of names of available fonts matching PATTERN on frame
6037 F. If SIZE is not 0, it is the size (maximum bound width) of fonts
6038 to be listed. Frame F NULL means we have not yet created any
6039 frame, which means we can't get proper size info, as we don't have
6040 a device context to use for GetTextMetrics.
6041 MAXNAMES sets a limit on how many fonts to match. If MAXNAMES is
6042 negative, then all matching fonts are returned. */
6044 Lisp_Object
6045 w32_list_fonts (f, pattern, size, maxnames)
6046 struct frame *f;
6047 Lisp_Object pattern;
6048 int size;
6049 int maxnames;
6051 Lisp_Object patterns, key = Qnil, tem, tpat;
6052 Lisp_Object list = Qnil, newlist = Qnil, second_best = Qnil;
6053 struct w32_display_info *dpyinfo = &one_w32_display_info;
6054 int n_fonts = 0;
6056 patterns = Fassoc (pattern, Valternate_fontname_alist);
6057 if (NILP (patterns))
6058 patterns = Fcons (pattern, Qnil);
6060 for (; CONSP (patterns); patterns = XCDR (patterns))
6062 enumfont_t ef;
6063 int codepage;
6065 tpat = XCAR (patterns);
6067 if (!STRINGP (tpat))
6068 continue;
6070 /* Avoid expensive EnumFontFamilies functions if we are not
6071 going to be able to output one of these anyway. */
6072 codepage = w32_codepage_for_font (SDATA (tpat));
6073 if (codepage != CP_8BIT && codepage != CP_UNICODE
6074 && codepage != CP_DEFAULT && codepage != CP_UNKNOWN
6075 && !IsValidCodePage (codepage))
6076 continue;
6078 /* See if we cached the result for this particular query.
6079 The cache is an alist of the form:
6080 ((PATTERN (FONTNAME . WIDTH) ...) ...)
6082 if (tem = XCDR (dpyinfo->name_list_element),
6083 !NILP (list = Fassoc (tpat, tem)))
6085 list = Fcdr_safe (list);
6086 /* We have a cached list. Don't have to get the list again. */
6087 goto label_cached;
6090 BLOCK_INPUT;
6091 /* At first, put PATTERN in the cache. */
6092 ef.pattern = tpat;
6093 ef.list = Qnil;
6094 ef.numFonts = 0;
6096 /* Use EnumFontFamiliesEx where it is available, as it knows
6097 about character sets. Fall back to EnumFontFamilies for
6098 older versions of NT that don't support the 'Ex function. */
6099 x_to_w32_font (SDATA (tpat), &ef.logfont);
6101 LOGFONT font_match_pattern;
6102 HMODULE gdi32 = GetModuleHandle ("gdi32.dll");
6103 FARPROC enum_font_families_ex
6104 = GetProcAddress ( gdi32, "EnumFontFamiliesExA");
6106 /* We do our own pattern matching so we can handle wildcards. */
6107 font_match_pattern.lfFaceName[0] = 0;
6108 font_match_pattern.lfPitchAndFamily = 0;
6109 /* We can use the charset, because if it is a wildcard it will
6110 be DEFAULT_CHARSET anyway. */
6111 font_match_pattern.lfCharSet = ef.logfont.lfCharSet;
6113 ef.hdc = GetDC (dpyinfo->root_window);
6115 if (enum_font_families_ex)
6116 enum_font_families_ex (ef.hdc,
6117 &font_match_pattern,
6118 (FONTENUMPROC) enum_fontex_cb1,
6119 (LPARAM) &ef, 0);
6120 else
6121 EnumFontFamilies (ef.hdc, NULL, (FONTENUMPROC) enum_font_cb1,
6122 (LPARAM)&ef);
6124 ReleaseDC (dpyinfo->root_window, ef.hdc);
6127 UNBLOCK_INPUT;
6128 list = ef.list;
6130 /* Make a list of the fonts we got back.
6131 Store that in the font cache for the display. */
6132 XSETCDR (dpyinfo->name_list_element,
6133 Fcons (Fcons (tpat, list),
6134 XCDR (dpyinfo->name_list_element)));
6136 label_cached:
6137 if (NILP (list)) continue; /* Try the remaining alternatives. */
6139 newlist = second_best = Qnil;
6141 /* Make a list of the fonts that have the right width. */
6142 for (; CONSP (list); list = XCDR (list))
6144 int found_size;
6145 tem = XCAR (list);
6147 if (!CONSP (tem))
6148 continue;
6149 if (NILP (XCAR (tem)))
6150 continue;
6151 if (!size)
6153 newlist = Fcons (XCAR (tem), newlist);
6154 n_fonts++;
6155 if (maxnames >= 0 && n_fonts >= maxnames)
6156 break;
6157 else
6158 continue;
6160 if (!INTEGERP (XCDR (tem)))
6162 /* Since we don't yet know the size of the font, we must
6163 load it and try GetTextMetrics. */
6164 W32FontStruct thisinfo;
6165 LOGFONT lf;
6166 HDC hdc;
6167 HANDLE oldobj;
6169 if (!x_to_w32_font (SDATA (XCAR (tem)), &lf))
6170 continue;
6172 BLOCK_INPUT;
6173 thisinfo.bdf = NULL;
6174 thisinfo.hfont = CreateFontIndirect (&lf);
6175 if (thisinfo.hfont == NULL)
6176 continue;
6178 hdc = GetDC (dpyinfo->root_window);
6179 oldobj = SelectObject (hdc, thisinfo.hfont);
6180 if (GetTextMetrics (hdc, &thisinfo.tm))
6181 XSETCDR (tem, make_number (FONT_WIDTH (&thisinfo)));
6182 else
6183 XSETCDR (tem, make_number (0));
6184 SelectObject (hdc, oldobj);
6185 ReleaseDC (dpyinfo->root_window, hdc);
6186 DeleteObject (thisinfo.hfont);
6187 UNBLOCK_INPUT;
6189 found_size = XINT (XCDR (tem));
6190 if (found_size == size)
6192 newlist = Fcons (XCAR (tem), newlist);
6193 n_fonts++;
6194 if (maxnames >= 0 && n_fonts >= maxnames)
6195 break;
6197 /* keep track of the closest matching size in case
6198 no exact match is found. */
6199 else if (found_size > 0)
6201 if (NILP (second_best))
6202 second_best = tem;
6204 else if (found_size < size)
6206 if (XINT (XCDR (second_best)) > size
6207 || XINT (XCDR (second_best)) < found_size)
6208 second_best = tem;
6210 else
6212 if (XINT (XCDR (second_best)) > size
6213 && XINT (XCDR (second_best)) >
6214 found_size)
6215 second_best = tem;
6220 if (!NILP (newlist))
6221 break;
6222 else if (!NILP (second_best))
6224 newlist = Fcons (XCAR (second_best), Qnil);
6225 break;
6229 /* Include any bdf fonts. */
6230 if (n_fonts < maxnames || maxnames < 0)
6232 Lisp_Object combined[2];
6233 combined[0] = w32_list_bdf_fonts (pattern, maxnames - n_fonts);
6234 combined[1] = newlist;
6235 newlist = Fnconc (2, combined);
6238 return newlist;
6242 /* Return a pointer to struct font_info of font FONT_IDX of frame F. */
6243 struct font_info *
6244 w32_get_font_info (f, font_idx)
6245 FRAME_PTR f;
6246 int font_idx;
6248 return (FRAME_W32_FONT_TABLE (f) + font_idx);
6252 struct font_info*
6253 w32_query_font (struct frame *f, char *fontname)
6255 int i;
6256 struct font_info *pfi;
6258 pfi = FRAME_W32_FONT_TABLE (f);
6260 for (i = 0; i < one_w32_display_info.n_fonts ;i++, pfi++)
6262 if (stricmp (pfi->name, fontname) == 0) return pfi;
6265 return NULL;
6268 /* Find a CCL program for a font specified by FONTP, and set the member
6269 `encoder' of the structure. */
6271 void
6272 w32_find_ccl_program (fontp)
6273 struct font_info *fontp;
6275 Lisp_Object list, elt;
6277 for (list = Vfont_ccl_encoder_alist; CONSP (list); list = XCDR (list))
6279 elt = XCAR (list);
6280 if (CONSP (elt)
6281 && STRINGP (XCAR (elt))
6282 && (fast_c_string_match_ignore_case (XCAR (elt), fontp->name)
6283 >= 0))
6284 break;
6286 if (! NILP (list))
6288 struct ccl_program *ccl
6289 = (struct ccl_program *) xmalloc (sizeof (struct ccl_program));
6291 if (setup_ccl_program (ccl, XCDR (elt)) < 0)
6292 xfree (ccl);
6293 else
6294 fontp->font_encoder = ccl;
6298 /* directory-files from dired.c. */
6299 Lisp_Object Fdirectory_files P_ ((Lisp_Object, Lisp_Object, Lisp_Object, Lisp_Object));
6302 /* Find BDF files in a specified directory. (use GCPRO when calling,
6303 as this calls lisp to get a directory listing). */
6304 static Lisp_Object
6305 w32_find_bdf_fonts_in_dir (Lisp_Object directory)
6307 Lisp_Object filelist, list = Qnil;
6308 char fontname[100];
6310 if (!STRINGP (directory))
6311 return Qnil;
6313 filelist = Fdirectory_files (directory, Qt,
6314 build_string (".*\\.[bB][dD][fF]"), Qt);
6316 for ( ; CONSP (filelist); filelist = XCDR (filelist))
6318 Lisp_Object filename = XCAR (filelist);
6319 if (w32_BDF_to_x_font (SDATA (filename), fontname, 100))
6320 store_in_alist (&list, build_string (fontname), filename);
6322 return list;
6325 DEFUN ("w32-find-bdf-fonts", Fw32_find_bdf_fonts, Sw32_find_bdf_fonts,
6326 1, 1, 0,
6327 doc: /* Return a list of BDF fonts in DIRECTORY.
6328 The list is suitable for appending to `w32-bdf-filename-alist'.
6329 Fonts which do not contain an xlfd description will not be included
6330 in the list. DIRECTORY may be a list of directories. */)
6331 (directory)
6332 Lisp_Object directory;
6334 Lisp_Object list = Qnil;
6335 struct gcpro gcpro1, gcpro2;
6337 if (!CONSP (directory))
6338 return w32_find_bdf_fonts_in_dir (directory);
6340 for ( ; CONSP (directory); directory = XCDR (directory))
6342 Lisp_Object pair[2];
6343 pair[0] = list;
6344 pair[1] = Qnil;
6345 GCPRO2 (directory, list);
6346 pair[1] = w32_find_bdf_fonts_in_dir ( XCAR (directory) );
6347 list = Fnconc ( 2, pair );
6348 UNGCPRO;
6350 return list;
6354 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6355 doc: /* Internal function called by `color-defined-p', which see. */)
6356 (color, frame)
6357 Lisp_Object color, frame;
6359 XColor foo;
6360 FRAME_PTR f = check_x_frame (frame);
6362 CHECK_STRING (color);
6364 if (w32_defined_color (f, SDATA (color), &foo, 0))
6365 return Qt;
6366 else
6367 return Qnil;
6370 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6371 doc: /* Internal function called by `color-values', which see. */)
6372 (color, frame)
6373 Lisp_Object color, frame;
6375 XColor foo;
6376 FRAME_PTR f = check_x_frame (frame);
6378 CHECK_STRING (color);
6380 if (w32_defined_color (f, SDATA (color), &foo, 0))
6381 return list3 (make_number ((GetRValue (foo.pixel) << 8)
6382 | GetRValue (foo.pixel)),
6383 make_number ((GetGValue (foo.pixel) << 8)
6384 | GetGValue (foo.pixel)),
6385 make_number ((GetBValue (foo.pixel) << 8)
6386 | GetBValue (foo.pixel)));
6387 else
6388 return Qnil;
6391 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6392 doc: /* Internal function called by `display-color-p', which see. */)
6393 (display)
6394 Lisp_Object display;
6396 struct w32_display_info *dpyinfo = check_x_display_info (display);
6398 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6399 return Qnil;
6401 return Qt;
6404 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6405 Sx_display_grayscale_p, 0, 1, 0,
6406 doc: /* Return t if DISPLAY supports shades of gray.
6407 Note that color displays do support shades of gray.
6408 The optional argument DISPLAY specifies which display to ask about.
6409 DISPLAY should be either a frame or a display name (a string).
6410 If omitted or nil, that stands for the selected frame's display. */)
6411 (display)
6412 Lisp_Object display;
6414 struct w32_display_info *dpyinfo = check_x_display_info (display);
6416 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6417 return Qnil;
6419 return Qt;
6422 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6423 Sx_display_pixel_width, 0, 1, 0,
6424 doc: /* Return the width in pixels of DISPLAY.
6425 The optional argument DISPLAY specifies which display to ask about.
6426 DISPLAY should be either a frame or a display name (a string).
6427 If omitted or nil, that stands for the selected frame's display. */)
6428 (display)
6429 Lisp_Object display;
6431 struct w32_display_info *dpyinfo = check_x_display_info (display);
6433 return make_number (dpyinfo->width);
6436 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6437 Sx_display_pixel_height, 0, 1, 0,
6438 doc: /* Return the height in pixels of DISPLAY.
6439 The optional argument DISPLAY specifies which display to ask about.
6440 DISPLAY should be either a frame or a display name (a string).
6441 If omitted or nil, that stands for the selected frame's display. */)
6442 (display)
6443 Lisp_Object display;
6445 struct w32_display_info *dpyinfo = check_x_display_info (display);
6447 return make_number (dpyinfo->height);
6450 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6451 0, 1, 0,
6452 doc: /* Return the number of bitplanes of DISPLAY.
6453 The optional argument DISPLAY specifies which display to ask about.
6454 DISPLAY should be either a frame or a display name (a string).
6455 If omitted or nil, that stands for the selected frame's display. */)
6456 (display)
6457 Lisp_Object display;
6459 struct w32_display_info *dpyinfo = check_x_display_info (display);
6461 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6464 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6465 0, 1, 0,
6466 doc: /* Return the number of color cells of DISPLAY.
6467 The optional argument DISPLAY specifies which display to ask about.
6468 DISPLAY should be either a frame or a display name (a string).
6469 If omitted or nil, that stands for the selected frame's display. */)
6470 (display)
6471 Lisp_Object display;
6473 struct w32_display_info *dpyinfo = check_x_display_info (display);
6474 HDC hdc;
6475 int cap;
6477 hdc = GetDC (dpyinfo->root_window);
6478 if (dpyinfo->has_palette)
6479 cap = GetDeviceCaps (hdc, SIZEPALETTE);
6480 else
6481 cap = GetDeviceCaps (hdc, NUMCOLORS);
6483 /* We force 24+ bit depths to 24-bit, both to prevent an overflow
6484 and because probably is more meaningful on Windows anyway */
6485 if (cap < 0)
6486 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
6488 ReleaseDC (dpyinfo->root_window, hdc);
6490 return make_number (cap);
6493 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6494 Sx_server_max_request_size,
6495 0, 1, 0,
6496 doc: /* Return the maximum request size of the server of DISPLAY.
6497 The optional argument DISPLAY specifies which display to ask about.
6498 DISPLAY should be either a frame or a display name (a string).
6499 If omitted or nil, that stands for the selected frame's display. */)
6500 (display)
6501 Lisp_Object display;
6503 struct w32_display_info *dpyinfo = check_x_display_info (display);
6505 return make_number (1);
6508 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6509 doc: /* Return the "vendor ID" string of the W32 system (Microsoft).
6510 The optional argument DISPLAY specifies which display to ask about.
6511 DISPLAY should be either a frame or a display name (a string).
6512 If omitted or nil, that stands for the selected frame's display. */)
6513 (display)
6514 Lisp_Object display;
6516 return build_string ("Microsoft Corp.");
6519 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6520 doc: /* Return the version numbers of the server of DISPLAY.
6521 The value is a list of three integers: the major and minor
6522 version numbers of the X Protocol in use, and the distributor-specific
6523 release number. See also the function `x-server-vendor'.
6525 The optional argument DISPLAY specifies which display to ask about.
6526 DISPLAY should be either a frame or a display name (a string).
6527 If omitted or nil, that stands for the selected frame's display. */)
6528 (display)
6529 Lisp_Object display;
6531 return Fcons (make_number (w32_major_version),
6532 Fcons (make_number (w32_minor_version),
6533 Fcons (make_number (w32_build_number), Qnil)));
6536 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6537 doc: /* Return the number of screens on the server of DISPLAY.
6538 The optional argument DISPLAY specifies which display to ask about.
6539 DISPLAY should be either a frame or a display name (a string).
6540 If omitted or nil, that stands for the selected frame's display. */)
6541 (display)
6542 Lisp_Object display;
6544 return make_number (1);
6547 DEFUN ("x-display-mm-height", Fx_display_mm_height,
6548 Sx_display_mm_height, 0, 1, 0,
6549 doc: /* Return the height in millimeters of DISPLAY.
6550 The optional argument DISPLAY specifies which display to ask about.
6551 DISPLAY should be either a frame or a display name (a string).
6552 If omitted or nil, that stands for the selected frame's display. */)
6553 (display)
6554 Lisp_Object display;
6556 struct w32_display_info *dpyinfo = check_x_display_info (display);
6557 HDC hdc;
6558 int cap;
6560 hdc = GetDC (dpyinfo->root_window);
6562 cap = GetDeviceCaps (hdc, VERTSIZE);
6564 ReleaseDC (dpyinfo->root_window, hdc);
6566 return make_number (cap);
6569 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6570 doc: /* Return the width in millimeters of DISPLAY.
6571 The optional argument DISPLAY specifies which display to ask about.
6572 DISPLAY should be either a frame or a display name (a string).
6573 If omitted or nil, that stands for the selected frame's display. */)
6574 (display)
6575 Lisp_Object display;
6577 struct w32_display_info *dpyinfo = check_x_display_info (display);
6579 HDC hdc;
6580 int cap;
6582 hdc = GetDC (dpyinfo->root_window);
6584 cap = GetDeviceCaps (hdc, HORZSIZE);
6586 ReleaseDC (dpyinfo->root_window, hdc);
6588 return make_number (cap);
6591 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6592 Sx_display_backing_store, 0, 1, 0,
6593 doc: /* Return an indication of whether DISPLAY does backing store.
6594 The value may be `always', `when-mapped', or `not-useful'.
6595 The optional argument DISPLAY specifies which display to ask about.
6596 DISPLAY should be either a frame or a display name (a string).
6597 If omitted or nil, that stands for the selected frame's display. */)
6598 (display)
6599 Lisp_Object display;
6601 return intern ("not-useful");
6604 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6605 Sx_display_visual_class, 0, 1, 0,
6606 doc: /* Return the visual class of DISPLAY.
6607 The value is one of the symbols `static-gray', `gray-scale',
6608 `static-color', `pseudo-color', `true-color', or `direct-color'.
6610 The optional argument DISPLAY specifies which display to ask about.
6611 DISPLAY should be either a frame or a display name (a string).
6612 If omitted or nil, that stands for the selected frame's display. */)
6613 (display)
6614 Lisp_Object display;
6616 struct w32_display_info *dpyinfo = check_x_display_info (display);
6617 Lisp_Object result = Qnil;
6619 if (dpyinfo->has_palette)
6620 result = intern ("pseudo-color");
6621 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6622 result = intern ("static-grey");
6623 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6624 result = intern ("static-color");
6625 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6626 result = intern ("true-color");
6628 return result;
6631 DEFUN ("x-display-save-under", Fx_display_save_under,
6632 Sx_display_save_under, 0, 1, 0,
6633 doc: /* Return t if DISPLAY supports the save-under feature.
6634 The optional argument DISPLAY specifies which display to ask about.
6635 DISPLAY should be either a frame or a display name (a string).
6636 If omitted or nil, that stands for the selected frame's display. */)
6637 (display)
6638 Lisp_Object display;
6640 return Qnil;
6644 x_pixel_width (f)
6645 register struct frame *f;
6647 return FRAME_PIXEL_WIDTH (f);
6651 x_pixel_height (f)
6652 register struct frame *f;
6654 return FRAME_PIXEL_HEIGHT (f);
6658 x_char_width (f)
6659 register struct frame *f;
6661 return FRAME_COLUMN_WIDTH (f);
6665 x_char_height (f)
6666 register struct frame *f;
6668 return FRAME_LINE_HEIGHT (f);
6672 x_screen_planes (f)
6673 register struct frame *f;
6675 return FRAME_W32_DISPLAY_INFO (f)->n_planes;
6678 /* Return the display structure for the display named NAME.
6679 Open a new connection if necessary. */
6681 struct w32_display_info *
6682 x_display_info_for_name (name)
6683 Lisp_Object name;
6685 Lisp_Object names;
6686 struct w32_display_info *dpyinfo;
6688 CHECK_STRING (name);
6690 for (dpyinfo = &one_w32_display_info, names = w32_display_name_list;
6691 dpyinfo;
6692 dpyinfo = dpyinfo->next, names = XCDR (names))
6694 Lisp_Object tem;
6695 tem = Fstring_equal (XCAR (XCAR (names)), name);
6696 if (!NILP (tem))
6697 return dpyinfo;
6700 /* Use this general default value to start with. */
6701 Vx_resource_name = Vinvocation_name;
6703 validate_x_resource_name ();
6705 dpyinfo = w32_term_init (name, (unsigned char *)0,
6706 (char *) SDATA (Vx_resource_name));
6708 if (dpyinfo == 0)
6709 error ("Cannot connect to server %s", SDATA (name));
6711 w32_in_use = 1;
6712 XSETFASTINT (Vwindow_system_version, 3);
6714 return dpyinfo;
6717 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6718 1, 3, 0, doc: /* Open a connection to a server.
6719 DISPLAY is the name of the display to connect to.
6720 Optional second arg XRM-STRING is a string of resources in xrdb format.
6721 If the optional third arg MUST-SUCCEED is non-nil,
6722 terminate Emacs if we can't open the connection. */)
6723 (display, xrm_string, must_succeed)
6724 Lisp_Object display, xrm_string, must_succeed;
6726 unsigned char *xrm_option;
6727 struct w32_display_info *dpyinfo;
6729 /* If initialization has already been done, return now to avoid
6730 overwriting critical parts of one_w32_display_info. */
6731 if (w32_in_use)
6732 return Qnil;
6734 CHECK_STRING (display);
6735 if (! NILP (xrm_string))
6736 CHECK_STRING (xrm_string);
6738 #if 0
6739 if (! EQ (Vwindow_system, intern ("w32")))
6740 error ("Not using Microsoft Windows");
6741 #endif
6743 /* Allow color mapping to be defined externally; first look in user's
6744 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6746 Lisp_Object color_file;
6747 struct gcpro gcpro1;
6749 color_file = build_string ("~/rgb.txt");
6751 GCPRO1 (color_file);
6753 if (NILP (Ffile_readable_p (color_file)))
6754 color_file =
6755 Fexpand_file_name (build_string ("rgb.txt"),
6756 Fsymbol_value (intern ("data-directory")));
6758 Vw32_color_map = Fw32_load_color_file (color_file);
6760 UNGCPRO;
6762 if (NILP (Vw32_color_map))
6763 Vw32_color_map = Fw32_default_color_map ();
6765 /* Merge in system logical colors. */
6766 add_system_logical_colors_to_map (&Vw32_color_map);
6768 if (! NILP (xrm_string))
6769 xrm_option = (unsigned char *) SDATA (xrm_string);
6770 else
6771 xrm_option = (unsigned char *) 0;
6773 /* Use this general default value to start with. */
6774 /* First remove .exe suffix from invocation-name - it looks ugly. */
6776 char basename[ MAX_PATH ], *str;
6778 strcpy (basename, SDATA (Vinvocation_name));
6779 str = strrchr (basename, '.');
6780 if (str) *str = 0;
6781 Vinvocation_name = build_string (basename);
6783 Vx_resource_name = Vinvocation_name;
6785 validate_x_resource_name ();
6787 /* This is what opens the connection and sets x_current_display.
6788 This also initializes many symbols, such as those used for input. */
6789 dpyinfo = w32_term_init (display, xrm_option,
6790 (char *) SDATA (Vx_resource_name));
6792 if (dpyinfo == 0)
6794 if (!NILP (must_succeed))
6795 fatal ("Cannot connect to server %s.\n",
6796 SDATA (display));
6797 else
6798 error ("Cannot connect to server %s", SDATA (display));
6801 w32_in_use = 1;
6803 XSETFASTINT (Vwindow_system_version, 3);
6804 return Qnil;
6807 DEFUN ("x-close-connection", Fx_close_connection,
6808 Sx_close_connection, 1, 1, 0,
6809 doc: /* Close the connection to DISPLAY's server.
6810 For DISPLAY, specify either a frame or a display name (a string).
6811 If DISPLAY is nil, that stands for the selected frame's display. */)
6812 (display)
6813 Lisp_Object display;
6815 struct w32_display_info *dpyinfo = check_x_display_info (display);
6816 int i;
6818 if (dpyinfo->reference_count > 0)
6819 error ("Display still has frames on it");
6821 BLOCK_INPUT;
6822 /* Free the fonts in the font table. */
6823 for (i = 0; i < dpyinfo->n_fonts; i++)
6824 if (dpyinfo->font_table[i].name)
6826 if (dpyinfo->font_table[i].name != dpyinfo->font_table[i].full_name)
6827 xfree (dpyinfo->font_table[i].full_name);
6828 xfree (dpyinfo->font_table[i].name);
6829 w32_unload_font (dpyinfo, dpyinfo->font_table[i].font);
6831 x_destroy_all_bitmaps (dpyinfo);
6833 x_delete_display (dpyinfo);
6834 UNBLOCK_INPUT;
6836 return Qnil;
6839 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6840 doc: /* Return the list of display names that Emacs has connections to. */)
6843 Lisp_Object tail, result;
6845 result = Qnil;
6846 for (tail = w32_display_name_list; CONSP (tail); tail = XCDR (tail))
6847 result = Fcons (XCAR (XCAR (tail)), result);
6849 return result;
6852 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6853 doc: /* This is a noop on W32 systems. */)
6854 (on, display)
6855 Lisp_Object display, on;
6857 return Qnil;
6862 /***********************************************************************
6863 Window properties
6864 ***********************************************************************/
6866 DEFUN ("x-change-window-property", Fx_change_window_property,
6867 Sx_change_window_property, 2, 6, 0,
6868 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6869 VALUE may be a string or a list of conses, numbers and/or strings.
6870 If an element in the list is a string, it is converted to
6871 an Atom and the value of the Atom is used. If an element is a cons,
6872 it is converted to a 32 bit number where the car is the 16 top bits and the
6873 cdr is the lower 16 bits.
6874 FRAME nil or omitted means use the selected frame.
6875 If TYPE is given and non-nil, it is the name of the type of VALUE.
6876 If TYPE is not given or nil, the type is STRING.
6877 FORMAT gives the size in bits of each element if VALUE is a list.
6878 It must be one of 8, 16 or 32.
6879 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6880 If OUTER_P is non-nil, the property is changed for the outer X window of
6881 FRAME. Default is to change on the edit X window.
6883 Value is VALUE. */)
6884 (prop, value, frame, type, format, outer_p)
6885 Lisp_Object prop, value, frame, type, format, outer_p;
6887 #if 0 /* TODO : port window properties to W32 */
6888 struct frame *f = check_x_frame (frame);
6889 Atom prop_atom;
6891 CHECK_STRING (prop);
6892 CHECK_STRING (value);
6894 BLOCK_INPUT;
6895 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6896 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6897 prop_atom, XA_STRING, 8, PropModeReplace,
6898 SDATA (value), SCHARS (value));
6900 /* Make sure the property is set when we return. */
6901 XFlush (FRAME_W32_DISPLAY (f));
6902 UNBLOCK_INPUT;
6904 #endif /* TODO */
6906 return value;
6910 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6911 Sx_delete_window_property, 1, 2, 0,
6912 doc: /* Remove window property PROP from X window of FRAME.
6913 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6914 (prop, frame)
6915 Lisp_Object prop, frame;
6917 #if 0 /* TODO : port window properties to W32 */
6919 struct frame *f = check_x_frame (frame);
6920 Atom prop_atom;
6922 CHECK_STRING (prop);
6923 BLOCK_INPUT;
6924 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6925 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6927 /* Make sure the property is removed when we return. */
6928 XFlush (FRAME_W32_DISPLAY (f));
6929 UNBLOCK_INPUT;
6930 #endif /* TODO */
6932 return prop;
6936 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6937 1, 2, 0,
6938 doc: /* Value is the value of window property PROP on FRAME.
6939 If FRAME is nil or omitted, use the selected frame. Value is nil
6940 if FRAME hasn't a property with name PROP or if PROP has no string
6941 value. */)
6942 (prop, frame)
6943 Lisp_Object prop, frame;
6945 #if 0 /* TODO : port window properties to W32 */
6947 struct frame *f = check_x_frame (frame);
6948 Atom prop_atom;
6949 int rc;
6950 Lisp_Object prop_value = Qnil;
6951 char *tmp_data = NULL;
6952 Atom actual_type;
6953 int actual_format;
6954 unsigned long actual_size, bytes_remaining;
6956 CHECK_STRING (prop);
6957 BLOCK_INPUT;
6958 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6959 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6960 prop_atom, 0, 0, False, XA_STRING,
6961 &actual_type, &actual_format, &actual_size,
6962 &bytes_remaining, (unsigned char **) &tmp_data);
6963 if (rc == Success)
6965 int size = bytes_remaining;
6967 XFree (tmp_data);
6968 tmp_data = NULL;
6970 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6971 prop_atom, 0, bytes_remaining,
6972 False, XA_STRING,
6973 &actual_type, &actual_format,
6974 &actual_size, &bytes_remaining,
6975 (unsigned char **) &tmp_data);
6976 if (rc == Success)
6977 prop_value = make_string (tmp_data, size);
6979 XFree (tmp_data);
6982 UNBLOCK_INPUT;
6984 return prop_value;
6986 #endif /* TODO */
6987 return Qnil;
6992 /***********************************************************************
6993 Busy cursor
6994 ***********************************************************************/
6996 /* If non-null, an asynchronous timer that, when it expires, displays
6997 an hourglass cursor on all frames. */
6999 static struct atimer *hourglass_atimer;
7001 /* Non-zero means an hourglass cursor is currently shown. */
7003 static int hourglass_shown_p;
7005 /* Number of seconds to wait before displaying an hourglass cursor. */
7007 static Lisp_Object Vhourglass_delay;
7009 /* Default number of seconds to wait before displaying an hourglass
7010 cursor. */
7012 #define DEFAULT_HOURGLASS_DELAY 1
7014 /* Function prototypes. */
7016 static void show_hourglass P_ ((struct atimer *));
7017 static void hide_hourglass P_ ((void));
7020 /* Cancel a currently active hourglass timer, and start a new one. */
7022 void
7023 start_hourglass ()
7025 #if 0 /* TODO: cursor shape changes. */
7026 EMACS_TIME delay;
7027 int secs, usecs = 0;
7029 cancel_hourglass ();
7031 if (INTEGERP (Vhourglass_delay)
7032 && XINT (Vhourglass_delay) > 0)
7033 secs = XFASTINT (Vhourglass_delay);
7034 else if (FLOATP (Vhourglass_delay)
7035 && XFLOAT_DATA (Vhourglass_delay) > 0)
7037 Lisp_Object tem;
7038 tem = Ftruncate (Vhourglass_delay, Qnil);
7039 secs = XFASTINT (tem);
7040 usecs = (XFLOAT_DATA (Vhourglass_delay) - secs) * 1000000;
7042 else
7043 secs = DEFAULT_HOURGLASS_DELAY;
7045 EMACS_SET_SECS_USECS (delay, secs, usecs);
7046 hourglass_atimer = start_atimer (ATIMER_RELATIVE, delay,
7047 show_hourglass, NULL);
7048 #endif
7052 /* Cancel the hourglass cursor timer if active, hide an hourglass
7053 cursor if shown. */
7055 void
7056 cancel_hourglass ()
7058 if (hourglass_atimer)
7060 cancel_atimer (hourglass_atimer);
7061 hourglass_atimer = NULL;
7064 if (hourglass_shown_p)
7065 hide_hourglass ();
7069 /* Timer function of hourglass_atimer. TIMER is equal to
7070 hourglass_atimer.
7072 Display an hourglass cursor on all frames by mapping the frames'
7073 hourglass_window. Set the hourglass_p flag in the frames'
7074 output_data.x structure to indicate that an hourglass cursor is
7075 shown on the frames. */
7077 static void
7078 show_hourglass (timer)
7079 struct atimer *timer;
7081 #if 0 /* TODO: cursor shape changes. */
7082 /* The timer implementation will cancel this timer automatically
7083 after this function has run. Set hourglass_atimer to null
7084 so that we know the timer doesn't have to be canceled. */
7085 hourglass_atimer = NULL;
7087 if (!hourglass_shown_p)
7089 Lisp_Object rest, frame;
7091 BLOCK_INPUT;
7093 FOR_EACH_FRAME (rest, frame)
7094 if (FRAME_W32_P (XFRAME (frame)))
7096 struct frame *f = XFRAME (frame);
7098 f->output_data.w32->hourglass_p = 1;
7100 if (!f->output_data.w32->hourglass_window)
7102 unsigned long mask = CWCursor;
7103 XSetWindowAttributes attrs;
7105 attrs.cursor = f->output_data.w32->hourglass_cursor;
7107 f->output_data.w32->hourglass_window
7108 = XCreateWindow (FRAME_X_DISPLAY (f),
7109 FRAME_OUTER_WINDOW (f),
7110 0, 0, 32000, 32000, 0, 0,
7111 InputOnly,
7112 CopyFromParent,
7113 mask, &attrs);
7116 XMapRaised (FRAME_X_DISPLAY (f),
7117 f->output_data.w32->hourglass_window);
7118 XFlush (FRAME_X_DISPLAY (f));
7121 hourglass_shown_p = 1;
7122 UNBLOCK_INPUT;
7124 #endif
7128 /* Hide the hourglass cursor on all frames, if it is currently shown. */
7130 static void
7131 hide_hourglass ()
7133 #if 0 /* TODO: cursor shape changes. */
7134 if (hourglass_shown_p)
7136 Lisp_Object rest, frame;
7138 BLOCK_INPUT;
7139 FOR_EACH_FRAME (rest, frame)
7141 struct frame *f = XFRAME (frame);
7143 if (FRAME_W32_P (f)
7144 /* Watch out for newly created frames. */
7145 && f->output_data.x->hourglass_window)
7147 XUnmapWindow (FRAME_X_DISPLAY (f),
7148 f->output_data.x->hourglass_window);
7149 /* Sync here because XTread_socket looks at the
7150 hourglass_p flag that is reset to zero below. */
7151 XSync (FRAME_X_DISPLAY (f), False);
7152 f->output_data.x->hourglass_p = 0;
7156 hourglass_shown_p = 0;
7157 UNBLOCK_INPUT;
7159 #endif
7164 /***********************************************************************
7165 Tool tips
7166 ***********************************************************************/
7168 static Lisp_Object x_create_tip_frame P_ ((struct w32_display_info *,
7169 Lisp_Object, Lisp_Object));
7170 static void compute_tip_xy P_ ((struct frame *, Lisp_Object, Lisp_Object,
7171 Lisp_Object, int, int, int *, int *));
7173 /* The frame of a currently visible tooltip. */
7175 Lisp_Object tip_frame;
7177 /* If non-nil, a timer started that hides the last tooltip when it
7178 fires. */
7180 Lisp_Object tip_timer;
7181 Window tip_window;
7183 /* If non-nil, a vector of 3 elements containing the last args
7184 with which x-show-tip was called. See there. */
7186 Lisp_Object last_show_tip_args;
7188 /* Maximum size for tooltips; a cons (COLUMNS . ROWS). */
7190 Lisp_Object Vx_max_tooltip_size;
7193 static Lisp_Object
7194 unwind_create_tip_frame (frame)
7195 Lisp_Object frame;
7197 Lisp_Object deleted;
7199 deleted = unwind_create_frame (frame);
7200 if (EQ (deleted, Qt))
7202 tip_window = NULL;
7203 tip_frame = Qnil;
7206 return deleted;
7210 /* Create a frame for a tooltip on the display described by DPYINFO.
7211 PARMS is a list of frame parameters. TEXT is the string to
7212 display in the tip frame. Value is the frame.
7214 Note that functions called here, esp. x_default_parameter can
7215 signal errors, for instance when a specified color name is
7216 undefined. We have to make sure that we're in a consistent state
7217 when this happens. */
7219 static Lisp_Object
7220 x_create_tip_frame (dpyinfo, parms, text)
7221 struct w32_display_info *dpyinfo;
7222 Lisp_Object parms, text;
7224 struct frame *f;
7225 Lisp_Object frame, tem;
7226 Lisp_Object name;
7227 long window_prompting = 0;
7228 int width, height;
7229 int count = SPECPDL_INDEX ();
7230 struct gcpro gcpro1, gcpro2, gcpro3;
7231 struct kboard *kb;
7232 int face_change_count_before = face_change_count;
7233 Lisp_Object buffer;
7234 struct buffer *old_buffer;
7236 check_w32 ();
7238 /* Use this general default value to start with until we know if
7239 this frame has a specified name. */
7240 Vx_resource_name = Vinvocation_name;
7242 #ifdef MULTI_KBOARD
7243 kb = dpyinfo->terminal->kboard;
7244 #else
7245 kb = &the_only_kboard;
7246 #endif
7248 /* Get the name of the frame to use for resource lookup. */
7249 name = w32_get_arg (parms, Qname, "name", "Name", RES_TYPE_STRING);
7250 if (!STRINGP (name)
7251 && !EQ (name, Qunbound)
7252 && !NILP (name))
7253 error ("Invalid frame name--not a string or nil");
7254 Vx_resource_name = name;
7256 frame = Qnil;
7257 GCPRO3 (parms, name, frame);
7258 /* Make a frame without minibuffer nor mode-line. */
7259 f = make_frame (0);
7260 f->wants_modeline = 0;
7261 XSETFRAME (frame, f);
7263 buffer = Fget_buffer_create (build_string (" *tip*"));
7264 Fset_window_buffer (FRAME_ROOT_WINDOW (f), buffer, Qnil);
7265 old_buffer = current_buffer;
7266 set_buffer_internal_1 (XBUFFER (buffer));
7267 current_buffer->truncate_lines = Qnil;
7268 specbind (Qinhibit_read_only, Qt);
7269 specbind (Qinhibit_modification_hooks, Qt);
7270 Ferase_buffer ();
7271 Finsert (1, &text);
7272 set_buffer_internal_1 (old_buffer);
7274 FRAME_CAN_HAVE_SCROLL_BARS (f) = 0;
7275 record_unwind_protect (unwind_create_tip_frame, frame);
7277 /* By setting the output method, we're essentially saying that
7278 the frame is live, as per FRAME_LIVE_P. If we get a signal
7279 from this point on, x_destroy_window might screw up reference
7280 counts etc. */
7281 f->terminal = dpyinfo->terminal;
7282 f->terminal->reference_count++;
7283 f->output_method = output_w32;
7284 f->output_data.w32 =
7285 (struct w32_output *) xmalloc (sizeof (struct w32_output));
7286 bzero (f->output_data.w32, sizeof (struct w32_output));
7288 FRAME_FONTSET (f) = -1;
7289 f->icon_name = Qnil;
7291 #if 0 /* GLYPH_DEBUG TODO: image support. */
7292 image_cache_refcount = FRAME_X_IMAGE_CACHE (f)->refcount;
7293 dpyinfo_refcount = dpyinfo->reference_count;
7294 #endif /* GLYPH_DEBUG */
7295 #ifdef MULTI_KBOARD
7296 FRAME_KBOARD (f) = kb;
7297 #endif
7298 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
7299 f->output_data.w32->explicit_parent = 0;
7301 /* Set the name; the functions to which we pass f expect the name to
7302 be set. */
7303 if (EQ (name, Qunbound) || NILP (name))
7305 f->name = build_string (dpyinfo->w32_id_name);
7306 f->explicit_name = 0;
7308 else
7310 f->name = name;
7311 f->explicit_name = 1;
7312 /* use the frame's title when getting resources for this frame. */
7313 specbind (Qx_resource_name, name);
7316 /* Extract the window parameters from the supplied values
7317 that are needed to determine window geometry. */
7319 Lisp_Object font;
7321 font = w32_get_arg (parms, Qfont, "font", "Font", RES_TYPE_STRING);
7323 BLOCK_INPUT;
7324 /* First, try whatever font the caller has specified. */
7325 if (STRINGP (font))
7327 tem = Fquery_fontset (font, Qnil);
7328 if (STRINGP (tem))
7329 font = x_new_fontset (f, SDATA (tem));
7330 else
7331 font = x_new_font (f, SDATA (font));
7334 /* Try out a font which we hope has bold and italic variations. */
7335 if (!STRINGP (font))
7336 font = x_new_font (f, "-*-Courier New-normal-r-*-*-*-100-*-*-c-*-iso8859-1");
7337 if (! STRINGP (font))
7338 font = x_new_font (f, "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1");
7339 /* If those didn't work, look for something which will at least work. */
7340 if (! STRINGP (font))
7341 font = x_new_font (f, "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1");
7342 UNBLOCK_INPUT;
7343 if (! STRINGP (font))
7344 font = build_string ("Fixedsys");
7346 x_default_parameter (f, parms, Qfont, font,
7347 "font", "Font", RES_TYPE_STRING);
7350 x_default_parameter (f, parms, Qborder_width, make_number (2),
7351 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
7352 /* This defaults to 2 in order to match xterm. We recognize either
7353 internalBorderWidth or internalBorder (which is what xterm calls
7354 it). */
7355 if (NILP (Fassq (Qinternal_border_width, parms)))
7357 Lisp_Object value;
7359 value = w32_get_arg (parms, Qinternal_border_width,
7360 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
7361 if (! EQ (value, Qunbound))
7362 parms = Fcons (Fcons (Qinternal_border_width, value),
7363 parms);
7365 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
7366 "internalBorderWidth", "internalBorderWidth",
7367 RES_TYPE_NUMBER);
7369 /* Also do the stuff which must be set before the window exists. */
7370 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
7371 "foreground", "Foreground", RES_TYPE_STRING);
7372 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
7373 "background", "Background", RES_TYPE_STRING);
7374 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
7375 "pointerColor", "Foreground", RES_TYPE_STRING);
7376 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
7377 "cursorColor", "Foreground", RES_TYPE_STRING);
7378 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
7379 "borderColor", "BorderColor", RES_TYPE_STRING);
7381 /* Init faces before x_default_parameter is called for scroll-bar
7382 parameters because that function calls x_set_scroll_bar_width,
7383 which calls change_frame_size, which calls Fset_window_buffer,
7384 which runs hooks, which call Fvertical_motion. At the end, we
7385 end up in init_iterator with a null face cache, which should not
7386 happen. */
7387 init_frame_faces (f);
7389 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
7390 f->output_data.w32->parent_desc = FRAME_W32_DISPLAY_INFO (f)->root_window;
7392 window_prompting = x_figure_window_size (f, parms, 0);
7394 /* No fringes on tip frame. */
7395 f->fringe_cols = 0;
7396 f->left_fringe_width = 0;
7397 f->right_fringe_width = 0;
7399 BLOCK_INPUT;
7400 my_create_tip_window (f);
7401 UNBLOCK_INPUT;
7403 x_make_gc (f);
7405 x_default_parameter (f, parms, Qauto_raise, Qnil,
7406 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7407 x_default_parameter (f, parms, Qauto_lower, Qnil,
7408 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7409 x_default_parameter (f, parms, Qcursor_type, Qbox,
7410 "cursorType", "CursorType", RES_TYPE_SYMBOL);
7412 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
7413 Change will not be effected unless different from the current
7414 FRAME_LINES (f). */
7415 width = FRAME_COLS (f);
7416 height = FRAME_LINES (f);
7417 FRAME_LINES (f) = 0;
7418 SET_FRAME_COLS (f, 0);
7419 change_frame_size (f, height, width, 1, 0, 0);
7421 /* Add `tooltip' frame parameter's default value. */
7422 if (NILP (Fframe_parameter (frame, intern ("tooltip"))))
7423 Fmodify_frame_parameters (frame, Fcons (Fcons (intern ("tooltip"), Qt),
7424 Qnil));
7426 /* Set up faces after all frame parameters are known. This call
7427 also merges in face attributes specified for new frames.
7429 Frame parameters may be changed if .Xdefaults contains
7430 specifications for the default font. For example, if there is an
7431 `Emacs.default.attributeBackground: pink', the `background-color'
7432 attribute of the frame get's set, which let's the internal border
7433 of the tooltip frame appear in pink. Prevent this. */
7435 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
7437 /* Set tip_frame here, so that */
7438 tip_frame = frame;
7439 call1 (Qface_set_after_frame_default, frame);
7441 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
7442 Fmodify_frame_parameters (frame, Fcons (Fcons (Qbackground_color, bg),
7443 Qnil));
7446 f->no_split = 1;
7448 UNGCPRO;
7450 /* It is now ok to make the frame official even if we get an error
7451 below. And the frame needs to be on Vframe_list or making it
7452 visible won't work. */
7453 Vframe_list = Fcons (frame, Vframe_list);
7455 /* Now that the frame is official, it counts as a reference to
7456 its display. */
7457 FRAME_W32_DISPLAY_INFO (f)->reference_count++;
7459 /* Setting attributes of faces of the tooltip frame from resources
7460 and similar will increment face_change_count, which leads to the
7461 clearing of all current matrices. Since this isn't necessary
7462 here, avoid it by resetting face_change_count to the value it
7463 had before we created the tip frame. */
7464 face_change_count = face_change_count_before;
7466 /* Discard the unwind_protect. */
7467 return unbind_to (count, frame);
7471 /* Compute where to display tip frame F. PARMS is the list of frame
7472 parameters for F. DX and DY are specified offsets from the current
7473 location of the mouse. WIDTH and HEIGHT are the width and height
7474 of the tooltip. Return coordinates relative to the root window of
7475 the display in *ROOT_X, and *ROOT_Y. */
7477 static void
7478 compute_tip_xy (f, parms, dx, dy, width, height, root_x, root_y)
7479 struct frame *f;
7480 Lisp_Object parms, dx, dy;
7481 int width, height;
7482 int *root_x, *root_y;
7484 Lisp_Object left, top;
7486 /* User-specified position? */
7487 left = Fcdr (Fassq (Qleft, parms));
7488 top = Fcdr (Fassq (Qtop, parms));
7490 /* Move the tooltip window where the mouse pointer is. Resize and
7491 show it. */
7492 if (!INTEGERP (left) || !INTEGERP (top))
7494 POINT pt;
7496 BLOCK_INPUT;
7497 GetCursorPos (&pt);
7498 *root_x = pt.x;
7499 *root_y = pt.y;
7500 UNBLOCK_INPUT;
7503 if (INTEGERP (top))
7504 *root_y = XINT (top);
7505 else if (*root_y + XINT (dy) <= 0)
7506 *root_y = 0; /* Can happen for negative dy */
7507 else if (*root_y + XINT (dy) + height <= FRAME_W32_DISPLAY_INFO (f)->height)
7508 /* It fits below the pointer */
7509 *root_y += XINT (dy);
7510 else if (height + XINT (dy) <= *root_y)
7511 /* It fits above the pointer. */
7512 *root_y -= height + XINT (dy);
7513 else
7514 /* Put it on the top. */
7515 *root_y = 0;
7517 if (INTEGERP (left))
7518 *root_x = XINT (left);
7519 else if (*root_x + XINT (dx) <= 0)
7520 *root_x = 0; /* Can happen for negative dx */
7521 else if (*root_x + XINT (dx) + width <= FRAME_W32_DISPLAY_INFO (f)->width)
7522 /* It fits to the right of the pointer. */
7523 *root_x += XINT (dx);
7524 else if (width + XINT (dx) <= *root_x)
7525 /* It fits to the left of the pointer. */
7526 *root_x -= width + XINT (dx);
7527 else
7528 /* Put it left justified on the screen -- it ought to fit that way. */
7529 *root_x = 0;
7533 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
7534 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
7535 A tooltip window is a small window displaying a string.
7537 This is an internal function; Lisp code should call `tooltip-show'.
7539 FRAME nil or omitted means use the selected frame.
7541 PARMS is an optional list of frame parameters which can be
7542 used to change the tooltip's appearance.
7544 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
7545 means use the default timeout of 5 seconds.
7547 If the list of frame parameters PARMS contains a `left' parameter,
7548 the tooltip is displayed at that x-position. Otherwise it is
7549 displayed at the mouse position, with offset DX added (default is 5 if
7550 DX isn't specified). Likewise for the y-position; if a `top' frame
7551 parameter is specified, it determines the y-position of the tooltip
7552 window, otherwise it is displayed at the mouse position, with offset
7553 DY added (default is -10).
7555 A tooltip's maximum size is specified by `x-max-tooltip-size'.
7556 Text larger than the specified size is clipped. */)
7557 (string, frame, parms, timeout, dx, dy)
7558 Lisp_Object string, frame, parms, timeout, dx, dy;
7560 struct frame *f;
7561 struct window *w;
7562 int root_x, root_y;
7563 struct buffer *old_buffer;
7564 struct text_pos pos;
7565 int i, width, height;
7566 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
7567 int old_windows_or_buffers_changed = windows_or_buffers_changed;
7568 int count = SPECPDL_INDEX ();
7570 specbind (Qinhibit_redisplay, Qt);
7572 GCPRO4 (string, parms, frame, timeout);
7574 CHECK_STRING (string);
7575 f = check_x_frame (frame);
7576 if (NILP (timeout))
7577 timeout = make_number (5);
7578 else
7579 CHECK_NATNUM (timeout);
7581 if (NILP (dx))
7582 dx = make_number (5);
7583 else
7584 CHECK_NUMBER (dx);
7586 if (NILP (dy))
7587 dy = make_number (-10);
7588 else
7589 CHECK_NUMBER (dy);
7591 if (NILP (last_show_tip_args))
7592 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
7594 if (!NILP (tip_frame))
7596 Lisp_Object last_string = AREF (last_show_tip_args, 0);
7597 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
7598 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
7600 if (EQ (frame, last_frame)
7601 && !NILP (Fequal (last_string, string))
7602 && !NILP (Fequal (last_parms, parms)))
7604 struct frame *f = XFRAME (tip_frame);
7606 /* Only DX and DY have changed. */
7607 if (!NILP (tip_timer))
7609 Lisp_Object timer = tip_timer;
7610 tip_timer = Qnil;
7611 call1 (Qcancel_timer, timer);
7614 BLOCK_INPUT;
7615 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
7616 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
7618 /* Put tooltip in topmost group and in position. */
7619 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
7620 root_x, root_y, 0, 0,
7621 SWP_NOSIZE | SWP_NOACTIVATE);
7623 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7624 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
7625 0, 0, 0, 0,
7626 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
7628 UNBLOCK_INPUT;
7629 goto start_timer;
7633 /* Hide a previous tip, if any. */
7634 Fx_hide_tip ();
7636 ASET (last_show_tip_args, 0, string);
7637 ASET (last_show_tip_args, 1, frame);
7638 ASET (last_show_tip_args, 2, parms);
7640 /* Add default values to frame parameters. */
7641 if (NILP (Fassq (Qname, parms)))
7642 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7643 if (NILP (Fassq (Qinternal_border_width, parms)))
7644 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7645 if (NILP (Fassq (Qborder_width, parms)))
7646 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7647 if (NILP (Fassq (Qborder_color, parms)))
7648 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7649 if (NILP (Fassq (Qbackground_color, parms)))
7650 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7651 parms);
7653 /* Block input until the tip has been fully drawn, to avoid crashes
7654 when drawing tips in menus. */
7655 BLOCK_INPUT;
7657 /* Create a frame for the tooltip, and record it in the global
7658 variable tip_frame. */
7659 frame = x_create_tip_frame (FRAME_W32_DISPLAY_INFO (f), parms, string);
7660 f = XFRAME (frame);
7662 /* Set up the frame's root window. */
7663 w = XWINDOW (FRAME_ROOT_WINDOW (f));
7664 w->left_col = w->top_line = make_number (0);
7666 if (CONSP (Vx_max_tooltip_size)
7667 && INTEGERP (XCAR (Vx_max_tooltip_size))
7668 && XINT (XCAR (Vx_max_tooltip_size)) > 0
7669 && INTEGERP (XCDR (Vx_max_tooltip_size))
7670 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
7672 w->total_cols = XCAR (Vx_max_tooltip_size);
7673 w->total_lines = XCDR (Vx_max_tooltip_size);
7675 else
7677 w->total_cols = make_number (80);
7678 w->total_lines = make_number (40);
7681 FRAME_TOTAL_COLS (f) = XINT (w->total_cols);
7682 adjust_glyphs (f);
7683 w->pseudo_window_p = 1;
7685 /* Display the tooltip text in a temporary buffer. */
7686 old_buffer = current_buffer;
7687 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->buffer));
7688 current_buffer->truncate_lines = Qnil;
7689 clear_glyph_matrix (w->desired_matrix);
7690 clear_glyph_matrix (w->current_matrix);
7691 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7692 try_window (FRAME_ROOT_WINDOW (f), pos, 0);
7694 /* Compute width and height of the tooltip. */
7695 width = height = 0;
7696 for (i = 0; i < w->desired_matrix->nrows; ++i)
7698 struct glyph_row *row = &w->desired_matrix->rows[i];
7699 struct glyph *last;
7700 int row_width;
7702 /* Stop at the first empty row at the end. */
7703 if (!row->enabled_p || !row->displays_text_p)
7704 break;
7706 /* Let the row go over the full width of the frame. */
7707 row->full_width_p = 1;
7709 #ifdef TODO /* Investigate why some fonts need more width than is
7710 calculated for some tooltips. */
7711 /* There's a glyph at the end of rows that is use to place
7712 the cursor there. Don't include the width of this glyph. */
7713 if (row->used[TEXT_AREA])
7715 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
7716 row_width = row->pixel_width - last->pixel_width;
7718 else
7719 #endif
7720 row_width = row->pixel_width;
7722 /* TODO: find why tips do not draw along baseline as instructed. */
7723 height += row->height;
7724 width = max (width, row_width);
7727 /* Add the frame's internal border to the width and height the X
7728 window should have. */
7729 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
7730 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
7732 /* Move the tooltip window where the mouse pointer is. Resize and
7733 show it. */
7734 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
7737 /* Adjust Window size to take border into account. */
7738 RECT rect;
7739 rect.left = rect.top = 0;
7740 rect.right = width;
7741 rect.bottom = height;
7742 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
7743 FRAME_EXTERNAL_MENU_BAR (f));
7745 /* Position and size tooltip, and put it in the topmost group.
7746 The add-on of 3 to the 5th argument is a kludge: without it,
7747 some fonts cause the last character of the tip to be truncated,
7748 for some obscure reason. */
7749 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
7750 root_x, root_y, rect.right - rect.left + 3,
7751 rect.bottom - rect.top, SWP_NOACTIVATE);
7753 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7754 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
7755 0, 0, 0, 0,
7756 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
7758 /* Let redisplay know that we have made the frame visible already. */
7759 f->async_visible = 1;
7761 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
7764 /* Draw into the window. */
7765 w->must_be_updated_p = 1;
7766 update_single_window (w, 1);
7768 UNBLOCK_INPUT;
7770 /* Restore original current buffer. */
7771 set_buffer_internal_1 (old_buffer);
7772 windows_or_buffers_changed = old_windows_or_buffers_changed;
7774 start_timer:
7775 /* Let the tip disappear after timeout seconds. */
7776 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7777 intern ("x-hide-tip"));
7779 UNGCPRO;
7780 return unbind_to (count, Qnil);
7784 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7785 doc: /* Hide the current tooltip window, if there is any.
7786 Value is t if tooltip was open, nil otherwise. */)
7789 int count;
7790 Lisp_Object deleted, frame, timer;
7791 struct gcpro gcpro1, gcpro2;
7793 /* Return quickly if nothing to do. */
7794 if (NILP (tip_timer) && NILP (tip_frame))
7795 return Qnil;
7797 frame = tip_frame;
7798 timer = tip_timer;
7799 GCPRO2 (frame, timer);
7800 tip_frame = tip_timer = deleted = Qnil;
7802 count = SPECPDL_INDEX ();
7803 specbind (Qinhibit_redisplay, Qt);
7804 specbind (Qinhibit_quit, Qt);
7806 if (!NILP (timer))
7807 call1 (Qcancel_timer, timer);
7809 if (FRAMEP (frame))
7811 Fdelete_frame (frame, Qnil);
7812 deleted = Qt;
7815 UNGCPRO;
7816 return unbind_to (count, deleted);
7821 /***********************************************************************
7822 File selection dialog
7823 ***********************************************************************/
7824 extern Lisp_Object Qfile_name_history;
7826 /* Callback for altering the behaviour of the Open File dialog.
7827 Makes the Filename text field contain "Current Directory" and be
7828 read-only when "Directories" is selected in the filter. This
7829 allows us to work around the fact that the standard Open File
7830 dialog does not support directories. */
7831 UINT CALLBACK
7832 file_dialog_callback (hwnd, msg, wParam, lParam)
7833 HWND hwnd;
7834 UINT msg;
7835 WPARAM wParam;
7836 LPARAM lParam;
7838 if (msg == WM_NOTIFY)
7840 OFNOTIFY * notify = (OFNOTIFY *)lParam;
7841 /* Detect when the Filter dropdown is changed. */
7842 if (notify->hdr.code == CDN_TYPECHANGE
7843 || notify->hdr.code == CDN_INITDONE)
7845 HWND dialog = GetParent (hwnd);
7846 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7848 /* Directories is in index 2. */
7849 if (notify->lpOFN->nFilterIndex == 2)
7851 CommDlg_OpenSave_SetControlText (dialog, FILE_NAME_TEXT_FIELD,
7852 "Current Directory");
7853 EnableWindow (edit_control, FALSE);
7855 else
7857 /* Don't override default filename on init done. */
7858 if (notify->hdr.code == CDN_TYPECHANGE)
7859 CommDlg_OpenSave_SetControlText (dialog,
7860 FILE_NAME_TEXT_FIELD, "");
7861 EnableWindow (edit_control, TRUE);
7865 return 0;
7868 /* Since we compile with _WIN32_WINNT set to 0x0400 (for NT4 compatibility)
7869 we end up with the old file dialogs. Define a big enough struct for the
7870 new dialog to trick GetOpenFileName into giving us the new dialogs on
7871 Windows 2000 and XP. */
7872 typedef struct
7874 OPENFILENAME real_details;
7875 void * pReserved;
7876 DWORD dwReserved;
7877 DWORD FlagsEx;
7878 } NEWOPENFILENAME;
7881 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7882 doc: /* Read file name, prompting with PROMPT in directory DIR.
7883 Use a file selection dialog.
7884 Select DEFAULT-FILENAME in the dialog's file selection box, if
7885 specified. Ensure that file exists if MUSTMATCH is non-nil.
7886 If ONLY-DIR-P is non-nil, the user can only select directories. */)
7887 (prompt, dir, default_filename, mustmatch, only_dir_p)
7888 Lisp_Object prompt, dir, default_filename, mustmatch, only_dir_p;
7890 struct frame *f = SELECTED_FRAME ();
7891 Lisp_Object file = Qnil;
7892 int count = SPECPDL_INDEX ();
7893 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
7894 char filename[MAX_PATH + 1];
7895 char init_dir[MAX_PATH + 1];
7896 int default_filter_index = 1; /* 1: All Files, 2: Directories only */
7898 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, file);
7899 CHECK_STRING (prompt);
7900 CHECK_STRING (dir);
7902 /* Create the dialog with PROMPT as title, using DIR as initial
7903 directory and using "*" as pattern. */
7904 dir = Fexpand_file_name (dir, Qnil);
7905 strncpy (init_dir, SDATA (ENCODE_FILE (dir)), MAX_PATH);
7906 init_dir[MAX_PATH] = '\0';
7907 unixtodos_filename (init_dir);
7909 if (STRINGP (default_filename))
7911 char *file_name_only;
7912 char *full_path_name = SDATA (ENCODE_FILE (default_filename));
7914 unixtodos_filename (full_path_name);
7916 file_name_only = strrchr (full_path_name, '\\');
7917 if (!file_name_only)
7918 file_name_only = full_path_name;
7919 else
7920 file_name_only++;
7922 strncpy (filename, file_name_only, MAX_PATH);
7923 filename[MAX_PATH] = '\0';
7925 else
7926 filename[0] = '\0';
7929 NEWOPENFILENAME new_file_details;
7930 BOOL file_opened = FALSE;
7931 OPENFILENAME * file_details = &new_file_details.real_details;
7933 /* Prevent redisplay. */
7934 specbind (Qinhibit_redisplay, Qt);
7935 BLOCK_INPUT;
7937 bzero (&new_file_details, sizeof (new_file_details));
7938 /* Apparently NT4 crashes if you give it an unexpected size.
7939 I'm not sure about Windows 9x, so play it safe. */
7940 if (w32_major_version > 4 && w32_major_version < 95)
7941 file_details->lStructSize = sizeof (NEWOPENFILENAME);
7942 else
7943 file_details->lStructSize = sizeof (OPENFILENAME);
7945 file_details->hwndOwner = FRAME_W32_WINDOW (f);
7946 /* Undocumented Bug in Common File Dialog:
7947 If a filter is not specified, shell links are not resolved. */
7948 file_details->lpstrFilter = "All Files (*.*)\0*.*\0Directories\0*|*\0\0";
7949 file_details->lpstrFile = filename;
7950 file_details->nMaxFile = sizeof (filename);
7951 file_details->lpstrInitialDir = init_dir;
7952 file_details->lpstrTitle = SDATA (prompt);
7954 if (! NILP (only_dir_p))
7955 default_filter_index = 2;
7957 file_details->nFilterIndex = default_filter_index;
7959 file_details->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7960 | OFN_EXPLORER | OFN_ENABLEHOOK);
7961 if (!NILP (mustmatch))
7963 /* Require that the path to the parent directory exists. */
7964 file_details->Flags |= OFN_PATHMUSTEXIST;
7965 /* If we are looking for a file, require that it exists. */
7966 if (NILP (only_dir_p))
7967 file_details->Flags |= OFN_FILEMUSTEXIST;
7970 file_details->lpfnHook = (LPOFNHOOKPROC) file_dialog_callback;
7972 file_opened = GetOpenFileName (file_details);
7974 UNBLOCK_INPUT;
7976 if (file_opened)
7978 dostounix_filename (filename);
7980 if (file_details->nFilterIndex == 2)
7982 /* "Directories" selected - strip dummy file name. */
7983 char * last = strrchr (filename, '/');
7984 *last = '\0';
7987 file = DECODE_FILE (build_string (filename));
7989 /* User cancelled the dialog without making a selection. */
7990 else if (!CommDlgExtendedError ())
7991 file = Qnil;
7992 /* An error occurred, fallback on reading from the mini-buffer. */
7993 else
7994 file = Fcompleting_read (prompt, intern ("read-file-name-internal"),
7995 dir, mustmatch, dir, Qfile_name_history,
7996 default_filename, Qnil);
7998 file = unbind_to (count, file);
8001 UNGCPRO;
8003 /* Make "Cancel" equivalent to C-g. */
8004 if (NILP (file))
8005 Fsignal (Qquit, Qnil);
8007 return unbind_to (count, file);
8012 /***********************************************************************
8013 w32 specialized functions
8014 ***********************************************************************/
8016 DEFUN ("w32-select-font", Fw32_select_font, Sw32_select_font, 0, 2, 0,
8017 doc: /* Select a font for the named FRAME using the W32 font dialog.
8018 Return an X-style font string corresponding to the selection.
8020 If FRAME is omitted or nil, it defaults to the selected frame.
8021 If INCLUDE-PROPORTIONAL is non-nil, include proportional fonts
8022 in the font selection dialog. */)
8023 (frame, include_proportional)
8024 Lisp_Object frame, include_proportional;
8026 FRAME_PTR f = check_x_frame (frame);
8027 CHOOSEFONT cf;
8028 LOGFONT lf;
8029 TEXTMETRIC tm;
8030 HDC hdc;
8031 HANDLE oldobj;
8032 char buf[100];
8034 bzero (&cf, sizeof (cf));
8035 bzero (&lf, sizeof (lf));
8037 cf.lStructSize = sizeof (cf);
8038 cf.hwndOwner = FRAME_W32_WINDOW (f);
8039 cf.Flags = CF_FORCEFONTEXIST | CF_SCREENFONTS | CF_NOVERTFONTS;
8041 /* Unless include_proportional is non-nil, limit the selection to
8042 monospaced fonts. */
8043 if (NILP (include_proportional))
8044 cf.Flags |= CF_FIXEDPITCHONLY;
8046 cf.lpLogFont = &lf;
8048 /* Initialize as much of the font details as we can from the current
8049 default font. */
8050 hdc = GetDC (FRAME_W32_WINDOW (f));
8051 oldobj = SelectObject (hdc, FRAME_FONT (f)->hfont);
8052 GetTextFace (hdc, LF_FACESIZE, lf.lfFaceName);
8053 if (GetTextMetrics (hdc, &tm))
8055 lf.lfHeight = tm.tmInternalLeading - tm.tmHeight;
8056 lf.lfWeight = tm.tmWeight;
8057 lf.lfItalic = tm.tmItalic;
8058 lf.lfUnderline = tm.tmUnderlined;
8059 lf.lfStrikeOut = tm.tmStruckOut;
8060 lf.lfCharSet = tm.tmCharSet;
8061 cf.Flags |= CF_INITTOLOGFONTSTRUCT;
8063 SelectObject (hdc, oldobj);
8064 ReleaseDC (FRAME_W32_WINDOW (f), hdc);
8066 if (!ChooseFont (&cf) || !w32_to_x_font (&lf, buf, 100, NULL))
8067 return Qnil;
8069 return build_string (buf);
8072 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
8073 Sw32_send_sys_command, 1, 2, 0,
8074 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
8075 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
8076 to minimize), #xf120 to restore frame to original size, and #xf100
8077 to activate the menubar for keyboard access. #xf140 activates the
8078 screen saver if defined.
8080 If optional parameter FRAME is not specified, use selected frame. */)
8081 (command, frame)
8082 Lisp_Object command, frame;
8084 FRAME_PTR f = check_x_frame (frame);
8086 CHECK_NUMBER (command);
8088 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
8090 return Qnil;
8093 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
8094 doc: /* Get Windows to perform OPERATION on DOCUMENT.
8095 This is a wrapper around the ShellExecute system function, which
8096 invokes the application registered to handle OPERATION for DOCUMENT.
8098 OPERATION is either nil or a string that names a supported operation.
8099 What operations can be used depends on the particular DOCUMENT and its
8100 handler application, but typically it is one of the following common
8101 operations:
8103 \"open\" - open DOCUMENT, which could be a file, a directory, or an
8104 executable program. If it is an application, that
8105 application is launched in the current buffer's default
8106 directory. Otherwise, the application associated with
8107 DOCUMENT is launched in the buffer's default directory.
8108 \"print\" - print DOCUMENT, which must be a file
8109 \"explore\" - start the Windows Explorer on DOCUMENT
8110 \"edit\" - launch an editor and open DOCUMENT for editing; which
8111 editor is launched depends on the association for the
8112 specified DOCUMENT
8113 \"find\" - initiate search starting from DOCUMENT which must specify
8114 a directory
8115 nil - invoke the default OPERATION, or \"open\" if default is
8116 not defined or unavailable
8118 DOCUMENT is typically the name of a document file or a URL, but can
8119 also be a program executable to run, or a directory to open in the
8120 Windows Explorer.
8122 If DOCUMENT is a program executable, the optional third arg PARAMETERS
8123 can be a string containing command line parameters that will be passed
8124 to the program; otherwise, PARAMETERS should be nil or unspecified.
8126 Optional fourth argument SHOW-FLAG can be used to control how the
8127 application will be displayed when it is invoked. If SHOW-FLAG is nil
8128 or unspecified, the application is displayed normally, otherwise it is
8129 an integer representing a ShowWindow flag:
8131 0 - start hidden
8132 1 - start normally
8133 3 - start maximized
8134 6 - start minimized */)
8135 (operation, document, parameters, show_flag)
8136 Lisp_Object operation, document, parameters, show_flag;
8138 Lisp_Object current_dir;
8140 CHECK_STRING (document);
8142 /* Encode filename and current directory. */
8143 current_dir = ENCODE_FILE (current_buffer->directory);
8144 document = ENCODE_FILE (document);
8145 if ((int) ShellExecute (NULL,
8146 (STRINGP (operation) ?
8147 SDATA (operation) : NULL),
8148 SDATA (document),
8149 (STRINGP (parameters) ?
8150 SDATA (parameters) : NULL),
8151 SDATA (current_dir),
8152 (INTEGERP (show_flag) ?
8153 XINT (show_flag) : SW_SHOWDEFAULT))
8154 > 32)
8155 return Qt;
8156 error ("ShellExecute failed: %s", w32_strerror (0));
8159 /* Lookup virtual keycode from string representing the name of a
8160 non-ascii keystroke into the corresponding virtual key, using
8161 lispy_function_keys. */
8162 static int
8163 lookup_vk_code (char *key)
8165 int i;
8167 for (i = 0; i < 256; i++)
8168 if (lispy_function_keys[i]
8169 && strcmp (lispy_function_keys[i], key) == 0)
8170 return i;
8172 return -1;
8175 /* Convert a one-element vector style key sequence to a hot key
8176 definition. */
8177 static Lisp_Object
8178 w32_parse_hot_key (key)
8179 Lisp_Object key;
8181 /* Copied from Fdefine_key and store_in_keymap. */
8182 register Lisp_Object c;
8183 int vk_code;
8184 int lisp_modifiers;
8185 int w32_modifiers;
8186 struct gcpro gcpro1;
8188 CHECK_VECTOR (key);
8190 if (XFASTINT (Flength (key)) != 1)
8191 return Qnil;
8193 GCPRO1 (key);
8195 c = Faref (key, make_number (0));
8197 if (CONSP (c) && lucid_event_type_list_p (c))
8198 c = Fevent_convert_list (c);
8200 UNGCPRO;
8202 if (! INTEGERP (c) && ! SYMBOLP (c))
8203 error ("Key definition is invalid");
8205 /* Work out the base key and the modifiers. */
8206 if (SYMBOLP (c))
8208 c = parse_modifiers (c);
8209 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8210 c = Fcar (c);
8211 if (!SYMBOLP (c))
8212 abort ();
8213 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
8215 else if (INTEGERP (c))
8217 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8218 /* Many ascii characters are their own virtual key code. */
8219 vk_code = XINT (c) & CHARACTERBITS;
8222 if (vk_code < 0 || vk_code > 255)
8223 return Qnil;
8225 if ((lisp_modifiers & meta_modifier) != 0
8226 && !NILP (Vw32_alt_is_meta))
8227 lisp_modifiers |= alt_modifier;
8229 /* Supply defs missing from mingw32. */
8230 #ifndef MOD_ALT
8231 #define MOD_ALT 0x0001
8232 #define MOD_CONTROL 0x0002
8233 #define MOD_SHIFT 0x0004
8234 #define MOD_WIN 0x0008
8235 #endif
8237 /* Convert lisp modifiers to Windows hot-key form. */
8238 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8239 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8240 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8241 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8243 return HOTKEY (vk_code, w32_modifiers);
8246 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8247 Sw32_register_hot_key, 1, 1, 0,
8248 doc: /* Register KEY as a hot-key combination.
8249 Certain key combinations like Alt-Tab are reserved for system use on
8250 Windows, and therefore are normally intercepted by the system. However,
8251 most of these key combinations can be received by registering them as
8252 hot-keys, overriding their special meaning.
8254 KEY must be a one element key definition in vector form that would be
8255 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
8256 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
8257 is always interpreted as the Windows modifier keys.
8259 The return value is the hotkey-id if registered, otherwise nil. */)
8260 (key)
8261 Lisp_Object key;
8263 key = w32_parse_hot_key (key);
8265 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8267 /* Reuse an empty slot if possible. */
8268 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8270 /* Safe to add new key to list, even if we have focus. */
8271 if (NILP (item))
8272 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8273 else
8274 XSETCAR (item, key);
8276 /* Notify input thread about new hot-key definition, so that it
8277 takes effect without needing to switch focus. */
8278 #ifdef USE_LISP_UNION_TYPE
8279 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8280 (WPARAM) key.i, 0);
8281 #else
8282 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8283 (WPARAM) key, 0);
8284 #endif
8287 return key;
8290 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8291 Sw32_unregister_hot_key, 1, 1, 0,
8292 doc: /* Unregister KEY as a hot-key combination. */)
8293 (key)
8294 Lisp_Object key;
8296 Lisp_Object item;
8298 if (!INTEGERP (key))
8299 key = w32_parse_hot_key (key);
8301 item = Fmemq (key, w32_grabbed_keys);
8303 if (!NILP (item))
8305 /* Notify input thread about hot-key definition being removed, so
8306 that it takes effect without needing focus switch. */
8307 #ifdef USE_LISP_UNION_TYPE
8308 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8309 (WPARAM) XINT (XCAR (item)), (LPARAM) item.i))
8310 #else
8311 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8312 (WPARAM) XINT (XCAR (item)), (LPARAM) item))
8313 #endif
8315 MSG msg;
8316 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8318 return Qt;
8320 return Qnil;
8323 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8324 Sw32_registered_hot_keys, 0, 0, 0,
8325 doc: /* Return list of registered hot-key IDs. */)
8328 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8331 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8332 Sw32_reconstruct_hot_key, 1, 1, 0,
8333 doc: /* Convert hot-key ID to a lisp key combination.
8334 usage: (w32-reconstruct-hot-key ID) */)
8335 (hotkeyid)
8336 Lisp_Object hotkeyid;
8338 int vk_code, w32_modifiers;
8339 Lisp_Object key;
8341 CHECK_NUMBER (hotkeyid);
8343 vk_code = HOTKEY_VK_CODE (hotkeyid);
8344 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8346 if (vk_code < 256 && lispy_function_keys[vk_code])
8347 key = intern (lispy_function_keys[vk_code]);
8348 else
8349 key = make_number (vk_code);
8351 key = Fcons (key, Qnil);
8352 if (w32_modifiers & MOD_SHIFT)
8353 key = Fcons (Qshift, key);
8354 if (w32_modifiers & MOD_CONTROL)
8355 key = Fcons (Qctrl, key);
8356 if (w32_modifiers & MOD_ALT)
8357 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8358 if (w32_modifiers & MOD_WIN)
8359 key = Fcons (Qhyper, key);
8361 return key;
8364 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8365 Sw32_toggle_lock_key, 1, 2, 0,
8366 doc: /* Toggle the state of the lock key KEY.
8367 KEY can be `capslock', `kp-numlock', or `scroll'.
8368 If the optional parameter NEW-STATE is a number, then the state of KEY
8369 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
8370 (key, new_state)
8371 Lisp_Object key, new_state;
8373 int vk_code;
8375 if (EQ (key, intern ("capslock")))
8376 vk_code = VK_CAPITAL;
8377 else if (EQ (key, intern ("kp-numlock")))
8378 vk_code = VK_NUMLOCK;
8379 else if (EQ (key, intern ("scroll")))
8380 vk_code = VK_SCROLL;
8381 else
8382 return Qnil;
8384 if (!dwWindowsThreadId)
8385 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8387 #ifdef USE_LISP_UNION_TYPE
8388 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8389 (WPARAM) vk_code, (LPARAM) new_state.i))
8390 #else
8391 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8392 (WPARAM) vk_code, (LPARAM) new_state))
8393 #endif
8395 MSG msg;
8396 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8397 return make_number (msg.wParam);
8399 return Qnil;
8402 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8403 2, 2, 0,
8404 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8406 This is a direct interface to the Windows API FindWindow function. */)
8407 (class, name)
8408 Lisp_Object class, name;
8410 HWND hnd;
8412 if (!NILP (class))
8413 CHECK_STRING (class);
8414 if (!NILP (name))
8415 CHECK_STRING (name);
8417 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8418 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8419 if (!hnd)
8420 return Qnil;
8421 return Qt;
8426 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8427 doc: /* Return storage information about the file system FILENAME is on.
8428 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8429 storage of the file system, FREE is the free storage, and AVAIL is the
8430 storage available to a non-superuser. All 3 numbers are in bytes.
8431 If the underlying system call fails, value is nil. */)
8432 (filename)
8433 Lisp_Object filename;
8435 Lisp_Object encoded, value;
8437 CHECK_STRING (filename);
8438 filename = Fexpand_file_name (filename, Qnil);
8439 encoded = ENCODE_FILE (filename);
8441 value = Qnil;
8443 /* Determining the required information on Windows turns out, sadly,
8444 to be more involved than one would hope. The original Win32 api
8445 call for this will return bogus information on some systems, but we
8446 must dynamically probe for the replacement api, since that was
8447 added rather late on. */
8449 HMODULE hKernel = GetModuleHandle ("kernel32");
8450 BOOL (*pfn_GetDiskFreeSpaceEx)
8451 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
8452 = (void *) GetProcAddress (hKernel, "GetDiskFreeSpaceEx");
8454 /* On Windows, we may need to specify the root directory of the
8455 volume holding FILENAME. */
8456 char rootname[MAX_PATH];
8457 char *name = SDATA (encoded);
8459 /* find the root name of the volume if given */
8460 if (isalpha (name[0]) && name[1] == ':')
8462 rootname[0] = name[0];
8463 rootname[1] = name[1];
8464 rootname[2] = '\\';
8465 rootname[3] = 0;
8467 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8469 char *str = rootname;
8470 int slashes = 4;
8473 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8474 break;
8475 *str++ = *name++;
8477 while ( *name );
8479 *str++ = '\\';
8480 *str = 0;
8483 if (pfn_GetDiskFreeSpaceEx)
8485 /* Unsigned large integers cannot be cast to double, so
8486 use signed ones instead. */
8487 LARGE_INTEGER availbytes;
8488 LARGE_INTEGER freebytes;
8489 LARGE_INTEGER totalbytes;
8491 if (pfn_GetDiskFreeSpaceEx (rootname,
8492 (ULARGE_INTEGER *)&availbytes,
8493 (ULARGE_INTEGER *)&totalbytes,
8494 (ULARGE_INTEGER *)&freebytes))
8495 value = list3 (make_float ((double) totalbytes.QuadPart),
8496 make_float ((double) freebytes.QuadPart),
8497 make_float ((double) availbytes.QuadPart));
8499 else
8501 DWORD sectors_per_cluster;
8502 DWORD bytes_per_sector;
8503 DWORD free_clusters;
8504 DWORD total_clusters;
8506 if (GetDiskFreeSpace (rootname,
8507 &sectors_per_cluster,
8508 &bytes_per_sector,
8509 &free_clusters,
8510 &total_clusters))
8511 value = list3 (make_float ((double) total_clusters
8512 * sectors_per_cluster * bytes_per_sector),
8513 make_float ((double) free_clusters
8514 * sectors_per_cluster * bytes_per_sector),
8515 make_float ((double) free_clusters
8516 * sectors_per_cluster * bytes_per_sector));
8520 return value;
8523 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8524 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8527 static char pname_buf[256];
8528 int err;
8529 HANDLE hPrn;
8530 PRINTER_INFO_2 *ppi2 = NULL;
8531 DWORD dwNeeded = 0, dwReturned = 0;
8533 /* Retrieve the default string from Win.ini (the registry).
8534 * String will be in form "printername,drivername,portname".
8535 * This is the most portable way to get the default printer. */
8536 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8537 return Qnil;
8538 /* printername precedes first "," character */
8539 strtok (pname_buf, ",");
8540 /* We want to know more than the printer name */
8541 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8542 return Qnil;
8543 GetPrinter (hPrn, 2, NULL, 0, &dwNeeded);
8544 if (dwNeeded == 0)
8546 ClosePrinter (hPrn);
8547 return Qnil;
8549 /* Allocate memory for the PRINTER_INFO_2 struct */
8550 ppi2 = (PRINTER_INFO_2 *) xmalloc (dwNeeded);
8551 if (!ppi2)
8553 ClosePrinter (hPrn);
8554 return Qnil;
8556 /* Call GetPrinter again with big enouth memory block */
8557 err = GetPrinter (hPrn, 2, (LPBYTE)ppi2, dwNeeded, &dwReturned);
8558 ClosePrinter (hPrn);
8559 if (!err)
8561 xfree (ppi2);
8562 return Qnil;
8565 if (ppi2)
8567 if (ppi2->Attributes & PRINTER_ATTRIBUTE_SHARED && ppi2->pServerName)
8569 /* a remote printer */
8570 if (*ppi2->pServerName == '\\')
8571 _snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", ppi2->pServerName,
8572 ppi2->pShareName);
8573 else
8574 _snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", ppi2->pServerName,
8575 ppi2->pShareName);
8576 pname_buf[sizeof (pname_buf) - 1] = '\0';
8578 else
8580 /* a local printer */
8581 strncpy (pname_buf, ppi2->pPortName, sizeof (pname_buf));
8582 pname_buf[sizeof (pname_buf) - 1] = '\0';
8583 /* `pPortName' can include several ports, delimited by ','.
8584 * we only use the first one. */
8585 strtok (pname_buf, ",");
8587 xfree (ppi2);
8590 return build_string (pname_buf);
8593 /***********************************************************************
8594 Initialization
8595 ***********************************************************************/
8597 /* Keep this list in the same order as frame_parms in frame.c.
8598 Use 0 for unsupported frame parameters. */
8600 frame_parm_handler w32_frame_parm_handlers[] =
8602 x_set_autoraise,
8603 x_set_autolower,
8604 x_set_background_color,
8605 x_set_border_color,
8606 x_set_border_width,
8607 x_set_cursor_color,
8608 x_set_cursor_type,
8609 x_set_font,
8610 x_set_foreground_color,
8611 x_set_icon_name,
8612 x_set_icon_type,
8613 x_set_internal_border_width,
8614 x_set_menu_bar_lines,
8615 x_set_mouse_color,
8616 x_explicitly_set_name,
8617 x_set_scroll_bar_width,
8618 x_set_title,
8619 x_set_unsplittable,
8620 x_set_vertical_scroll_bars,
8621 x_set_visibility,
8622 x_set_tool_bar_lines,
8623 0, /* x_set_scroll_bar_foreground, */
8624 0, /* x_set_scroll_bar_background, */
8625 x_set_screen_gamma,
8626 x_set_line_spacing,
8627 x_set_fringe_width,
8628 x_set_fringe_width,
8629 0, /* x_set_wait_for_wm, */
8630 x_set_fullscreen,
8633 void
8634 syms_of_w32fns ()
8636 globals_of_w32fns ();
8637 /* This is zero if not using MS-Windows. */
8638 w32_in_use = 0;
8639 track_mouse_window = NULL;
8641 w32_visible_system_caret_hwnd = NULL;
8643 Qnone = intern ("none");
8644 staticpro (&Qnone);
8645 Qsuppress_icon = intern ("suppress-icon");
8646 staticpro (&Qsuppress_icon);
8647 Qundefined_color = intern ("undefined-color");
8648 staticpro (&Qundefined_color);
8649 Qcancel_timer = intern ("cancel-timer");
8650 staticpro (&Qcancel_timer);
8652 Qhyper = intern ("hyper");
8653 staticpro (&Qhyper);
8654 Qsuper = intern ("super");
8655 staticpro (&Qsuper);
8656 Qmeta = intern ("meta");
8657 staticpro (&Qmeta);
8658 Qalt = intern ("alt");
8659 staticpro (&Qalt);
8660 Qctrl = intern ("ctrl");
8661 staticpro (&Qctrl);
8662 Qcontrol = intern ("control");
8663 staticpro (&Qcontrol);
8664 Qshift = intern ("shift");
8665 staticpro (&Qshift);
8666 /* This is the end of symbol initialization. */
8668 /* Text property `display' should be nonsticky by default. */
8669 Vtext_property_default_nonsticky
8670 = Fcons (Fcons (Qdisplay, Qt), Vtext_property_default_nonsticky);
8673 Fput (Qundefined_color, Qerror_conditions,
8674 Fcons (Qundefined_color, Fcons (Qerror, Qnil)));
8675 Fput (Qundefined_color, Qerror_message,
8676 build_string ("Undefined color"));
8678 staticpro (&w32_grabbed_keys);
8679 w32_grabbed_keys = Qnil;
8681 DEFVAR_LISP ("w32-color-map", &Vw32_color_map,
8682 doc: /* An array of color name mappings for Windows. */);
8683 Vw32_color_map = Qnil;
8685 DEFVAR_LISP ("w32-pass-alt-to-system", &Vw32_pass_alt_to_system,
8686 doc: /* Non-nil if Alt key presses are passed on to Windows.
8687 When non-nil, for example, Alt pressed and released and then space will
8688 open the System menu. When nil, Emacs processes the Alt key events, and
8689 then silently swallows them. */);
8690 Vw32_pass_alt_to_system = Qnil;
8692 DEFVAR_LISP ("w32-alt-is-meta", &Vw32_alt_is_meta,
8693 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8694 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8695 Vw32_alt_is_meta = Qt;
8697 DEFVAR_INT ("w32-quit-key", &w32_quit_key,
8698 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8699 w32_quit_key = 0;
8701 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8702 &Vw32_pass_lwindow_to_system,
8703 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8705 When non-nil, the Start menu is opened by tapping the key.
8706 If you set this to nil, the left \"Windows\" key is processed by Emacs
8707 according to the value of `w32-lwindow-modifier', which see.
8709 Note that some combinations of the left \"Windows\" key with other keys are
8710 caught by Windows at low level, and so binding them in Emacs will have no
8711 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8712 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8713 the doc string of `w32-phantom-key-code'. */);
8714 Vw32_pass_lwindow_to_system = Qt;
8716 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8717 &Vw32_pass_rwindow_to_system,
8718 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8720 When non-nil, the Start menu is opened by tapping the key.
8721 If you set this to nil, the right \"Windows\" key is processed by Emacs
8722 according to the value of `w32-rwindow-modifier', which see.
8724 Note that some combinations of the right \"Windows\" key with other keys are
8725 caught by Windows at low level, and so binding them in Emacs will have no
8726 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8727 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8728 the doc string of `w32-phantom-key-code'. */);
8729 Vw32_pass_rwindow_to_system = Qt;
8731 DEFVAR_LISP ("w32-phantom-key-code",
8732 &Vw32_phantom_key_code,
8733 doc: /* Virtual key code used to generate \"phantom\" key presses.
8734 Value is a number between 0 and 255.
8736 Phantom key presses are generated in order to stop the system from
8737 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8738 `w32-pass-rwindow-to-system' is nil. */);
8739 /* Although 255 is technically not a valid key code, it works and
8740 means that this hack won't interfere with any real key code. */
8741 XSETINT (Vw32_phantom_key_code, 255);
8743 DEFVAR_LISP ("w32-enable-num-lock",
8744 &Vw32_enable_num_lock,
8745 doc: /* If non-nil, the Num Lock key acts normally.
8746 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8747 Vw32_enable_num_lock = Qt;
8749 DEFVAR_LISP ("w32-enable-caps-lock",
8750 &Vw32_enable_caps_lock,
8751 doc: /* If non-nil, the Caps Lock key acts normally.
8752 Set to nil to handle Caps Lock as the `capslock' key. */);
8753 Vw32_enable_caps_lock = Qt;
8755 DEFVAR_LISP ("w32-scroll-lock-modifier",
8756 &Vw32_scroll_lock_modifier,
8757 doc: /* Modifier to use for the Scroll Lock ON state.
8758 The value can be hyper, super, meta, alt, control or shift for the
8759 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8760 Any other value will cause the Scroll Lock key to be ignored. */);
8761 Vw32_scroll_lock_modifier = Qt;
8763 DEFVAR_LISP ("w32-lwindow-modifier",
8764 &Vw32_lwindow_modifier,
8765 doc: /* Modifier to use for the left \"Windows\" key.
8766 The value can be hyper, super, meta, alt, control or shift for the
8767 respective modifier, or nil to appear as the `lwindow' key.
8768 Any other value will cause the key to be ignored. */);
8769 Vw32_lwindow_modifier = Qnil;
8771 DEFVAR_LISP ("w32-rwindow-modifier",
8772 &Vw32_rwindow_modifier,
8773 doc: /* Modifier to use for the right \"Windows\" key.
8774 The value can be hyper, super, meta, alt, control or shift for the
8775 respective modifier, or nil to appear as the `rwindow' key.
8776 Any other value will cause the key to be ignored. */);
8777 Vw32_rwindow_modifier = Qnil;
8779 DEFVAR_LISP ("w32-apps-modifier",
8780 &Vw32_apps_modifier,
8781 doc: /* Modifier to use for the \"Apps\" key.
8782 The value can be hyper, super, meta, alt, control or shift for the
8783 respective modifier, or nil to appear as the `apps' key.
8784 Any other value will cause the key to be ignored. */);
8785 Vw32_apps_modifier = Qnil;
8787 DEFVAR_BOOL ("w32-enable-synthesized-fonts", &w32_enable_synthesized_fonts,
8788 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8789 w32_enable_synthesized_fonts = 0;
8791 DEFVAR_LISP ("w32-enable-palette", &Vw32_enable_palette,
8792 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8793 Vw32_enable_palette = Qt;
8795 DEFVAR_INT ("w32-mouse-button-tolerance",
8796 &w32_mouse_button_tolerance,
8797 doc: /* Analogue of double click interval for faking middle mouse events.
8798 The value is the minimum time in milliseconds that must elapse between
8799 left and right button down events before they are considered distinct events.
8800 If both mouse buttons are depressed within this interval, a middle mouse
8801 button down event is generated instead. */);
8802 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8804 DEFVAR_INT ("w32-mouse-move-interval",
8805 &w32_mouse_move_interval,
8806 doc: /* Minimum interval between mouse move events.
8807 The value is the minimum time in milliseconds that must elapse between
8808 successive mouse move (or scroll bar drag) events before they are
8809 reported as lisp events. */);
8810 w32_mouse_move_interval = 0;
8812 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8813 &w32_pass_extra_mouse_buttons_to_system,
8814 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8815 Recent versions of Windows support mice with up to five buttons.
8816 Since most applications don't support these extra buttons, most mouse
8817 drivers will allow you to map them to functions at the system level.
8818 If this variable is non-nil, Emacs will pass them on, allowing the
8819 system to handle them. */);
8820 w32_pass_extra_mouse_buttons_to_system = 0;
8822 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8823 &w32_pass_multimedia_buttons_to_system,
8824 doc: /* If non-nil, media buttons are passed to Windows.
8825 Some modern keyboards contain buttons for controlling media players, web
8826 browsers and other applications. Generally these buttons are handled on a
8827 system wide basis, but by setting this to nil they are made available
8828 to Emacs for binding. Depending on your keyboard, additional keys that
8829 may be available are:
8831 browser-back, browser-forward, browser-refresh, browser-stop,
8832 browser-search, browser-favorites, browser-home,
8833 mail, mail-reply, mail-forward, mail-send,
8834 app-1, app-2,
8835 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8836 spell-check, correction-list, toggle-dictate-command,
8837 media-next, media-previous, media-stop, media-play-pause, media-select,
8838 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8839 media-channel-up, media-channel-down,
8840 volume-mute, volume-up, volume-down,
8841 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8842 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8843 w32_pass_multimedia_buttons_to_system = 1;
8845 DEFVAR_LISP ("x-pointer-shape", &Vx_pointer_shape,
8846 doc: /* The shape of the pointer when over text.
8847 Changing the value does not affect existing frames
8848 unless you set the mouse color. */);
8849 Vx_pointer_shape = Qnil;
8851 Vx_nontext_pointer_shape = Qnil;
8853 Vx_mode_pointer_shape = Qnil;
8855 DEFVAR_LISP ("x-hourglass-pointer-shape", &Vx_hourglass_pointer_shape,
8856 doc: /* The shape of the pointer when Emacs is busy.
8857 This variable takes effect when you create a new frame
8858 or when you set the mouse color. */);
8859 Vx_hourglass_pointer_shape = Qnil;
8861 DEFVAR_BOOL ("display-hourglass", &display_hourglass_p,
8862 doc: /* Non-zero means Emacs displays an hourglass pointer on window systems. */);
8863 display_hourglass_p = 1;
8865 DEFVAR_LISP ("hourglass-delay", &Vhourglass_delay,
8866 doc: /* *Seconds to wait before displaying an hourglass pointer.
8867 Value must be an integer or float. */);
8868 Vhourglass_delay = make_number (DEFAULT_HOURGLASS_DELAY);
8870 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8871 &Vx_sensitive_text_pointer_shape,
8872 doc: /* The shape of the pointer when over mouse-sensitive text.
8873 This variable takes effect when you create a new frame
8874 or when you set the mouse color. */);
8875 Vx_sensitive_text_pointer_shape = Qnil;
8877 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8878 &Vx_window_horizontal_drag_shape,
8879 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8880 This variable takes effect when you create a new frame
8881 or when you set the mouse color. */);
8882 Vx_window_horizontal_drag_shape = Qnil;
8884 DEFVAR_LISP ("x-cursor-fore-pixel", &Vx_cursor_fore_pixel,
8885 doc: /* A string indicating the foreground color of the cursor box. */);
8886 Vx_cursor_fore_pixel = Qnil;
8888 DEFVAR_LISP ("x-max-tooltip-size", &Vx_max_tooltip_size,
8889 doc: /* Maximum size for tooltips.
8890 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8891 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8893 DEFVAR_LISP ("x-no-window-manager", &Vx_no_window_manager,
8894 doc: /* Non-nil if no window manager is in use.
8895 Emacs doesn't try to figure this out; this is always nil
8896 unless you set it to something else. */);
8897 /* We don't have any way to find this out, so set it to nil
8898 and maybe the user would like to set it to t. */
8899 Vx_no_window_manager = Qnil;
8901 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8902 &Vx_pixel_size_width_font_regexp,
8903 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8905 Since Emacs gets width of a font matching with this regexp from
8906 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8907 such a font. This is especially effective for such large fonts as
8908 Chinese, Japanese, and Korean. */);
8909 Vx_pixel_size_width_font_regexp = Qnil;
8911 DEFVAR_LISP ("w32-bdf-filename-alist",
8912 &Vw32_bdf_filename_alist,
8913 doc: /* List of bdf fonts and their corresponding filenames. */);
8914 Vw32_bdf_filename_alist = Qnil;
8916 DEFVAR_BOOL ("w32-strict-fontnames",
8917 &w32_strict_fontnames,
8918 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8919 Default is nil, which allows old fontnames that are not XLFD compliant,
8920 and allows third-party CJK display to work by specifying false charset
8921 fields to trick Emacs into translating to Big5, SJIS etc.
8922 Setting this to t will prevent wrong fonts being selected when
8923 fontsets are automatically created. */);
8924 w32_strict_fontnames = 0;
8926 DEFVAR_BOOL ("w32-strict-painting",
8927 &w32_strict_painting,
8928 doc: /* Non-nil means use strict rules for repainting frames.
8929 Set this to nil to get the old behavior for repainting; this should
8930 only be necessary if the default setting causes problems. */);
8931 w32_strict_painting = 1;
8933 DEFVAR_LISP ("w32-charset-info-alist",
8934 &Vw32_charset_info_alist,
8935 doc: /* Alist linking Emacs character sets to Windows fonts and codepages.
8936 Each entry should be of the form:
8938 (CHARSET_NAME . (WINDOWS_CHARSET . CODEPAGE))
8940 where CHARSET_NAME is a string used in font names to identify the charset,
8941 WINDOWS_CHARSET is a symbol that can be one of:
8942 w32-charset-ansi, w32-charset-default, w32-charset-symbol,
8943 w32-charset-shiftjis, w32-charset-hangeul, w32-charset-gb2312,
8944 w32-charset-chinesebig5,
8945 w32-charset-johab, w32-charset-hebrew,
8946 w32-charset-arabic, w32-charset-greek, w32-charset-turkish,
8947 w32-charset-vietnamese, w32-charset-thai, w32-charset-easteurope,
8948 w32-charset-russian, w32-charset-mac, w32-charset-baltic,
8949 w32-charset-unicode,
8950 or w32-charset-oem.
8951 CODEPAGE should be an integer specifying the codepage that should be used
8952 to display the character set, t to do no translation and output as Unicode,
8953 or nil to do no translation and output as 8 bit (or multibyte on far-east
8954 versions of Windows) characters. */);
8955 Vw32_charset_info_alist = Qnil;
8957 staticpro (&Qw32_charset_ansi);
8958 Qw32_charset_ansi = intern ("w32-charset-ansi");
8959 staticpro (&Qw32_charset_symbol);
8960 Qw32_charset_default = intern ("w32-charset-default");
8961 staticpro (&Qw32_charset_default);
8962 Qw32_charset_symbol = intern ("w32-charset-symbol");
8963 staticpro (&Qw32_charset_shiftjis);
8964 Qw32_charset_shiftjis = intern ("w32-charset-shiftjis");
8965 staticpro (&Qw32_charset_hangeul);
8966 Qw32_charset_hangeul = intern ("w32-charset-hangeul");
8967 staticpro (&Qw32_charset_chinesebig5);
8968 Qw32_charset_chinesebig5 = intern ("w32-charset-chinesebig5");
8969 staticpro (&Qw32_charset_gb2312);
8970 Qw32_charset_gb2312 = intern ("w32-charset-gb2312");
8971 staticpro (&Qw32_charset_oem);
8972 Qw32_charset_oem = intern ("w32-charset-oem");
8974 #ifdef JOHAB_CHARSET
8976 static int w32_extra_charsets_defined = 1;
8977 DEFVAR_BOOL ("w32-extra-charsets-defined", &w32_extra_charsets_defined,
8978 doc: /* Internal variable. */);
8980 staticpro (&Qw32_charset_johab);
8981 Qw32_charset_johab = intern ("w32-charset-johab");
8982 staticpro (&Qw32_charset_easteurope);
8983 Qw32_charset_easteurope = intern ("w32-charset-easteurope");
8984 staticpro (&Qw32_charset_turkish);
8985 Qw32_charset_turkish = intern ("w32-charset-turkish");
8986 staticpro (&Qw32_charset_baltic);
8987 Qw32_charset_baltic = intern ("w32-charset-baltic");
8988 staticpro (&Qw32_charset_russian);
8989 Qw32_charset_russian = intern ("w32-charset-russian");
8990 staticpro (&Qw32_charset_arabic);
8991 Qw32_charset_arabic = intern ("w32-charset-arabic");
8992 staticpro (&Qw32_charset_greek);
8993 Qw32_charset_greek = intern ("w32-charset-greek");
8994 staticpro (&Qw32_charset_hebrew);
8995 Qw32_charset_hebrew = intern ("w32-charset-hebrew");
8996 staticpro (&Qw32_charset_vietnamese);
8997 Qw32_charset_vietnamese = intern ("w32-charset-vietnamese");
8998 staticpro (&Qw32_charset_thai);
8999 Qw32_charset_thai = intern ("w32-charset-thai");
9000 staticpro (&Qw32_charset_mac);
9001 Qw32_charset_mac = intern ("w32-charset-mac");
9003 #endif
9005 #ifdef UNICODE_CHARSET
9007 static int w32_unicode_charset_defined = 1;
9008 DEFVAR_BOOL ("w32-unicode-charset-defined",
9009 &w32_unicode_charset_defined,
9010 doc: /* Internal variable. */);
9012 staticpro (&Qw32_charset_unicode);
9013 Qw32_charset_unicode = intern ("w32-charset-unicode");
9015 #endif
9017 #if 0 /* TODO: Port to W32 */
9018 defsubr (&Sx_change_window_property);
9019 defsubr (&Sx_delete_window_property);
9020 defsubr (&Sx_window_property);
9021 #endif
9022 defsubr (&Sxw_display_color_p);
9023 defsubr (&Sx_display_grayscale_p);
9024 defsubr (&Sxw_color_defined_p);
9025 defsubr (&Sxw_color_values);
9026 defsubr (&Sx_server_max_request_size);
9027 defsubr (&Sx_server_vendor);
9028 defsubr (&Sx_server_version);
9029 defsubr (&Sx_display_pixel_width);
9030 defsubr (&Sx_display_pixel_height);
9031 defsubr (&Sx_display_mm_width);
9032 defsubr (&Sx_display_mm_height);
9033 defsubr (&Sx_display_screens);
9034 defsubr (&Sx_display_planes);
9035 defsubr (&Sx_display_color_cells);
9036 defsubr (&Sx_display_visual_class);
9037 defsubr (&Sx_display_backing_store);
9038 defsubr (&Sx_display_save_under);
9039 defsubr (&Sx_create_frame);
9040 defsubr (&Sx_open_connection);
9041 defsubr (&Sx_close_connection);
9042 defsubr (&Sx_display_list);
9043 defsubr (&Sx_synchronize);
9044 defsubr (&Sx_focus_frame);
9046 /* W32 specific functions */
9048 defsubr (&Sw32_select_font);
9049 defsubr (&Sw32_define_rgb_color);
9050 defsubr (&Sw32_default_color_map);
9051 defsubr (&Sw32_load_color_file);
9052 defsubr (&Sw32_send_sys_command);
9053 defsubr (&Sw32_shell_execute);
9054 defsubr (&Sw32_register_hot_key);
9055 defsubr (&Sw32_unregister_hot_key);
9056 defsubr (&Sw32_registered_hot_keys);
9057 defsubr (&Sw32_reconstruct_hot_key);
9058 defsubr (&Sw32_toggle_lock_key);
9059 defsubr (&Sw32_window_exists_p);
9060 defsubr (&Sw32_find_bdf_fonts);
9062 defsubr (&Sfile_system_info);
9063 defsubr (&Sdefault_printer_name);
9065 /* Setting callback functions for fontset handler. */
9066 get_font_info_func = w32_get_font_info;
9068 #if 0 /* This function pointer doesn't seem to be used anywhere.
9069 And the pointer assigned has the wrong type, anyway. */
9070 list_fonts_func = w32_list_fonts;
9071 #endif
9073 load_font_func = w32_load_font;
9074 find_ccl_program_func = w32_find_ccl_program;
9075 query_font_func = w32_query_font;
9076 set_frame_fontset_func = x_set_font;
9077 check_window_system_func = check_w32;
9080 hourglass_atimer = NULL;
9081 hourglass_shown_p = 0;
9082 defsubr (&Sx_show_tip);
9083 defsubr (&Sx_hide_tip);
9084 tip_timer = Qnil;
9085 staticpro (&tip_timer);
9086 tip_frame = Qnil;
9087 staticpro (&tip_frame);
9089 last_show_tip_args = Qnil;
9090 staticpro (&last_show_tip_args);
9092 defsubr (&Sx_file_dialog);
9097 globals_of_w32fns is used to initialize those global variables that
9098 must always be initialized on startup even when the global variable
9099 initialized is non zero (see the function main in emacs.c).
9100 globals_of_w32fns is called from syms_of_w32fns when the global
9101 variable initialized is 0 and directly from main when initialized
9102 is non zero.
9104 void
9105 globals_of_w32fns ()
9107 HMODULE user32_lib = GetModuleHandle ("user32.dll");
9109 TrackMouseEvent not available in all versions of Windows, so must load
9110 it dynamically. Do it once, here, instead of every time it is used.
9112 track_mouse_event_fn = (TrackMouseEvent_Proc)
9113 GetProcAddress (user32_lib, "TrackMouseEvent");
9114 /* ditto for GetClipboardSequenceNumber. */
9115 clipboard_sequence_fn = (ClipboardSequence_Proc)
9116 GetProcAddress (user32_lib, "GetClipboardSequenceNumber");
9118 DEFVAR_INT ("w32-ansi-code-page",
9119 &w32_ansi_code_page,
9120 doc: /* The ANSI code page used by the system. */);
9121 w32_ansi_code_page = GetACP ();
9123 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
9124 InitCommonControls ();
9127 #undef abort
9129 void
9130 w32_abort ()
9132 int button;
9133 button = MessageBox (NULL,
9134 "A fatal error has occurred!\n\n"
9135 "Would you like to attach a debugger?\n\n"
9136 "Select YES to debug, NO to abort Emacs"
9137 #if __GNUC__
9138 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
9139 "\"continue\" inside GDB before clicking YES.)"
9140 #endif
9141 , "Emacs Abort Dialog",
9142 MB_ICONEXCLAMATION | MB_TASKMODAL
9143 | MB_SETFOREGROUND | MB_YESNO);
9144 switch (button)
9146 case IDYES:
9147 DebugBreak ();
9148 exit (2); /* tell the compiler we will never return */
9149 case IDNO:
9150 default:
9151 abort ();
9152 break;
9156 /* For convenience when debugging. */
9158 w32_last_error ()
9160 return GetLastError ();
9163 /* arch-tag: 707589ab-b9be-4638-8cdd-74629cc9b446
9164 (do not change this comment) */