Allow to use the old key processing code on MS-Windows
[emacs.git] / src / w32fns.c
blob34e2720864c64b7b595871a0bc19baebde6714cd
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Added by Kevin Gallo */
22 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <math.h>
29 #include <fcntl.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
34 #include "lisp.h"
35 #include "w32term.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "intervals.h"
41 #include "dispextern.h"
42 #include "keyboard.h"
43 #include "blockinput.h"
44 #include "epaths.h"
45 #include "charset.h"
46 #include "coding.h"
47 #include "ccl.h"
48 #include "fontset.h"
49 #include "systime.h"
50 #include "termhooks.h"
52 #include "w32common.h"
54 #ifdef WINDOWSNT
55 #include "w32heap.h"
56 #include <mbstring.h>
57 #endif /* WINDOWSNT */
59 #if CYGWIN
60 #include "cygw32.h"
61 #else
62 #include "w32.h"
63 #endif
65 #include "bitmaps/gray.xbm"
67 #include <commctrl.h>
68 #include <commdlg.h>
69 #include <shellapi.h>
70 #include <ctype.h>
71 #include <winspool.h>
72 #include <objbase.h>
74 #include <dlgs.h>
75 #include <imm.h>
76 #include <windowsx.h>
78 #include "font.h"
79 #include "w32font.h"
81 #ifndef FOF_NO_CONNECTED_ELEMENTS
82 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
83 #endif
85 void syms_of_w32fns (void);
86 void globals_of_w32fns (void);
88 extern void free_frame_menubar (struct frame *);
89 extern int w32_console_toggle_lock_key (int, Lisp_Object);
90 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
91 extern void w32_free_menu_strings (HWND);
92 extern const char *map_w32_filename (const char *, const char **);
93 extern char * w32_strerror (int error_no);
95 #ifndef IDC_HAND
96 #define IDC_HAND MAKEINTRESOURCE(32649)
97 #endif
99 /* Prefix for system colors. */
100 #define SYSTEM_COLOR_PREFIX "System"
101 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
103 /* State variables for emulating a three button mouse. */
104 #define LMOUSE 1
105 #define MMOUSE 2
106 #define RMOUSE 4
108 static int button_state = 0;
109 static W32Msg saved_mouse_button_msg;
110 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
111 static W32Msg saved_mouse_move_msg;
112 static unsigned mouse_move_timer = 0;
114 /* Window that is tracking the mouse. */
115 static HWND track_mouse_window;
117 /* Multi-monitor API definitions that are not pulled from the headers
118 since we are compiling for NT 4. */
119 #ifndef MONITOR_DEFAULT_TO_NEAREST
120 #define MONITOR_DEFAULT_TO_NEAREST 2
121 #endif
122 #ifndef MONITORINFOF_PRIMARY
123 #define MONITORINFOF_PRIMARY 1
124 #endif
125 #ifndef SM_XVIRTUALSCREEN
126 #define SM_XVIRTUALSCREEN 76
127 #endif
128 #ifndef SM_YVIRTUALSCREEN
129 #define SM_YVIRTUALSCREEN 77
130 #endif
131 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
132 To avoid a compile error on one or the other, redefine with a new name. */
133 struct MONITOR_INFO
135 DWORD cbSize;
136 RECT rcMonitor;
137 RECT rcWork;
138 DWORD dwFlags;
141 #ifndef CCHDEVICENAME
142 #define CCHDEVICENAME 32
143 #endif
144 struct MONITOR_INFO_EX
146 DWORD cbSize;
147 RECT rcMonitor;
148 RECT rcWork;
149 DWORD dwFlags;
150 char szDevice[CCHDEVICENAME];
153 /* Reportedly, MSVC does not have this in its headers. */
154 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
155 DECLARE_HANDLE(HMONITOR);
156 #endif
158 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
159 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
160 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
161 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
162 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
163 typedef BOOL (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
164 typedef BOOL (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
165 IN COMPOSITIONFORM *form);
166 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
167 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
168 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
169 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
170 (IN HWND hwnd, IN DWORD dwFlags);
171 typedef BOOL CALLBACK (* MonitorEnum_Proc)
172 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
173 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
174 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
176 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
177 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
178 ImmGetContext_Proc get_ime_context_fn = NULL;
179 ImmReleaseContext_Proc release_ime_context_fn = NULL;
180 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
181 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
182 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
183 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
184 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
186 #ifdef NTGUI_UNICODE
187 #define unicode_append_menu AppendMenuW
188 #else /* !NTGUI_UNICODE */
189 extern AppendMenuW_Proc unicode_append_menu;
190 #endif /* NTGUI_UNICODE */
192 /* Flag to selectively ignore WM_IME_CHAR messages. */
193 static int ignore_ime_char = 0;
195 /* W95 mousewheel handler */
196 unsigned int msh_mousewheel = 0;
198 /* Timers */
199 #define MOUSE_BUTTON_ID 1
200 #define MOUSE_MOVE_ID 2
201 #define MENU_FREE_ID 3
202 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
203 is received. */
204 #define MENU_FREE_DELAY 1000
205 static unsigned menu_free_timer = 0;
207 #ifdef GLYPH_DEBUG
208 static ptrdiff_t image_cache_refcount;
209 static int dpyinfo_refcount;
210 #endif
212 static HWND w32_visible_system_caret_hwnd;
214 static int w32_unicode_gui;
216 /* From w32menu.c */
217 extern HMENU current_popup_menu;
218 int menubar_in_use = 0;
220 /* From w32uniscribe.c */
221 extern void syms_of_w32uniscribe (void);
222 extern int uniscribe_available;
224 #ifdef WINDOWSNT
225 /* From w32inevt.c */
226 extern int faked_key;
227 #endif /* WINDOWSNT */
229 /* This gives us the page size and the size of the allocation unit on NT. */
230 SYSTEM_INFO sysinfo_cache;
232 /* This gives us version, build, and platform identification. */
233 OSVERSIONINFO osinfo_cache;
235 DWORD_PTR syspage_mask = 0;
237 /* The major and minor versions of NT. */
238 int w32_major_version;
239 int w32_minor_version;
240 int w32_build_number;
242 /* Distinguish between Windows NT and Windows 95. */
243 int os_subtype;
245 #ifdef HAVE_NTGUI
246 HINSTANCE hinst = NULL;
247 #endif
249 static unsigned int sound_type = 0xFFFFFFFF;
250 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
252 /* Let the user specify a display with a frame.
253 nil stands for the selected frame--or, if that is not a w32 frame,
254 the first display on the list. */
256 struct w32_display_info *
257 check_x_display_info (Lisp_Object object)
259 if (NILP (object))
261 struct frame *sf = XFRAME (selected_frame);
263 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
264 return FRAME_DISPLAY_INFO (sf);
265 else
266 return &one_w32_display_info;
268 else if (TERMINALP (object))
270 struct terminal *t = decode_live_terminal (object);
272 if (t->type != output_w32)
273 error ("Terminal %d is not a W32 display", t->id);
275 return t->display_info.w32;
277 else if (STRINGP (object))
278 return x_display_info_for_name (object);
279 else
281 struct frame *f;
283 CHECK_LIVE_FRAME (object);
284 f = XFRAME (object);
285 if (! FRAME_W32_P (f))
286 error ("Non-W32 frame used");
287 return FRAME_DISPLAY_INFO (f);
291 /* Return the Emacs frame-object corresponding to an w32 window.
292 It could be the frame's main window or an icon window. */
294 struct frame *
295 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
297 Lisp_Object tail, frame;
298 struct frame *f;
300 FOR_EACH_FRAME (tail, frame)
302 f = XFRAME (frame);
303 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
304 continue;
306 if (FRAME_W32_WINDOW (f) == wdesc)
307 return f;
309 return 0;
313 static Lisp_Object unwind_create_frame (Lisp_Object);
314 static void unwind_create_tip_frame (Lisp_Object);
315 static void my_create_window (struct frame *);
316 static void my_create_tip_window (struct frame *);
318 /* TODO: Native Input Method support; see x_create_im. */
319 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
320 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
321 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
322 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
323 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
324 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
325 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
326 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
327 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
328 void x_set_menu_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
329 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
330 void x_set_tool_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
331 void x_set_internal_border_width (struct frame *f, Lisp_Object, Lisp_Object);
334 /* Store the screen positions of frame F into XPTR and YPTR.
335 These are the positions of the containing window manager window,
336 not Emacs's own window. */
338 void
339 x_real_positions (struct frame *f, int *xptr, int *yptr)
341 POINT pt;
342 RECT rect;
344 /* Get the bounds of the WM window. */
345 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
347 pt.x = 0;
348 pt.y = 0;
350 /* Convert (0, 0) in the client area to screen co-ordinates. */
351 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
353 *xptr = rect.left;
354 *yptr = rect.top;
357 /* Returns the window rectangle appropriate for the given fullscreen mode.
358 The normal rect parameter was the window's rectangle prior to entering
359 fullscreen mode. If multiple monitor support is available, the nearest
360 monitor to the window is chosen. */
362 void
363 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
365 struct MONITOR_INFO mi = { sizeof(mi) };
366 if (monitor_from_window_fn && get_monitor_info_fn)
368 HMONITOR monitor =
369 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
370 get_monitor_info_fn (monitor, &mi);
372 else
374 mi.rcMonitor.left = 0;
375 mi.rcMonitor.top = 0;
376 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
377 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
378 mi.rcWork.left = 0;
379 mi.rcWork.top = 0;
380 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
381 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
384 switch (fsmode)
386 case FULLSCREEN_BOTH:
387 rect->left = mi.rcMonitor.left;
388 rect->top = mi.rcMonitor.top;
389 rect->right = mi.rcMonitor.right;
390 rect->bottom = mi.rcMonitor.bottom;
391 break;
392 case FULLSCREEN_WIDTH:
393 rect->left = mi.rcWork.left;
394 rect->top = normal.top;
395 rect->right = mi.rcWork.right;
396 rect->bottom = normal.bottom;
397 break;
398 case FULLSCREEN_HEIGHT:
399 rect->left = normal.left;
400 rect->top = mi.rcWork.top;
401 rect->right = normal.right;
402 rect->bottom = mi.rcWork.bottom;
403 break;
404 default:
405 *rect = normal;
406 break;
412 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
413 Sw32_define_rgb_color, 4, 4, 0,
414 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
415 This adds or updates a named color to `w32-color-map', making it
416 available for use. The original entry's RGB ref is returned, or nil
417 if the entry is new. */)
418 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
420 Lisp_Object rgb;
421 Lisp_Object oldrgb = Qnil;
422 Lisp_Object entry;
424 CHECK_NUMBER (red);
425 CHECK_NUMBER (green);
426 CHECK_NUMBER (blue);
427 CHECK_STRING (name);
429 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
431 block_input ();
433 /* replace existing entry in w32-color-map or add new entry. */
434 entry = Fassoc (name, Vw32_color_map);
435 if (NILP (entry))
437 entry = Fcons (name, rgb);
438 Vw32_color_map = Fcons (entry, Vw32_color_map);
440 else
442 oldrgb = Fcdr (entry);
443 Fsetcdr (entry, rgb);
446 unblock_input ();
448 return (oldrgb);
451 /* The default colors for the w32 color map */
452 typedef struct colormap_t
454 char *name;
455 COLORREF colorref;
456 } colormap_t;
458 colormap_t w32_color_map[] =
460 {"snow" , PALETTERGB (255,250,250)},
461 {"ghost white" , PALETTERGB (248,248,255)},
462 {"GhostWhite" , PALETTERGB (248,248,255)},
463 {"white smoke" , PALETTERGB (245,245,245)},
464 {"WhiteSmoke" , PALETTERGB (245,245,245)},
465 {"gainsboro" , PALETTERGB (220,220,220)},
466 {"floral white" , PALETTERGB (255,250,240)},
467 {"FloralWhite" , PALETTERGB (255,250,240)},
468 {"old lace" , PALETTERGB (253,245,230)},
469 {"OldLace" , PALETTERGB (253,245,230)},
470 {"linen" , PALETTERGB (250,240,230)},
471 {"antique white" , PALETTERGB (250,235,215)},
472 {"AntiqueWhite" , PALETTERGB (250,235,215)},
473 {"papaya whip" , PALETTERGB (255,239,213)},
474 {"PapayaWhip" , PALETTERGB (255,239,213)},
475 {"blanched almond" , PALETTERGB (255,235,205)},
476 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
477 {"bisque" , PALETTERGB (255,228,196)},
478 {"peach puff" , PALETTERGB (255,218,185)},
479 {"PeachPuff" , PALETTERGB (255,218,185)},
480 {"navajo white" , PALETTERGB (255,222,173)},
481 {"NavajoWhite" , PALETTERGB (255,222,173)},
482 {"moccasin" , PALETTERGB (255,228,181)},
483 {"cornsilk" , PALETTERGB (255,248,220)},
484 {"ivory" , PALETTERGB (255,255,240)},
485 {"lemon chiffon" , PALETTERGB (255,250,205)},
486 {"LemonChiffon" , PALETTERGB (255,250,205)},
487 {"seashell" , PALETTERGB (255,245,238)},
488 {"honeydew" , PALETTERGB (240,255,240)},
489 {"mint cream" , PALETTERGB (245,255,250)},
490 {"MintCream" , PALETTERGB (245,255,250)},
491 {"azure" , PALETTERGB (240,255,255)},
492 {"alice blue" , PALETTERGB (240,248,255)},
493 {"AliceBlue" , PALETTERGB (240,248,255)},
494 {"lavender" , PALETTERGB (230,230,250)},
495 {"lavender blush" , PALETTERGB (255,240,245)},
496 {"LavenderBlush" , PALETTERGB (255,240,245)},
497 {"misty rose" , PALETTERGB (255,228,225)},
498 {"MistyRose" , PALETTERGB (255,228,225)},
499 {"white" , PALETTERGB (255,255,255)},
500 {"black" , PALETTERGB ( 0, 0, 0)},
501 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
502 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
503 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
504 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
505 {"dim gray" , PALETTERGB (105,105,105)},
506 {"DimGray" , PALETTERGB (105,105,105)},
507 {"dim grey" , PALETTERGB (105,105,105)},
508 {"DimGrey" , PALETTERGB (105,105,105)},
509 {"slate gray" , PALETTERGB (112,128,144)},
510 {"SlateGray" , PALETTERGB (112,128,144)},
511 {"slate grey" , PALETTERGB (112,128,144)},
512 {"SlateGrey" , PALETTERGB (112,128,144)},
513 {"light slate gray" , PALETTERGB (119,136,153)},
514 {"LightSlateGray" , PALETTERGB (119,136,153)},
515 {"light slate grey" , PALETTERGB (119,136,153)},
516 {"LightSlateGrey" , PALETTERGB (119,136,153)},
517 {"gray" , PALETTERGB (190,190,190)},
518 {"grey" , PALETTERGB (190,190,190)},
519 {"light grey" , PALETTERGB (211,211,211)},
520 {"LightGrey" , PALETTERGB (211,211,211)},
521 {"light gray" , PALETTERGB (211,211,211)},
522 {"LightGray" , PALETTERGB (211,211,211)},
523 {"midnight blue" , PALETTERGB ( 25, 25,112)},
524 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
525 {"navy" , PALETTERGB ( 0, 0,128)},
526 {"navy blue" , PALETTERGB ( 0, 0,128)},
527 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
528 {"cornflower blue" , PALETTERGB (100,149,237)},
529 {"CornflowerBlue" , PALETTERGB (100,149,237)},
530 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
531 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
532 {"slate blue" , PALETTERGB (106, 90,205)},
533 {"SlateBlue" , PALETTERGB (106, 90,205)},
534 {"medium slate blue" , PALETTERGB (123,104,238)},
535 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
536 {"light slate blue" , PALETTERGB (132,112,255)},
537 {"LightSlateBlue" , PALETTERGB (132,112,255)},
538 {"medium blue" , PALETTERGB ( 0, 0,205)},
539 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
540 {"royal blue" , PALETTERGB ( 65,105,225)},
541 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
542 {"blue" , PALETTERGB ( 0, 0,255)},
543 {"dodger blue" , PALETTERGB ( 30,144,255)},
544 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
545 {"deep sky blue" , PALETTERGB ( 0,191,255)},
546 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
547 {"sky blue" , PALETTERGB (135,206,235)},
548 {"SkyBlue" , PALETTERGB (135,206,235)},
549 {"light sky blue" , PALETTERGB (135,206,250)},
550 {"LightSkyBlue" , PALETTERGB (135,206,250)},
551 {"steel blue" , PALETTERGB ( 70,130,180)},
552 {"SteelBlue" , PALETTERGB ( 70,130,180)},
553 {"light steel blue" , PALETTERGB (176,196,222)},
554 {"LightSteelBlue" , PALETTERGB (176,196,222)},
555 {"light blue" , PALETTERGB (173,216,230)},
556 {"LightBlue" , PALETTERGB (173,216,230)},
557 {"powder blue" , PALETTERGB (176,224,230)},
558 {"PowderBlue" , PALETTERGB (176,224,230)},
559 {"pale turquoise" , PALETTERGB (175,238,238)},
560 {"PaleTurquoise" , PALETTERGB (175,238,238)},
561 {"dark turquoise" , PALETTERGB ( 0,206,209)},
562 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
563 {"medium turquoise" , PALETTERGB ( 72,209,204)},
564 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
565 {"turquoise" , PALETTERGB ( 64,224,208)},
566 {"cyan" , PALETTERGB ( 0,255,255)},
567 {"light cyan" , PALETTERGB (224,255,255)},
568 {"LightCyan" , PALETTERGB (224,255,255)},
569 {"cadet blue" , PALETTERGB ( 95,158,160)},
570 {"CadetBlue" , PALETTERGB ( 95,158,160)},
571 {"medium aquamarine" , PALETTERGB (102,205,170)},
572 {"MediumAquamarine" , PALETTERGB (102,205,170)},
573 {"aquamarine" , PALETTERGB (127,255,212)},
574 {"dark green" , PALETTERGB ( 0,100, 0)},
575 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
576 {"dark olive green" , PALETTERGB ( 85,107, 47)},
577 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
578 {"dark sea green" , PALETTERGB (143,188,143)},
579 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
580 {"sea green" , PALETTERGB ( 46,139, 87)},
581 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
582 {"medium sea green" , PALETTERGB ( 60,179,113)},
583 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
584 {"light sea green" , PALETTERGB ( 32,178,170)},
585 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
586 {"pale green" , PALETTERGB (152,251,152)},
587 {"PaleGreen" , PALETTERGB (152,251,152)},
588 {"spring green" , PALETTERGB ( 0,255,127)},
589 {"SpringGreen" , PALETTERGB ( 0,255,127)},
590 {"lawn green" , PALETTERGB (124,252, 0)},
591 {"LawnGreen" , PALETTERGB (124,252, 0)},
592 {"green" , PALETTERGB ( 0,255, 0)},
593 {"chartreuse" , PALETTERGB (127,255, 0)},
594 {"medium spring green" , PALETTERGB ( 0,250,154)},
595 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
596 {"green yellow" , PALETTERGB (173,255, 47)},
597 {"GreenYellow" , PALETTERGB (173,255, 47)},
598 {"lime green" , PALETTERGB ( 50,205, 50)},
599 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
600 {"yellow green" , PALETTERGB (154,205, 50)},
601 {"YellowGreen" , PALETTERGB (154,205, 50)},
602 {"forest green" , PALETTERGB ( 34,139, 34)},
603 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
604 {"olive drab" , PALETTERGB (107,142, 35)},
605 {"OliveDrab" , PALETTERGB (107,142, 35)},
606 {"dark khaki" , PALETTERGB (189,183,107)},
607 {"DarkKhaki" , PALETTERGB (189,183,107)},
608 {"khaki" , PALETTERGB (240,230,140)},
609 {"pale goldenrod" , PALETTERGB (238,232,170)},
610 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
611 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
612 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
613 {"light yellow" , PALETTERGB (255,255,224)},
614 {"LightYellow" , PALETTERGB (255,255,224)},
615 {"yellow" , PALETTERGB (255,255, 0)},
616 {"gold" , PALETTERGB (255,215, 0)},
617 {"light goldenrod" , PALETTERGB (238,221,130)},
618 {"LightGoldenrod" , PALETTERGB (238,221,130)},
619 {"goldenrod" , PALETTERGB (218,165, 32)},
620 {"dark goldenrod" , PALETTERGB (184,134, 11)},
621 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
622 {"rosy brown" , PALETTERGB (188,143,143)},
623 {"RosyBrown" , PALETTERGB (188,143,143)},
624 {"indian red" , PALETTERGB (205, 92, 92)},
625 {"IndianRed" , PALETTERGB (205, 92, 92)},
626 {"saddle brown" , PALETTERGB (139, 69, 19)},
627 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
628 {"sienna" , PALETTERGB (160, 82, 45)},
629 {"peru" , PALETTERGB (205,133, 63)},
630 {"burlywood" , PALETTERGB (222,184,135)},
631 {"beige" , PALETTERGB (245,245,220)},
632 {"wheat" , PALETTERGB (245,222,179)},
633 {"sandy brown" , PALETTERGB (244,164, 96)},
634 {"SandyBrown" , PALETTERGB (244,164, 96)},
635 {"tan" , PALETTERGB (210,180,140)},
636 {"chocolate" , PALETTERGB (210,105, 30)},
637 {"firebrick" , PALETTERGB (178,34, 34)},
638 {"brown" , PALETTERGB (165,42, 42)},
639 {"dark salmon" , PALETTERGB (233,150,122)},
640 {"DarkSalmon" , PALETTERGB (233,150,122)},
641 {"salmon" , PALETTERGB (250,128,114)},
642 {"light salmon" , PALETTERGB (255,160,122)},
643 {"LightSalmon" , PALETTERGB (255,160,122)},
644 {"orange" , PALETTERGB (255,165, 0)},
645 {"dark orange" , PALETTERGB (255,140, 0)},
646 {"DarkOrange" , PALETTERGB (255,140, 0)},
647 {"coral" , PALETTERGB (255,127, 80)},
648 {"light coral" , PALETTERGB (240,128,128)},
649 {"LightCoral" , PALETTERGB (240,128,128)},
650 {"tomato" , PALETTERGB (255, 99, 71)},
651 {"orange red" , PALETTERGB (255, 69, 0)},
652 {"OrangeRed" , PALETTERGB (255, 69, 0)},
653 {"red" , PALETTERGB (255, 0, 0)},
654 {"hot pink" , PALETTERGB (255,105,180)},
655 {"HotPink" , PALETTERGB (255,105,180)},
656 {"deep pink" , PALETTERGB (255, 20,147)},
657 {"DeepPink" , PALETTERGB (255, 20,147)},
658 {"pink" , PALETTERGB (255,192,203)},
659 {"light pink" , PALETTERGB (255,182,193)},
660 {"LightPink" , PALETTERGB (255,182,193)},
661 {"pale violet red" , PALETTERGB (219,112,147)},
662 {"PaleVioletRed" , PALETTERGB (219,112,147)},
663 {"maroon" , PALETTERGB (176, 48, 96)},
664 {"medium violet red" , PALETTERGB (199, 21,133)},
665 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
666 {"violet red" , PALETTERGB (208, 32,144)},
667 {"VioletRed" , PALETTERGB (208, 32,144)},
668 {"magenta" , PALETTERGB (255, 0,255)},
669 {"violet" , PALETTERGB (238,130,238)},
670 {"plum" , PALETTERGB (221,160,221)},
671 {"orchid" , PALETTERGB (218,112,214)},
672 {"medium orchid" , PALETTERGB (186, 85,211)},
673 {"MediumOrchid" , PALETTERGB (186, 85,211)},
674 {"dark orchid" , PALETTERGB (153, 50,204)},
675 {"DarkOrchid" , PALETTERGB (153, 50,204)},
676 {"dark violet" , PALETTERGB (148, 0,211)},
677 {"DarkViolet" , PALETTERGB (148, 0,211)},
678 {"blue violet" , PALETTERGB (138, 43,226)},
679 {"BlueViolet" , PALETTERGB (138, 43,226)},
680 {"purple" , PALETTERGB (160, 32,240)},
681 {"medium purple" , PALETTERGB (147,112,219)},
682 {"MediumPurple" , PALETTERGB (147,112,219)},
683 {"thistle" , PALETTERGB (216,191,216)},
684 {"gray0" , PALETTERGB ( 0, 0, 0)},
685 {"grey0" , PALETTERGB ( 0, 0, 0)},
686 {"dark grey" , PALETTERGB (169,169,169)},
687 {"DarkGrey" , PALETTERGB (169,169,169)},
688 {"dark gray" , PALETTERGB (169,169,169)},
689 {"DarkGray" , PALETTERGB (169,169,169)},
690 {"dark blue" , PALETTERGB ( 0, 0,139)},
691 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
692 {"dark cyan" , PALETTERGB ( 0,139,139)},
693 {"DarkCyan" , PALETTERGB ( 0,139,139)},
694 {"dark magenta" , PALETTERGB (139, 0,139)},
695 {"DarkMagenta" , PALETTERGB (139, 0,139)},
696 {"dark red" , PALETTERGB (139, 0, 0)},
697 {"DarkRed" , PALETTERGB (139, 0, 0)},
698 {"light green" , PALETTERGB (144,238,144)},
699 {"LightGreen" , PALETTERGB (144,238,144)},
702 static Lisp_Object
703 w32_default_color_map (void)
705 int i;
706 colormap_t *pc = w32_color_map;
707 Lisp_Object cmap;
709 block_input ();
711 cmap = Qnil;
713 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
714 cmap = Fcons (Fcons (build_string (pc->name),
715 make_number (pc->colorref)),
716 cmap);
718 unblock_input ();
720 return (cmap);
723 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
724 0, 0, 0, doc: /* Return the default color map. */)
725 (void)
727 return w32_default_color_map ();
730 static Lisp_Object
731 w32_color_map_lookup (const char *colorname)
733 Lisp_Object tail, ret = Qnil;
735 block_input ();
737 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
739 register Lisp_Object elt, tem;
741 elt = XCAR (tail);
742 if (!CONSP (elt)) continue;
744 tem = XCAR (elt);
746 if (lstrcmpi (SDATA (tem), colorname) == 0)
748 ret = Fcdr (elt);
749 break;
752 QUIT;
755 unblock_input ();
757 return ret;
761 static void
762 add_system_logical_colors_to_map (Lisp_Object *system_colors)
764 HKEY colors_key;
766 /* Other registry operations are done with input blocked. */
767 block_input ();
769 /* Look for "Control Panel/Colors" under User and Machine registry
770 settings. */
771 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
772 KEY_READ, &colors_key) == ERROR_SUCCESS
773 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
774 KEY_READ, &colors_key) == ERROR_SUCCESS)
776 /* List all keys. */
777 char color_buffer[64];
778 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
779 int index = 0;
780 DWORD name_size, color_size;
781 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
783 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
784 color_size = sizeof (color_buffer);
786 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
788 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
789 NULL, NULL, color_buffer, &color_size)
790 == ERROR_SUCCESS)
792 int r, g, b;
793 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
794 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
795 make_number (RGB (r, g, b))),
796 *system_colors);
798 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
799 color_size = sizeof (color_buffer);
800 index++;
802 RegCloseKey (colors_key);
805 unblock_input ();
809 static Lisp_Object
810 x_to_w32_color (const char * colorname)
812 register Lisp_Object ret = Qnil;
814 block_input ();
816 if (colorname[0] == '#')
818 /* Could be an old-style RGB Device specification. */
819 int size = strlen (colorname + 1);
820 char *color = alloca (size + 1);
822 strcpy (color, colorname + 1);
823 if (size == 3 || size == 6 || size == 9 || size == 12)
825 UINT colorval;
826 int i, pos;
827 pos = 0;
828 size /= 3;
829 colorval = 0;
831 for (i = 0; i < 3; i++)
833 char *end;
834 char t;
835 unsigned long value;
837 /* The check for 'x' in the following conditional takes into
838 account the fact that strtol allows a "0x" in front of
839 our numbers, and we don't. */
840 if (!isxdigit (color[0]) || color[1] == 'x')
841 break;
842 t = color[size];
843 color[size] = '\0';
844 value = strtoul (color, &end, 16);
845 color[size] = t;
846 if (errno == ERANGE || end - color != size)
847 break;
848 switch (size)
850 case 1:
851 value = value * 0x10;
852 break;
853 case 2:
854 break;
855 case 3:
856 value /= 0x10;
857 break;
858 case 4:
859 value /= 0x100;
860 break;
862 colorval |= (value << pos);
863 pos += 0x8;
864 if (i == 2)
866 unblock_input ();
867 XSETINT (ret, colorval);
868 return ret;
870 color = end;
874 else if (strnicmp (colorname, "rgb:", 4) == 0)
876 const char *color;
877 UINT colorval;
878 int i, pos;
879 pos = 0;
881 colorval = 0;
882 color = colorname + 4;
883 for (i = 0; i < 3; i++)
885 char *end;
886 unsigned long value;
888 /* The check for 'x' in the following conditional takes into
889 account the fact that strtol allows a "0x" in front of
890 our numbers, and we don't. */
891 if (!isxdigit (color[0]) || color[1] == 'x')
892 break;
893 value = strtoul (color, &end, 16);
894 if (errno == ERANGE)
895 break;
896 switch (end - color)
898 case 1:
899 value = value * 0x10 + value;
900 break;
901 case 2:
902 break;
903 case 3:
904 value /= 0x10;
905 break;
906 case 4:
907 value /= 0x100;
908 break;
909 default:
910 value = ULONG_MAX;
912 if (value == ULONG_MAX)
913 break;
914 colorval |= (value << pos);
915 pos += 0x8;
916 if (i == 2)
918 if (*end != '\0')
919 break;
920 unblock_input ();
921 XSETINT (ret, colorval);
922 return ret;
924 if (*end != '/')
925 break;
926 color = end + 1;
929 else if (strnicmp (colorname, "rgbi:", 5) == 0)
931 /* This is an RGB Intensity specification. */
932 const char *color;
933 UINT colorval;
934 int i, pos;
935 pos = 0;
937 colorval = 0;
938 color = colorname + 5;
939 for (i = 0; i < 3; i++)
941 char *end;
942 double value;
943 UINT val;
945 value = strtod (color, &end);
946 if (errno == ERANGE)
947 break;
948 if (value < 0.0 || value > 1.0)
949 break;
950 val = (UINT)(0x100 * value);
951 /* We used 0x100 instead of 0xFF to give a continuous
952 range between 0.0 and 1.0 inclusive. The next statement
953 fixes the 1.0 case. */
954 if (val == 0x100)
955 val = 0xFF;
956 colorval |= (val << pos);
957 pos += 0x8;
958 if (i == 2)
960 if (*end != '\0')
961 break;
962 unblock_input ();
963 XSETINT (ret, colorval);
964 return ret;
966 if (*end != '/')
967 break;
968 color = end + 1;
971 /* I am not going to attempt to handle any of the CIE color schemes
972 or TekHVC, since I don't know the algorithms for conversion to
973 RGB. */
975 /* If we fail to lookup the color name in w32_color_map, then check the
976 colorname to see if it can be crudely approximated: If the X color
977 ends in a number (e.g., "darkseagreen2"), strip the number and
978 return the result of looking up the base color name. */
979 ret = w32_color_map_lookup (colorname);
980 if (NILP (ret))
982 int len = strlen (colorname);
984 if (isdigit (colorname[len - 1]))
986 char *ptr, *approx = alloca (len + 1);
988 strcpy (approx, colorname);
989 ptr = &approx[len - 1];
990 while (ptr > approx && isdigit (*ptr))
991 *ptr-- = '\0';
993 ret = w32_color_map_lookup (approx);
997 unblock_input ();
998 return ret;
1001 void
1002 w32_regenerate_palette (struct frame *f)
1004 struct w32_palette_entry * list;
1005 LOGPALETTE * log_palette;
1006 HPALETTE new_palette;
1007 int i;
1009 /* don't bother trying to create palette if not supported */
1010 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1011 return;
1013 log_palette = (LOGPALETTE *)
1014 alloca (sizeof (LOGPALETTE) +
1015 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1016 log_palette->palVersion = 0x300;
1017 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1019 list = FRAME_DISPLAY_INFO (f)->color_list;
1020 for (i = 0;
1021 i < FRAME_DISPLAY_INFO (f)->num_colors;
1022 i++, list = list->next)
1023 log_palette->palPalEntry[i] = list->entry;
1025 new_palette = CreatePalette (log_palette);
1027 enter_crit ();
1029 if (FRAME_DISPLAY_INFO (f)->palette)
1030 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1031 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1033 /* Realize display palette and garbage all frames. */
1034 release_frame_dc (f, get_frame_dc (f));
1036 leave_crit ();
1039 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1040 #define SET_W32_COLOR(pe, color) \
1041 do \
1043 pe.peRed = GetRValue (color); \
1044 pe.peGreen = GetGValue (color); \
1045 pe.peBlue = GetBValue (color); \
1046 pe.peFlags = 0; \
1047 } while (0)
1049 #if 0
1050 /* Keep these around in case we ever want to track color usage. */
1051 void
1052 w32_map_color (struct frame *f, COLORREF color)
1054 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1056 if (NILP (Vw32_enable_palette))
1057 return;
1059 /* check if color is already mapped */
1060 while (list)
1062 if (W32_COLOR (list->entry) == color)
1064 ++list->refcount;
1065 return;
1067 list = list->next;
1070 /* not already mapped, so add to list and recreate Windows palette */
1071 list = xmalloc (sizeof (struct w32_palette_entry));
1072 SET_W32_COLOR (list->entry, color);
1073 list->refcount = 1;
1074 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1075 FRAME_DISPLAY_INFO (f)->color_list = list;
1076 FRAME_DISPLAY_INFO (f)->num_colors++;
1078 /* set flag that palette must be regenerated */
1079 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1082 void
1083 w32_unmap_color (struct frame *f, COLORREF color)
1085 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1086 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1088 if (NILP (Vw32_enable_palette))
1089 return;
1091 /* check if color is already mapped */
1092 while (list)
1094 if (W32_COLOR (list->entry) == color)
1096 if (--list->refcount == 0)
1098 *prev = list->next;
1099 xfree (list);
1100 FRAME_DISPLAY_INFO (f)->num_colors--;
1101 break;
1103 else
1104 return;
1106 prev = &list->next;
1107 list = list->next;
1110 /* set flag that palette must be regenerated */
1111 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1113 #endif
1116 /* Gamma-correct COLOR on frame F. */
1118 void
1119 gamma_correct (struct frame *f, COLORREF *color)
1121 if (f->gamma)
1123 *color = PALETTERGB (
1124 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1125 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1126 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1131 /* Decide if color named COLOR is valid for the display associated with
1132 the selected frame; if so, return the rgb values in COLOR_DEF.
1133 If ALLOC is nonzero, allocate a new colormap cell. */
1136 w32_defined_color (struct frame *f, const char *color, XColor *color_def,
1137 bool alloc_p)
1139 register Lisp_Object tem;
1140 COLORREF w32_color_ref;
1142 tem = x_to_w32_color (color);
1144 if (!NILP (tem))
1146 if (f)
1148 /* Apply gamma correction. */
1149 w32_color_ref = XUINT (tem);
1150 gamma_correct (f, &w32_color_ref);
1151 XSETINT (tem, w32_color_ref);
1154 /* Map this color to the palette if it is enabled. */
1155 if (!NILP (Vw32_enable_palette))
1157 struct w32_palette_entry * entry =
1158 one_w32_display_info.color_list;
1159 struct w32_palette_entry ** prev =
1160 &one_w32_display_info.color_list;
1162 /* check if color is already mapped */
1163 while (entry)
1165 if (W32_COLOR (entry->entry) == XUINT (tem))
1166 break;
1167 prev = &entry->next;
1168 entry = entry->next;
1171 if (entry == NULL && alloc_p)
1173 /* not already mapped, so add to list */
1174 entry = xmalloc (sizeof (struct w32_palette_entry));
1175 SET_W32_COLOR (entry->entry, XUINT (tem));
1176 entry->next = NULL;
1177 *prev = entry;
1178 one_w32_display_info.num_colors++;
1180 /* set flag that palette must be regenerated */
1181 one_w32_display_info.regen_palette = TRUE;
1184 /* Ensure COLORREF value is snapped to nearest color in (default)
1185 palette by simulating the PALETTERGB macro. This works whether
1186 or not the display device has a palette. */
1187 w32_color_ref = XUINT (tem) | 0x2000000;
1189 color_def->pixel = w32_color_ref;
1190 color_def->red = GetRValue (w32_color_ref) * 256;
1191 color_def->green = GetGValue (w32_color_ref) * 256;
1192 color_def->blue = GetBValue (w32_color_ref) * 256;
1194 return 1;
1196 else
1198 return 0;
1202 /* Given a string ARG naming a color, compute a pixel value from it
1203 suitable for screen F.
1204 If F is not a color screen, return DEF (default) regardless of what
1205 ARG says. */
1208 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1210 XColor cdef;
1212 CHECK_STRING (arg);
1214 if (strcmp (SDATA (arg), "black") == 0)
1215 return BLACK_PIX_DEFAULT (f);
1216 else if (strcmp (SDATA (arg), "white") == 0)
1217 return WHITE_PIX_DEFAULT (f);
1219 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1220 return def;
1222 /* w32_defined_color is responsible for coping with failures
1223 by looking for a near-miss. */
1224 if (w32_defined_color (f, SDATA (arg), &cdef, true))
1225 return cdef.pixel;
1227 /* defined_color failed; return an ultimate default. */
1228 return def;
1233 /* Functions called only from `x_set_frame_param'
1234 to set individual parameters.
1236 If FRAME_W32_WINDOW (f) is 0,
1237 the frame is being created and its window does not exist yet.
1238 In that case, just record the parameter's new value
1239 in the standard place; do not attempt to change the window. */
1241 void
1242 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1244 struct w32_output *x = f->output_data.w32;
1245 PIX_TYPE fg, old_fg;
1247 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1248 old_fg = FRAME_FOREGROUND_PIXEL (f);
1249 FRAME_FOREGROUND_PIXEL (f) = fg;
1251 if (FRAME_W32_WINDOW (f) != 0)
1253 if (x->cursor_pixel == old_fg)
1255 x->cursor_pixel = fg;
1256 x->cursor_gc->background = fg;
1259 update_face_from_frame_parameter (f, Qforeground_color, arg);
1260 if (FRAME_VISIBLE_P (f))
1261 redraw_frame (f);
1265 void
1266 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1268 FRAME_BACKGROUND_PIXEL (f)
1269 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1271 if (FRAME_W32_WINDOW (f) != 0)
1273 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1274 FRAME_BACKGROUND_PIXEL (f));
1276 update_face_from_frame_parameter (f, Qbackground_color, arg);
1278 if (FRAME_VISIBLE_P (f))
1279 redraw_frame (f);
1283 void
1284 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1286 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1287 int count;
1288 int mask_color;
1290 if (!EQ (Qnil, arg))
1291 f->output_data.w32->mouse_pixel
1292 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1293 mask_color = FRAME_BACKGROUND_PIXEL (f);
1295 /* Don't let pointers be invisible. */
1296 if (mask_color == f->output_data.w32->mouse_pixel
1297 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1298 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1300 #if 0 /* TODO : Mouse cursor customization. */
1301 block_input ();
1303 /* It's not okay to crash if the user selects a screwy cursor. */
1304 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1306 if (!EQ (Qnil, Vx_pointer_shape))
1308 CHECK_NUMBER (Vx_pointer_shape);
1309 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1311 else
1312 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1313 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1315 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1317 CHECK_NUMBER (Vx_nontext_pointer_shape);
1318 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1319 XINT (Vx_nontext_pointer_shape));
1321 else
1322 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1323 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1325 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1327 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1328 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1329 XINT (Vx_hourglass_pointer_shape));
1331 else
1332 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1333 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1335 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1336 if (!EQ (Qnil, Vx_mode_pointer_shape))
1338 CHECK_NUMBER (Vx_mode_pointer_shape);
1339 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1340 XINT (Vx_mode_pointer_shape));
1342 else
1343 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1344 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1346 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1348 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1349 hand_cursor
1350 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1351 XINT (Vx_sensitive_text_pointer_shape));
1353 else
1354 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1356 if (!NILP (Vx_window_horizontal_drag_shape))
1358 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1359 horizontal_drag_cursor
1360 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1361 XINT (Vx_window_horizontal_drag_shape));
1363 else
1364 horizontal_drag_cursor
1365 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1367 if (!NILP (Vx_window_vertical_drag_shape))
1369 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1370 vertical_drag_cursor
1371 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1372 XINT (Vx_window_vertical_drag_shape));
1374 else
1375 vertical_drag_cursor
1376 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1378 /* Check and report errors with the above calls. */
1379 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1380 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1383 XColor fore_color, back_color;
1385 fore_color.pixel = f->output_data.w32->mouse_pixel;
1386 back_color.pixel = mask_color;
1387 XQueryColor (FRAME_W32_DISPLAY (f),
1388 DefaultColormap (FRAME_W32_DISPLAY (f),
1389 DefaultScreen (FRAME_W32_DISPLAY (f))),
1390 &fore_color);
1391 XQueryColor (FRAME_W32_DISPLAY (f),
1392 DefaultColormap (FRAME_W32_DISPLAY (f),
1393 DefaultScreen (FRAME_W32_DISPLAY (f))),
1394 &back_color);
1395 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1396 &fore_color, &back_color);
1397 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1398 &fore_color, &back_color);
1399 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1400 &fore_color, &back_color);
1401 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1402 &fore_color, &back_color);
1403 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1404 &fore_color, &back_color);
1407 if (FRAME_W32_WINDOW (f) != 0)
1408 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1410 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1411 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1412 f->output_data.w32->text_cursor = cursor;
1414 if (nontext_cursor != f->output_data.w32->nontext_cursor
1415 && f->output_data.w32->nontext_cursor != 0)
1416 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1417 f->output_data.w32->nontext_cursor = nontext_cursor;
1419 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1420 && f->output_data.w32->hourglass_cursor != 0)
1421 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1422 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1424 if (mode_cursor != f->output_data.w32->modeline_cursor
1425 && f->output_data.w32->modeline_cursor != 0)
1426 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1427 f->output_data.w32->modeline_cursor = mode_cursor;
1429 if (hand_cursor != f->output_data.w32->hand_cursor
1430 && f->output_data.w32->hand_cursor != 0)
1431 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1432 f->output_data.w32->hand_cursor = hand_cursor;
1434 XFlush (FRAME_W32_DISPLAY (f));
1435 unblock_input ();
1437 update_face_from_frame_parameter (f, Qmouse_color, arg);
1438 #endif /* TODO */
1441 void
1442 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1444 unsigned long fore_pixel, pixel;
1446 if (!NILP (Vx_cursor_fore_pixel))
1447 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1448 WHITE_PIX_DEFAULT (f));
1449 else
1450 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1452 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1454 /* Make sure that the cursor color differs from the background color. */
1455 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1457 pixel = f->output_data.w32->mouse_pixel;
1458 if (pixel == fore_pixel)
1459 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1462 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1463 f->output_data.w32->cursor_pixel = pixel;
1465 if (FRAME_W32_WINDOW (f) != 0)
1467 block_input ();
1468 /* Update frame's cursor_gc. */
1469 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1470 f->output_data.w32->cursor_gc->background = pixel;
1472 unblock_input ();
1474 if (FRAME_VISIBLE_P (f))
1476 x_update_cursor (f, 0);
1477 x_update_cursor (f, 1);
1481 update_face_from_frame_parameter (f, Qcursor_color, arg);
1484 /* Set the border-color of frame F to pixel value PIX.
1485 Note that this does not fully take effect if done before
1486 F has a window. */
1488 void
1489 x_set_border_pixel (struct frame *f, int pix)
1492 f->output_data.w32->border_pixel = pix;
1494 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1496 if (FRAME_VISIBLE_P (f))
1497 redraw_frame (f);
1501 /* Set the border-color of frame F to value described by ARG.
1502 ARG can be a string naming a color.
1503 The border-color is used for the border that is drawn by the server.
1504 Note that this does not fully take effect if done before
1505 F has a window; it must be redone when the window is created. */
1507 void
1508 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1510 int pix;
1512 CHECK_STRING (arg);
1513 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1514 x_set_border_pixel (f, pix);
1515 update_face_from_frame_parameter (f, Qborder_color, arg);
1519 void
1520 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1522 set_frame_cursor_types (f, arg);
1525 void
1526 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1528 bool result;
1530 if (NILP (arg) && NILP (oldval))
1531 return;
1533 if (STRINGP (arg) && STRINGP (oldval)
1534 && EQ (Fstring_equal (oldval, arg), Qt))
1535 return;
1537 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1538 return;
1540 block_input ();
1542 result = x_bitmap_icon (f, arg);
1543 if (result)
1545 unblock_input ();
1546 error ("No icon window available");
1549 unblock_input ();
1552 void
1553 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1555 if (STRINGP (arg))
1557 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1558 return;
1560 else if (!NILP (arg) || NILP (oldval))
1561 return;
1563 fset_icon_name (f, arg);
1565 #if 0
1566 if (f->output_data.w32->icon_bitmap != 0)
1567 return;
1569 block_input ();
1571 result = x_text_icon (f,
1572 SSDATA ((!NILP (f->icon_name)
1573 ? f->icon_name
1574 : !NILP (f->title)
1575 ? f->title
1576 : f->name)));
1578 if (result)
1580 unblock_input ();
1581 error ("No icon window available");
1584 /* If the window was unmapped (and its icon was mapped),
1585 the new icon is not mapped, so map the window in its stead. */
1586 if (FRAME_VISIBLE_P (f))
1588 #ifdef USE_X_TOOLKIT
1589 XtPopup (f->output_data.w32->widget, XtGrabNone);
1590 #endif
1591 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1594 XFlush (FRAME_W32_DISPLAY (f));
1595 unblock_input ();
1596 #endif
1599 void
1600 x_clear_under_internal_border (struct frame *f)
1602 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1604 /* Clear border if it's larger than before. */
1605 if (border != 0)
1607 HDC hdc = get_frame_dc (f);
1608 int width = FRAME_PIXEL_WIDTH (f);
1609 int height = FRAME_PIXEL_HEIGHT (f);
1611 block_input ();
1612 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1613 w32_clear_area (f, hdc, 0, 0, border, height);
1614 w32_clear_area (f, hdc, width - border, 0, border, height);
1615 w32_clear_area (f, hdc, 0, height - border, width, border);
1616 release_frame_dc (f, hdc);
1617 unblock_input ();
1622 void
1623 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1625 int border;
1627 CHECK_TYPE_RANGED_INTEGER (int, arg);
1628 border = max (XINT (arg), 0);
1630 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1632 FRAME_INTERNAL_BORDER_WIDTH (f) = border;
1634 if (FRAME_X_WINDOW (f) != 0)
1636 adjust_frame_size (f, -1, -1, 3, false, Qinternal_border_width);
1638 if (FRAME_VISIBLE_P (f))
1639 x_clear_under_internal_border (f);
1645 void
1646 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1648 int nlines;
1650 /* Right now, menu bars don't work properly in minibuf-only frames;
1651 most of the commands try to apply themselves to the minibuffer
1652 frame itself, and get an error because you can't switch buffers
1653 in or split the minibuffer window. */
1654 if (FRAME_MINIBUF_ONLY_P (f))
1655 return;
1657 if (INTEGERP (value))
1658 nlines = XINT (value);
1659 else
1660 nlines = 0;
1662 FRAME_MENU_BAR_LINES (f) = 0;
1663 FRAME_MENU_BAR_HEIGHT (f) = 0;
1664 if (nlines)
1666 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1667 windows_or_buffers_changed = 23;
1669 else
1671 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1672 free_frame_menubar (f);
1673 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1675 /* Adjust the frame size so that the client (text) dimensions
1676 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1677 set correctly. Note that we resize twice: The first time upon
1678 a request from the window manager who wants to keep the height
1679 of the outer rectangle (including decorations) unchanged, and a
1680 second time because we want to keep the height of the inner
1681 rectangle (without the decorations unchanged). */
1682 adjust_frame_size (f, -1, -1, 2, true, Qmenu_bar_lines);
1684 /* Not sure whether this is needed. */
1685 x_clear_under_internal_border (f);
1690 /* Set the number of lines used for the tool bar of frame F to VALUE.
1691 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1692 the old number of tool bar lines (and is unused). This function may
1693 change the height of all windows on frame F to match the new tool bar
1694 height. By design, the frame's height doesn't change (but maybe it
1695 should if we don't get enough space otherwise). */
1697 void
1698 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1700 int nlines;
1702 /* Treat tool bars like menu bars. */
1703 if (FRAME_MINIBUF_ONLY_P (f))
1704 return;
1706 /* Use VALUE only if an integer >= 0. */
1707 if (INTEGERP (value) && XINT (value) >= 0)
1708 nlines = XFASTINT (value);
1709 else
1710 nlines = 0;
1712 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1716 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1717 void
1718 x_change_tool_bar_height (struct frame *f, int height)
1720 Lisp_Object frame;
1721 int unit = FRAME_LINE_HEIGHT (f);
1722 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1723 int lines = (height + unit - 1) / unit;
1724 int old_text_height = FRAME_TEXT_HEIGHT (f);
1725 Lisp_Object fullscreen;
1727 /* Make sure we redisplay all windows in this frame. */
1728 windows_or_buffers_changed = 23;
1730 /* Recalculate tool bar and frame text sizes. */
1731 FRAME_TOOL_BAR_HEIGHT (f) = height;
1732 FRAME_TOOL_BAR_LINES (f) = lines;
1733 /* Store `tool-bar-lines' and `height' frame parameters. */
1734 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1735 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1737 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1739 clear_frame (f);
1740 clear_current_matrices (f);
1743 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1744 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1746 /* Recalculate toolbar height. */
1747 f->n_tool_bar_rows = 0;
1749 adjust_frame_size (f, -1, -1,
1750 ((!f->tool_bar_redisplayed_once
1751 && (NILP (fullscreen =
1752 get_frame_param (f, Qfullscreen))
1753 || EQ (fullscreen, Qfullwidth))) ? 1
1754 : (old_height == 0 || height == 0) ? 2
1755 : 4),
1756 false, Qtool_bar_lines);
1758 /* adjust_frame_size might not have done anything, garbage frame
1759 here. */
1760 adjust_frame_glyphs (f);
1761 SET_FRAME_GARBAGED (f);
1762 if (FRAME_X_WINDOW (f))
1763 x_clear_under_internal_border (f);
1766 static void
1767 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1769 if (FRAME_W32_WINDOW (f))
1771 block_input ();
1772 #ifdef __CYGWIN__
1773 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1774 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1775 #else
1776 /* The frame's title many times shows the name of the file
1777 visited in the selected window's buffer, so it makes sense to
1778 support non-ASCII characters outside of the current system
1779 codepage in the title. */
1780 if (w32_unicode_filenames)
1782 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1783 wchar_t *title_w;
1784 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1785 -1, NULL, 0);
1787 if (tlen > 0)
1789 /* Windows truncates the title text beyond what fits on
1790 a single line, so we can limit the length to some
1791 reasonably large value, and use alloca. */
1792 if (tlen > 10000)
1793 tlen = 10000;
1794 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1795 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1796 title_w, tlen);
1797 title_w[tlen] = L'\0';
1798 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1800 else /* Conversion to UTF-16 failed, so we punt. */
1801 SetWindowTextA (FRAME_W32_WINDOW (f),
1802 SSDATA (ENCODE_SYSTEM (name)));
1804 else
1805 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1806 #endif
1807 unblock_input ();
1811 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1812 w32_id_name.
1814 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1815 name; if NAME is a string, set F's name to NAME and set
1816 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1818 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1819 suggesting a new name, which lisp code should override; if
1820 F->explicit_name is set, ignore the new name; otherwise, set it. */
1822 void
1823 x_set_name (struct frame *f, Lisp_Object name, bool explicit)
1825 /* Make sure that requests from lisp code override requests from
1826 Emacs redisplay code. */
1827 if (explicit)
1829 /* If we're switching from explicit to implicit, we had better
1830 update the mode lines and thereby update the title. */
1831 if (f->explicit_name && NILP (name))
1832 update_mode_lines = 25;
1834 f->explicit_name = ! NILP (name);
1836 else if (f->explicit_name)
1837 return;
1839 /* If NAME is nil, set the name to the w32_id_name. */
1840 if (NILP (name))
1842 /* Check for no change needed in this very common case
1843 before we do any consing. */
1844 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1845 SDATA (f->name)))
1846 return;
1847 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1849 else
1850 CHECK_STRING (name);
1852 /* Don't change the name if it's already NAME. */
1853 if (! NILP (Fstring_equal (name, f->name)))
1854 return;
1856 fset_name (f, name);
1858 /* For setting the frame title, the title parameter should override
1859 the name parameter. */
1860 if (! NILP (f->title))
1861 name = f->title;
1863 w32_set_title_bar_text (f, name);
1866 /* This function should be called when the user's lisp code has
1867 specified a name for the frame; the name will override any set by the
1868 redisplay code. */
1869 void
1870 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1872 x_set_name (f, arg, true);
1875 /* This function should be called by Emacs redisplay code to set the
1876 name; names set this way will never override names set by the user's
1877 lisp code. */
1878 void
1879 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1881 x_set_name (f, arg, false);
1884 /* Change the title of frame F to NAME.
1885 If NAME is nil, use the frame name as the title. */
1887 void
1888 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1890 /* Don't change the title if it's already NAME. */
1891 if (EQ (name, f->title))
1892 return;
1894 update_mode_lines = 26;
1896 fset_title (f, name);
1898 if (NILP (name))
1899 name = f->name;
1901 w32_set_title_bar_text (f, name);
1904 void
1905 x_set_scroll_bar_default_width (struct frame *f)
1907 int unit = FRAME_COLUMN_WIDTH (f);
1909 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1910 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1911 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1915 void
1916 x_set_scroll_bar_default_height (struct frame *f)
1918 int unit = FRAME_LINE_HEIGHT (f);
1920 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
1921 FRAME_CONFIG_SCROLL_BAR_LINES (f)
1922 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
1925 /* Subroutines for creating a frame. */
1927 Cursor
1928 w32_load_cursor (LPCTSTR name)
1930 /* Try first to load cursor from application resource. */
1931 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1932 name, IMAGE_CURSOR, 0, 0,
1933 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1934 if (!cursor)
1936 /* Then try to load a shared predefined cursor. */
1937 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1938 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1940 return cursor;
1943 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1945 #define INIT_WINDOW_CLASS(WC) \
1946 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1947 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1948 (WC).cbClsExtra = 0; \
1949 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1950 (WC).hInstance = hinst; \
1951 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1952 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1953 (WC).hbrBackground = NULL; \
1954 (WC).lpszMenuName = NULL; \
1956 static BOOL
1957 w32_init_class (HINSTANCE hinst)
1959 if (w32_unicode_gui)
1961 WNDCLASSW uwc;
1962 INIT_WINDOW_CLASS(uwc);
1963 uwc.lpszClassName = L"Emacs";
1965 return RegisterClassW (&uwc);
1967 else
1969 WNDCLASS wc;
1970 INIT_WINDOW_CLASS(wc);
1971 wc.lpszClassName = EMACS_CLASS;
1973 return RegisterClassA (&wc);
1977 static HWND
1978 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
1980 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1981 /* Position and size of scroll bar. */
1982 bar->left, bar->top, bar->width, bar->height,
1983 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1986 static HWND
1987 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
1989 return CreateWindow ("SCROLLBAR", "", SBS_HORZ | WS_CHILD | WS_VISIBLE,
1990 /* Position and size of scroll bar. */
1991 bar->left, bar->top, bar->width, bar->height,
1992 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1995 static void
1996 w32_createwindow (struct frame *f, int *coords)
1998 HWND hwnd;
1999 RECT rect;
2000 int top;
2001 int left;
2003 rect.left = rect.top = 0;
2004 rect.right = FRAME_PIXEL_WIDTH (f);
2005 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2007 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2008 FRAME_EXTERNAL_MENU_BAR (f));
2010 /* Do first time app init */
2012 w32_init_class (hinst);
2014 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2016 left = f->left_pos;
2017 top = f->top_pos;
2019 else
2021 left = coords[0];
2022 top = coords[1];
2025 FRAME_W32_WINDOW (f) = hwnd
2026 = CreateWindow (EMACS_CLASS,
2027 f->namebuf,
2028 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2029 left, top,
2030 rect.right - rect.left, rect.bottom - rect.top,
2031 NULL,
2032 NULL,
2033 hinst,
2034 NULL);
2036 if (hwnd)
2038 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2039 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2040 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2041 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2042 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2043 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2045 /* Enable drag-n-drop. */
2046 DragAcceptFiles (hwnd, TRUE);
2048 /* Do this to discard the default setting specified by our parent. */
2049 ShowWindow (hwnd, SW_HIDE);
2051 /* Update frame positions. */
2052 GetWindowRect (hwnd, &rect);
2053 f->left_pos = rect.left;
2054 f->top_pos = rect.top;
2058 static void
2059 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2061 wmsg->msg.hwnd = hwnd;
2062 wmsg->msg.message = msg;
2063 wmsg->msg.wParam = wParam;
2064 wmsg->msg.lParam = lParam;
2065 wmsg->msg.time = GetMessageTime ();
2067 post_msg (wmsg);
2070 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2071 between left and right keys as advertised. We test for this
2072 support dynamically, and set a flag when the support is absent. If
2073 absent, we keep track of the left and right control and alt keys
2074 ourselves. This is particularly necessary on keyboards that rely
2075 upon the AltGr key, which is represented as having the left control
2076 and right alt keys pressed. For these keyboards, we need to know
2077 when the left alt key has been pressed in addition to the AltGr key
2078 so that we can properly support M-AltGr-key sequences (such as M-@
2079 on Swedish keyboards). */
2081 #define EMACS_LCONTROL 0
2082 #define EMACS_RCONTROL 1
2083 #define EMACS_LMENU 2
2084 #define EMACS_RMENU 3
2086 static int modifiers[4];
2087 static int modifiers_recorded;
2088 static int modifier_key_support_tested;
2090 static void
2091 test_modifier_support (unsigned int wparam)
2093 unsigned int l, r;
2095 if (wparam != VK_CONTROL && wparam != VK_MENU)
2096 return;
2097 if (wparam == VK_CONTROL)
2099 l = VK_LCONTROL;
2100 r = VK_RCONTROL;
2102 else
2104 l = VK_LMENU;
2105 r = VK_RMENU;
2107 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2108 modifiers_recorded = 1;
2109 else
2110 modifiers_recorded = 0;
2111 modifier_key_support_tested = 1;
2114 static void
2115 record_keydown (unsigned int wparam, unsigned int lparam)
2117 int i;
2119 if (!modifier_key_support_tested)
2120 test_modifier_support (wparam);
2122 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2123 return;
2125 if (wparam == VK_CONTROL)
2126 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2127 else
2128 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2130 modifiers[i] = 1;
2133 static void
2134 record_keyup (unsigned int wparam, unsigned int lparam)
2136 int i;
2138 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2139 return;
2141 if (wparam == VK_CONTROL)
2142 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2143 else
2144 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2146 modifiers[i] = 0;
2149 /* Emacs can lose focus while a modifier key has been pressed. When
2150 it regains focus, be conservative and clear all modifiers since
2151 we cannot reconstruct the left and right modifier state. */
2152 static void
2153 reset_modifiers (void)
2155 SHORT ctrl, alt;
2157 if (GetFocus () == NULL)
2158 /* Emacs doesn't have keyboard focus. Do nothing. */
2159 return;
2161 ctrl = GetAsyncKeyState (VK_CONTROL);
2162 alt = GetAsyncKeyState (VK_MENU);
2164 if (!(ctrl & 0x08000))
2165 /* Clear any recorded control modifier state. */
2166 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2168 if (!(alt & 0x08000))
2169 /* Clear any recorded alt modifier state. */
2170 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2172 /* Update the state of all modifier keys, because modifiers used in
2173 hot-key combinations can get stuck on if Emacs loses focus as a
2174 result of a hot-key being pressed. */
2176 BYTE keystate[256];
2178 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2180 memset (keystate, 0, sizeof (keystate));
2181 GetKeyboardState (keystate);
2182 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2183 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2184 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2185 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2186 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2187 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2188 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2189 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2190 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2191 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2192 SetKeyboardState (keystate);
2196 /* Synchronize modifier state with what is reported with the current
2197 keystroke. Even if we cannot distinguish between left and right
2198 modifier keys, we know that, if no modifiers are set, then neither
2199 the left or right modifier should be set. */
2200 static void
2201 sync_modifiers (void)
2203 if (!modifiers_recorded)
2204 return;
2206 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2207 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2209 if (!(GetKeyState (VK_MENU) & 0x8000))
2210 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2213 static int
2214 modifier_set (int vkey)
2216 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2217 toggle keys is not an omission! If you want to add it, you will
2218 have to make changes in the default sub-case of the WM_KEYDOWN
2219 switch, because if the NUMLOCK modifier is set, the code there
2220 will directly convert any key that looks like an ASCII letter,
2221 and also downcase those that look like upper-case ASCII. */
2222 if (vkey == VK_CAPITAL)
2224 if (NILP (Vw32_enable_caps_lock))
2225 return 0;
2226 else
2227 return (GetKeyState (vkey) & 0x1);
2229 if (vkey == VK_SCROLL)
2231 if (NILP (Vw32_scroll_lock_modifier)
2232 /* w32-scroll-lock-modifier can be any non-nil value that is
2233 not one of the modifiers, in which case it shall be ignored. */
2234 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2235 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2236 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2237 || EQ (Vw32_scroll_lock_modifier, Qalt)
2238 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2239 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2240 return 0;
2241 else
2242 return (GetKeyState (vkey) & 0x1);
2245 if (!modifiers_recorded)
2246 return (GetKeyState (vkey) & 0x8000);
2248 switch (vkey)
2250 case VK_LCONTROL:
2251 return modifiers[EMACS_LCONTROL];
2252 case VK_RCONTROL:
2253 return modifiers[EMACS_RCONTROL];
2254 case VK_LMENU:
2255 return modifiers[EMACS_LMENU];
2256 case VK_RMENU:
2257 return modifiers[EMACS_RMENU];
2259 return (GetKeyState (vkey) & 0x8000);
2262 /* Convert between the modifier bits W32 uses and the modifier bits
2263 Emacs uses. */
2265 unsigned int
2266 w32_key_to_modifier (int key)
2268 Lisp_Object key_mapping;
2270 switch (key)
2272 case VK_LWIN:
2273 key_mapping = Vw32_lwindow_modifier;
2274 break;
2275 case VK_RWIN:
2276 key_mapping = Vw32_rwindow_modifier;
2277 break;
2278 case VK_APPS:
2279 key_mapping = Vw32_apps_modifier;
2280 break;
2281 case VK_SCROLL:
2282 key_mapping = Vw32_scroll_lock_modifier;
2283 break;
2284 default:
2285 key_mapping = Qnil;
2288 /* NB. This code runs in the input thread, asynchronously to the lisp
2289 thread, so we must be careful to ensure access to lisp data is
2290 thread-safe. The following code is safe because the modifier
2291 variable values are updated atomically from lisp and symbols are
2292 not relocated by GC. Also, we don't have to worry about seeing GC
2293 markbits here. */
2294 if (EQ (key_mapping, Qhyper))
2295 return hyper_modifier;
2296 if (EQ (key_mapping, Qsuper))
2297 return super_modifier;
2298 if (EQ (key_mapping, Qmeta))
2299 return meta_modifier;
2300 if (EQ (key_mapping, Qalt))
2301 return alt_modifier;
2302 if (EQ (key_mapping, Qctrl))
2303 return ctrl_modifier;
2304 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2305 return ctrl_modifier;
2306 if (EQ (key_mapping, Qshift))
2307 return shift_modifier;
2309 /* Don't generate any modifier if not explicitly requested. */
2310 return 0;
2313 static unsigned int
2314 w32_get_modifiers (void)
2316 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2317 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2318 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2319 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2320 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2321 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2322 (modifier_set (VK_MENU) ?
2323 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2326 /* We map the VK_* modifiers into console modifier constants
2327 so that we can use the same routines to handle both console
2328 and window input. */
2330 static int
2331 construct_console_modifiers (void)
2333 int mods;
2335 mods = 0;
2336 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2337 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2338 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2339 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2340 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2341 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2342 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2343 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2344 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2345 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2346 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2348 return mods;
2351 static int
2352 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2354 int mods;
2356 /* Convert to emacs modifiers. */
2357 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2359 return mods;
2362 unsigned int
2363 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2365 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2366 return virt_key;
2368 if (virt_key == VK_RETURN)
2369 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2371 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2372 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2374 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2375 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2377 if (virt_key == VK_CLEAR)
2378 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2380 return virt_key;
2383 /* List of special key combinations which w32 would normally capture,
2384 but Emacs should grab instead. Not directly visible to lisp, to
2385 simplify synchronization. Each item is an integer encoding a virtual
2386 key code and modifier combination to capture. */
2387 static Lisp_Object w32_grabbed_keys;
2389 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2390 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2391 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2392 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2394 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2395 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2396 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2398 /* Register hot-keys for reserved key combinations when Emacs has
2399 keyboard focus, since this is the only way Emacs can receive key
2400 combinations like Alt-Tab which are used by the system. */
2402 static void
2403 register_hot_keys (HWND hwnd)
2405 Lisp_Object keylist;
2407 /* Use CONSP, since we are called asynchronously. */
2408 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2410 Lisp_Object key = XCAR (keylist);
2412 /* Deleted entries get set to nil. */
2413 if (!INTEGERP (key))
2414 continue;
2416 RegisterHotKey (hwnd, HOTKEY_ID (key),
2417 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2421 static void
2422 unregister_hot_keys (HWND hwnd)
2424 Lisp_Object keylist;
2426 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2428 Lisp_Object key = XCAR (keylist);
2430 if (!INTEGERP (key))
2431 continue;
2433 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2437 #if EMACSDEBUG
2438 const char*
2439 w32_name_of_message (UINT msg)
2441 unsigned i;
2442 static char buf[64];
2443 static const struct {
2444 UINT msg;
2445 const char* name;
2446 } msgnames[] = {
2447 #define M(msg) { msg, # msg }
2448 M (WM_PAINT),
2449 M (WM_TIMER),
2450 M (WM_USER),
2451 M (WM_MOUSEMOVE),
2452 M (WM_LBUTTONUP),
2453 M (WM_KEYDOWN),
2454 M (WM_EMACS_KILL),
2455 M (WM_EMACS_CREATEWINDOW),
2456 M (WM_EMACS_DONE),
2457 M (WM_EMACS_CREATEVSCROLLBAR),
2458 M (WM_EMACS_CREATEHSCROLLBAR),
2459 M (WM_EMACS_SHOWWINDOW),
2460 M (WM_EMACS_SETWINDOWPOS),
2461 M (WM_EMACS_DESTROYWINDOW),
2462 M (WM_EMACS_TRACKPOPUPMENU),
2463 M (WM_EMACS_SETFOCUS),
2464 M (WM_EMACS_SETFOREGROUND),
2465 M (WM_EMACS_SETLOCALE),
2466 M (WM_EMACS_SETKEYBOARDLAYOUT),
2467 M (WM_EMACS_REGISTER_HOT_KEY),
2468 M (WM_EMACS_UNREGISTER_HOT_KEY),
2469 M (WM_EMACS_TOGGLE_LOCK_KEY),
2470 M (WM_EMACS_TRACK_CARET),
2471 M (WM_EMACS_DESTROY_CARET),
2472 M (WM_EMACS_SHOW_CARET),
2473 M (WM_EMACS_HIDE_CARET),
2474 M (WM_EMACS_SETCURSOR),
2475 M (WM_EMACS_SHOWCURSOR),
2476 M (WM_EMACS_PAINT),
2477 M (WM_CHAR),
2478 #undef M
2479 { 0, 0 }
2482 for (i = 0; msgnames[i].name; ++i)
2483 if (msgnames[i].msg == msg)
2484 return msgnames[i].name;
2486 sprintf (buf, "message 0x%04x", (unsigned)msg);
2487 return buf;
2489 #endif /* EMACSDEBUG */
2491 /* Here's an overview of how Emacs input works in GUI sessions on
2492 MS-Windows. (For description of non-GUI input, see the commentary
2493 before w32_console_read_socket in w32inevt.c.)
2495 System messages are read and processed by w32_msg_pump below. This
2496 function runs in a separate thread. It handles a small number of
2497 custom WM_EMACS_* messages (posted by the main thread, look for
2498 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2499 is the main window procedure for the entire Emacs application.
2501 w32_wnd_proc also runs in the same separate input thread. It
2502 handles some messages, mostly those that need GDI calls, by itself.
2503 For the others, it calls my_post_msg, which inserts the messages
2504 into the input queue serviced by w32_read_socket.
2506 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2507 called synchronously from keyboard.c when it is known or suspected
2508 that some input is available. w32_read_socket either handles
2509 messages immediately, or converts them into Emacs input events and
2510 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2511 them and process them when read_char and its callers require
2512 input.
2514 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2515 select(2) takes the place of w32_read_socket.
2519 /* Main message dispatch loop. */
2521 static void
2522 w32_msg_pump (deferred_msg * msg_buf)
2524 MSG msg;
2525 WPARAM result;
2526 HWND focus_window;
2528 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2530 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2533 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2534 /* w32_name_of_message (msg.message), msg.time)); */
2536 if (msg.hwnd == NULL)
2538 switch (msg.message)
2540 case WM_NULL:
2541 /* Produced by complete_deferred_msg; just ignore. */
2542 break;
2543 case WM_EMACS_CREATEWINDOW:
2544 /* Initialize COM for this window. Even though we don't use it,
2545 some third party shell extensions can cause it to be used in
2546 system dialogs, which causes a crash if it is not initialized.
2547 This is a known bug in Windows, which was fixed long ago, but
2548 the patch for XP is not publicly available until XP SP3,
2549 and older versions will never be patched. */
2550 CoInitialize (NULL);
2551 w32_createwindow ((struct frame *) msg.wParam,
2552 (int *) msg.lParam);
2553 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2554 emacs_abort ();
2555 break;
2556 case WM_EMACS_SETLOCALE:
2557 SetThreadLocale (msg.wParam);
2558 /* Reply is not expected. */
2559 break;
2560 case WM_EMACS_SETKEYBOARDLAYOUT:
2561 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2562 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2563 result, 0))
2564 emacs_abort ();
2565 break;
2566 case WM_EMACS_REGISTER_HOT_KEY:
2567 focus_window = GetFocus ();
2568 if (focus_window != NULL)
2569 RegisterHotKey (focus_window,
2570 RAW_HOTKEY_ID (msg.wParam),
2571 RAW_HOTKEY_MODIFIERS (msg.wParam),
2572 RAW_HOTKEY_VK_CODE (msg.wParam));
2573 /* Reply is not expected. */
2574 break;
2575 case WM_EMACS_UNREGISTER_HOT_KEY:
2576 focus_window = GetFocus ();
2577 if (focus_window != NULL)
2578 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2579 /* Mark item as erased. NB: this code must be
2580 thread-safe. The next line is okay because the cons
2581 cell is never made into garbage and is not relocated by
2582 GC. */
2583 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
2584 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2585 emacs_abort ();
2586 break;
2587 case WM_EMACS_TOGGLE_LOCK_KEY:
2589 int vk_code = (int) msg.wParam;
2590 int cur_state = (GetKeyState (vk_code) & 1);
2591 int new_state = msg.lParam;
2593 if (new_state == -1
2594 || ((new_state & 1) != cur_state))
2596 one_w32_display_info.faked_key = vk_code;
2598 keybd_event ((BYTE) vk_code,
2599 (BYTE) MapVirtualKey (vk_code, 0),
2600 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2601 keybd_event ((BYTE) vk_code,
2602 (BYTE) MapVirtualKey (vk_code, 0),
2603 KEYEVENTF_EXTENDEDKEY | 0, 0);
2604 keybd_event ((BYTE) vk_code,
2605 (BYTE) MapVirtualKey (vk_code, 0),
2606 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2607 cur_state = !cur_state;
2609 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2610 cur_state, 0))
2611 emacs_abort ();
2613 break;
2614 #ifdef MSG_DEBUG
2615 /* Broadcast messages make it here, so you need to be looking
2616 for something in particular for this to be useful. */
2617 default:
2618 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2619 #endif
2622 else
2624 if (w32_unicode_gui)
2625 DispatchMessageW (&msg);
2626 else
2627 DispatchMessageA (&msg);
2630 /* Exit nested loop when our deferred message has completed. */
2631 if (msg_buf->completed)
2632 break;
2636 deferred_msg * deferred_msg_head;
2638 static deferred_msg *
2639 find_deferred_msg (HWND hwnd, UINT msg)
2641 deferred_msg * item;
2643 /* Don't actually need synchronization for read access, since
2644 modification of single pointer is always atomic. */
2645 /* enter_crit (); */
2647 for (item = deferred_msg_head; item != NULL; item = item->next)
2648 if (item->w32msg.msg.hwnd == hwnd
2649 && item->w32msg.msg.message == msg)
2650 break;
2652 /* leave_crit (); */
2654 return item;
2657 static LRESULT
2658 send_deferred_msg (deferred_msg * msg_buf,
2659 HWND hwnd,
2660 UINT msg,
2661 WPARAM wParam,
2662 LPARAM lParam)
2664 /* Only input thread can send deferred messages. */
2665 if (GetCurrentThreadId () != dwWindowsThreadId)
2666 emacs_abort ();
2668 /* It is an error to send a message that is already deferred. */
2669 if (find_deferred_msg (hwnd, msg) != NULL)
2670 emacs_abort ();
2672 /* Enforced synchronization is not needed because this is the only
2673 function that alters deferred_msg_head, and the following critical
2674 section is guaranteed to only be serially reentered (since only the
2675 input thread can call us). */
2677 /* enter_crit (); */
2679 msg_buf->completed = 0;
2680 msg_buf->next = deferred_msg_head;
2681 deferred_msg_head = msg_buf;
2682 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2684 /* leave_crit (); */
2686 /* Start a new nested message loop to process other messages until
2687 this one is completed. */
2688 w32_msg_pump (msg_buf);
2690 deferred_msg_head = msg_buf->next;
2692 return msg_buf->result;
2695 void
2696 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2698 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2700 if (msg_buf == NULL)
2701 /* Message may have been canceled, so don't abort. */
2702 return;
2704 msg_buf->result = result;
2705 msg_buf->completed = 1;
2707 /* Ensure input thread is woken so it notices the completion. */
2708 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2711 static void
2712 cancel_all_deferred_msgs (void)
2714 deferred_msg * item;
2716 /* Don't actually need synchronization for read access, since
2717 modification of single pointer is always atomic. */
2718 /* enter_crit (); */
2720 for (item = deferred_msg_head; item != NULL; item = item->next)
2722 item->result = 0;
2723 item->completed = 1;
2726 /* leave_crit (); */
2728 /* Ensure input thread is woken so it notices the completion. */
2729 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2732 DWORD WINAPI
2733 w32_msg_worker (void *arg)
2735 MSG msg;
2736 deferred_msg dummy_buf;
2738 /* Ensure our message queue is created */
2740 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2742 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2743 emacs_abort ();
2745 memset (&dummy_buf, 0, sizeof (dummy_buf));
2746 dummy_buf.w32msg.msg.hwnd = NULL;
2747 dummy_buf.w32msg.msg.message = WM_NULL;
2749 /* This is the initial message loop which should only exit when the
2750 application quits. */
2751 w32_msg_pump (&dummy_buf);
2753 return 0;
2756 static void
2757 signal_user_input (void)
2759 /* Interrupt any lisp that wants to be interrupted by input. */
2760 if (!NILP (Vthrow_on_input))
2762 Vquit_flag = Vthrow_on_input;
2763 /* Doing a QUIT from this thread is a bad idea, since this
2764 unwinds the stack of the Lisp thread, and the Windows runtime
2765 rightfully barfs. Disabled. */
2766 #if 0
2767 /* If we're inside a function that wants immediate quits,
2768 do it now. */
2769 if (immediate_quit && NILP (Vinhibit_quit))
2771 immediate_quit = 0;
2772 QUIT;
2774 #endif
2779 static void
2780 post_character_message (HWND hwnd, UINT msg,
2781 WPARAM wParam, LPARAM lParam,
2782 DWORD modifiers)
2784 W32Msg wmsg;
2786 wmsg.dwModifiers = modifiers;
2788 /* Detect quit_char and set quit-flag directly. Note that we
2789 still need to post a message to ensure the main thread will be
2790 woken up if blocked in sys_select, but we do NOT want to post
2791 the quit_char message itself (because it will usually be as if
2792 the user had typed quit_char twice). Instead, we post a dummy
2793 message that has no particular effect. */
2795 int c = wParam;
2796 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2797 c = make_ctrl_char (c) & 0377;
2798 if (c == quit_char
2799 || (wmsg.dwModifiers == 0
2800 && w32_quit_key && wParam == w32_quit_key))
2802 Vquit_flag = Qt;
2804 /* The choice of message is somewhat arbitrary, as long as
2805 the main thread handler just ignores it. */
2806 msg = WM_NULL;
2808 /* Interrupt any blocking system calls. */
2809 signal_quit ();
2811 /* As a safety precaution, forcibly complete any deferred
2812 messages. This is a kludge, but I don't see any particularly
2813 clean way to handle the situation where a deferred message is
2814 "dropped" in the lisp thread, and will thus never be
2815 completed, eg. by the user trying to activate the menubar
2816 when the lisp thread is busy, and then typing C-g when the
2817 menubar doesn't open promptly (with the result that the
2818 menubar never responds at all because the deferred
2819 WM_INITMENU message is never completed). Another problem
2820 situation is when the lisp thread calls SendMessage (to send
2821 a window manager command) when a message has been deferred;
2822 the lisp thread gets blocked indefinitely waiting for the
2823 deferred message to be completed, which itself is waiting for
2824 the lisp thread to respond.
2826 Note that we don't want to block the input thread waiting for
2827 a response from the lisp thread (although that would at least
2828 solve the deadlock problem above), because we want to be able
2829 to receive C-g to interrupt the lisp thread. */
2830 cancel_all_deferred_msgs ();
2832 else
2833 signal_user_input ();
2836 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2839 static int
2840 get_wm_chars (HWND aWnd, int *buf, int buflen, int ignore_ctrl, int ctrl,
2841 int *ctrl_cnt, int *is_dead, int vk, int exp)
2843 MSG msg;
2844 /* If doubled is at the end, ignore it. */
2845 int i = buflen, doubled = 0, code_unit;
2847 if (ctrl_cnt)
2848 *ctrl_cnt = 0;
2849 if (is_dead)
2850 *is_dead = -1;
2851 eassert(w32_unicode_gui);
2852 while (buflen
2853 /* Should be called only when w32_unicode_gui: */
2854 && PeekMessageW(&msg, aWnd, WM_KEYFIRST, WM_KEYLAST,
2855 PM_NOREMOVE | PM_NOYIELD)
2856 && (msg.message == WM_CHAR || msg.message == WM_SYSCHAR
2857 || msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR
2858 || msg.message == WM_UNICHAR))
2860 /* We extract character payload, but in this call we handle only the
2861 characters which come BEFORE the next keyup/keydown message. */
2862 int dead;
2864 GetMessageW(&msg, aWnd, msg.message, msg.message);
2865 dead = (msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR);
2866 if (is_dead)
2867 *is_dead = (dead ? msg.wParam : -1);
2868 if (dead)
2869 continue;
2870 code_unit = msg.wParam;
2871 if (doubled)
2873 /* Had surrogate. */
2874 if (msg.message == WM_UNICHAR
2875 || code_unit < 0xDC00 || code_unit > 0xDFFF)
2876 { /* Mismatched first surrogate.
2877 Pass both code units as if they were two characters. */
2878 *buf++ = doubled;
2879 if (!--buflen)
2880 return i; /* Drop the 2nd char if at the end of the buffer. */
2882 else /* see https://en.wikipedia.org/wiki/UTF-16 */
2883 code_unit = (doubled << 10) + code_unit - 0x35FDC00;
2884 doubled = 0;
2886 else if (code_unit >= 0xD800 && code_unit <= 0xDBFF)
2888 /* Handle mismatched 2nd surrogate the same as a normal character. */
2889 doubled = code_unit;
2890 continue;
2893 /* The only "fake" characters delivered by ToUnicode() or
2894 TranslateMessage() are:
2895 0x01 .. 0x1a for Ctrl-letter, Enter, Tab, Ctrl-Break, Esc, Backspace
2896 0x00 and 0x1b .. 0x1f for Control- []\@^_
2897 0x7f for Control-BackSpace
2898 0x20 for Control-Space */
2899 if (ignore_ctrl
2900 && (code_unit < 0x20 || code_unit == 0x7f
2901 || (code_unit == 0x20 && ctrl)))
2903 /* Non-character payload in a WM_CHAR
2904 (Ctrl-something pressed, see above). Ignore, and report. */
2905 if (ctrl_cnt)
2906 *ctrl_cnt++;
2907 continue;
2909 /* Traditionally, Emacs would ignore the character payload of VK_NUMPAD*
2910 keys, and would treat them later via `function-key-map'. In addition
2911 to usual 102-key NUMPAD keys, this map also treats `kp-'-variants of
2912 space, tab, enter, separator, equal. TAB and EQUAL, apparently,
2913 cannot be generated on Win-GUI branch. ENTER is already handled
2914 by the code above. According to `lispy_function_keys', kp_space is
2915 generated by not-extended VK_CLEAR. (kp-tab != VK_OEM_NEC_EQUAL!).
2917 We do similarly for backward-compatibility, but ignore only the
2918 characters restorable later by `function-key-map'. */
2919 if (code_unit < 0x7f
2920 && ((vk >= VK_NUMPAD0 && vk <= VK_DIVIDE)
2921 || (exp && ((vk >= VK_PRIOR && vk <= VK_DOWN) ||
2922 vk == VK_INSERT || vk == VK_DELETE || vk == VK_CLEAR)))
2923 && strchr("0123456789/*-+.,", code_unit))
2924 continue;
2925 *buf++ = code_unit;
2926 buflen--;
2928 return i - buflen;
2931 #ifdef DBG_WM_CHARS
2932 # define FPRINTF_WM_CHARS(ARG) fprintf ARG
2933 #else
2934 # define FPRINTF_WM_CHARS(ARG) 0
2935 #endif
2937 /* This is a heuristic only. This is supposed to track the state of the
2938 finite automaton in the language environment of Windows.
2940 However, separate windows (if with the same different language
2941 environments!) should have different values. Moreover, switching to a
2942 non-Emacs window with the same language environment, and using (dead)keys
2943 there would change the value stored in the kernel, but not this value. */
2944 static int after_deadkey = 0;
2947 deliver_wm_chars (int do_translate, HWND hwnd, UINT msg, UINT wParam,
2948 UINT lParam, int legacy_alt_meta)
2950 /* An "old style" keyboard description may assign up to 125 UTF-16 code
2951 points to a keypress.
2952 (However, the "old style" TranslateMessage() would deliver at most 16 of
2953 them.) Be on a safe side, and prepare to treat many more. */
2954 int ctrl_cnt, buf[1024], count, is_dead, after_dead = (after_deadkey != -1);
2956 /* Since the keypress processing logic of Windows has a lot of state, it
2957 is important to call TranslateMessage() for every keyup/keydown, AND
2958 do it exactly once. (The actual change of state is done by
2959 ToUnicode[Ex](), which is called by TranslateMessage(). So one can
2960 call ToUnicode[Ex]() instead.)
2962 The "usual" message pump calls TranslateMessage() for EVERY event.
2963 Emacs calls TranslateMessage() very selectively (is it needed for doing
2964 some tricky stuff with Win95??? With newer Windows, selectiveness is,
2965 most probably, not needed -- and harms a lot).
2967 So, with the usual message pump, the following call to TranslateMessage()
2968 is not needed (and is going to be VERY harmful). With Emacs' message
2969 pump, the call is needed. */
2970 if (do_translate)
2972 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
2974 windows_msg.time = GetMessageTime ();
2975 TranslateMessage (&windows_msg);
2977 count = get_wm_chars (hwnd, buf, sizeof(buf)/sizeof(*buf), 1,
2978 /* The message may have been synthesized by
2979 who knows what; be conservative. */
2980 modifier_set (VK_LCONTROL)
2981 || modifier_set (VK_RCONTROL)
2982 || modifier_set (VK_CONTROL),
2983 &ctrl_cnt, &is_dead, wParam,
2984 (lParam & 0x1000000L) != 0);
2985 if (count)
2987 W32Msg wmsg;
2988 DWORD console_modifiers = construct_console_modifiers ();
2989 int *b = buf, strip_Alt = 1, strip_ExtraMods = 1, hairy = 0;
2990 char *type_CtrlAlt = NULL;
2992 /* XXXX In fact, there may be another case when we need to do the same:
2993 What happens if the string defined in the LIGATURES has length
2994 0? Probably, we will get count==0, but the state of the finite
2995 automaton would reset to 0??? */
2996 after_deadkey = -1;
2998 /* wParam is checked when converting CapsLock to Shift; this is a clone
2999 of w32_get_key_modifiers (). */
3000 wmsg.dwModifiers = w32_kbd_mods_to_emacs (console_modifiers, wParam);
3002 /* What follows is just heuristics; the correct treatement requires
3003 non-destructive ToUnicode():
3004 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Can_an_application_on_Windows_accept_keyboard_events?_Part_IV:_application-specific_modifiers
3006 What one needs to find is:
3007 * which of the present modifiers AFFECT the resulting char(s)
3008 (so should be stripped, since their EFFECT is "already
3009 taken into account" in the string in buf), and
3010 * which modifiers are not affecting buf, so should be reported to
3011 the application for further treatment.
3013 Example: assume that we know:
3014 (A) lCtrl+rCtrl+rAlt modifiers with VK_A key produce a Latin "f"
3015 ("may be logical" in JCUKEN-flavored Russian keyboard flavors);
3016 (B) removing any of lCtrl, rCtrl, rAlt changes the produced char;
3017 (C) Win-modifier is not affecting the produced character
3018 (this is the common case: happens with all "standard" layouts).
3020 Suppose the user presses Win+lCtrl+rCtrl+rAlt modifiers with VK_A.
3021 What is the intent of the user? We need to guess the intent to decide
3022 which event to deliver to the application.
3024 This looks like a reasonable logic: since Win- modifier doesn't affect
3025 the output string, the user was pressing Win for SOME OTHER purpose.
3026 So the user wanted to generate Win-SOMETHING event. Now, what is
3027 something? If one takes the mantra that "character payload is more
3028 important than the combination of keypresses which resulted in this
3029 payload", then one should ignore lCtrl+rCtrl+rAlt, ignore VK_A, and
3030 assume that the user wanted to generate Win-f.
3032 Unfortunately, without non-destructive ToUnicode(), checking (B),(C)
3033 is out of question. So we use heuristics (hopefully, covering
3034 99.9999% of cases). */
3036 /* Another thing to watch for is a possibility to use AltGr-* and
3037 Ctrl-Alt-* with different semantic.
3039 Background: the layout defining the KLLF_ALTGR bit are treated
3040 specially by the kernel: when VK_RMENU (=rightAlt, =AltGr) is pressed
3041 (released), a press (release) of VK_LCONTROL is emulated (unless Ctrl
3042 is already down). As a result, any press/release of AltGr is seen
3043 by applications as a press/release of lCtrl AND rAlt. This is
3044 applicable, in particular, to ToUnicode[Ex](). (Keyrepeat is covered
3045 the same way!)
3047 NOTE: it IS possible to see bare rAlt even with KLLF_ALTGR; but this
3048 requires a good finger coordination: doing (physically)
3049 Down-lCtrl Down-rAlt Up-lCtrl Down-a
3050 (doing quick enough, so that key repeat of rAlt [which would
3051 generate new "fake" Down-lCtrl events] does not happens before 'a'
3052 is down) results in no "fake" events, so the application will see
3053 only rAlt down when 'a' is pressed. (However, fake Up-lCtrl WILL
3054 be generated when rAlt goes UP.)
3056 In fact, note also that KLLF_ALTGR does not prohibit construction of
3057 rCtrl-rAlt (just press them in this order!).
3059 Moreover: "traditional" layouts do not define distinct modifier-masks
3060 for VK_LMENU and VK_RMENU (same for VK_L/RCONTROL). Instead, they
3061 rely on the KLLF_ALTGR bit to make the behavior of VK_LMENU and
3062 VK_RMENU distinct. As a corollary, for such layouts, the produced
3063 character is the same for AltGr-* (=rAlt-*) and Ctrl-Alt-* (in any
3064 combination of handedness). For description of masks, see
3066 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Keyboard_input_on_Windows,_Part_I:_what_is_the_kernel_doing?
3068 By default, Emacs was using these coincidences via the following
3069 heuristics: it was treating:
3070 (*) keypresses with lCtrl-rAlt modifiers as if they are carrying
3071 ONLY the character payload (no matter what the actual keyboard
3072 was defining: if lCtrl-lAlt-b was delivering U+05df=beta, then
3073 Emacs saw [beta]; if lCtrl-lAlt-b was undefined in the layout,
3074 the keypress was completely ignored), and
3075 (*) keypresses with the other combinations of handedness of Ctrl-Alt
3076 modifiers (e.g., lCtrl-lAlt) as if they NEVER carry a character
3077 payload (so they were reported "raw": if lCtrl-lAlt-b was
3078 delivering beta, then Emacs saw event [C-A-b], and not [beta]).
3079 This worked good for "traditional" layouts: users could type both
3080 AltGr-x and Ctrl-Alt-x, and one was a character, another a bindable
3081 event.
3083 However, for layouts which deliver different characters for AltGr-x
3084 and lCtrl-lAlt-x, this scheme makes the latter character unaccessible
3085 in Emacs. While it is easy to access functionality of [C-M-x] in
3086 Emacs by other means (for example, by the `controlify' prefix, or
3087 using lCtrl-rCtrl-x, or rCtrl-rAlt-x [in this order]), missing
3088 characters cannot be reconstructed without a tedious manual work. */
3090 /* These two cases are often going to be distinguishable, since at most
3091 one of these character is defined with KBDCTRL | KBDMENU modifier
3092 bitmap. (This heuristic breaks if both lCtrl-lAlt- AND lCtrl-rAlt-
3093 are translated to modifier bitmaps distinct from KBDCTRL | KBDMENU,
3094 or in the cases when lCtrl-lAlt-* and lCtrl-rAlt-* are generally
3095 different, but lCtrl-lAlt-x and lCtrl-rAlt-x happen to deliver the
3096 same character.)
3098 So we have 2 chunks of info:
3099 (A) is it lCtrl-rAlt-, or lCtrl-lAlt, or some other combination?
3100 (B) is the delivered character defined with KBDCTRL | KBDMENU bits?
3101 Basing on (A) and (B), we should decide whether to ignore the
3102 delivered character. (Before, Emacs was completely ignoring (B), and
3103 was treating the 3-state of (A) as a bit.) This means that we have 6
3104 bits of customization.
3106 Additionally, a presence of two Ctrl down may be AltGr-rCtrl-. */
3108 /* Strip all non-Shift modifiers if:
3109 - more than one UTF-16 code point delivered (can't call VkKeyScanW ())
3110 - or the character is a result of combining with a prefix key. */
3111 if (!after_dead && count == 1 && *b < 0x10000)
3113 if (console_modifiers & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
3114 && console_modifiers & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
3116 type_CtrlAlt = "bB"; /* generic bindable Ctrl-Alt- modifiers */
3117 if (console_modifiers & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)
3118 == (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3119 /* double-Ctrl:
3120 e.g. AltGr-rCtrl on some layouts (in this order!) */
3121 type_CtrlAlt = "dD";
3122 else if (console_modifiers
3123 & (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED)
3124 == (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3125 type_CtrlAlt = "lL"; /* Ctrl-Alt- modifiers on the left */
3126 else if (!NILP (Vw32_recognize_altgr)
3127 && (console_modifiers
3128 & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
3129 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
3130 type_CtrlAlt = "gG"; /* modifiers as in AltGr */
3132 else if (wmsg.dwModifiers & (alt_modifier | meta_modifier)
3133 || (console_modifiers
3134 & (RIGHT_WIN_PRESSED | RIGHT_WIN_PRESSED
3135 | APPS_PRESSED | SCROLLLOCK_ON)))
3137 /* Pure Alt (or combination of Alt, Win, APPS, scrolllock. */
3138 type_CtrlAlt = "aA";
3140 if (type_CtrlAlt)
3142 /* Out of bound bitmap: */
3143 SHORT r = VkKeyScanW( *b ), bitmap = 0x1FF;
3145 FPRINTF_WM_CHARS((stderr, "VkKeyScanW %#06x %#04x\n", (int)r,
3146 wParam));
3147 if ((r & 0xFF) == wParam)
3148 bitmap = r>>8; /* *b is reachable via simple interface */
3149 if (*type_CtrlAlt == 'a') /* Simple Alt seen */
3151 if ((bitmap & ~1) == 0) /* 1: KBDSHIFT */
3153 /* In "traditional" layouts, Alt without Ctrl does not
3154 change the delivered character. This detects this
3155 situation; it is safe to report this as Alt-something
3156 -- as opposed to delivering the reported character
3157 without modifiers. */
3158 if (legacy_alt_meta
3159 && *b > 0x7f && ('A' <= wParam && wParam <= 'Z'))
3160 /* For backward-compatibility with older Emacsen, let
3161 this be processed by another branch below (which
3162 would convert it to Alt-Latin char via wParam). */
3163 return 0;
3165 else
3166 hairy = 1;
3168 /* Check whether the delivered character(s) is accessible via
3169 KBDCTRL | KBDALT ( | KBDSHIFT ) modifier mask (which is 7). */
3170 else if ((bitmap & ~1) != 6)
3172 /* The character is not accessible via plain Ctrl-Alt(-Shift)
3173 (which is, probably, same as AltGr) modifiers.
3174 Either it was after a prefix key, or is combined with
3175 modifier keys which we don't see, or there is an asymmetry
3176 between left-hand and right-hand modifiers, or other hairy
3177 stuff. */
3178 hairy = 1;
3180 /* The best solution is to delegate these tough (but rarely
3181 needed) choices to the user. Temporarily (???), it is
3182 implemented as C macros.
3184 Essentially, there are 3 things to do: return 0 (handle to the
3185 legacy processing code [ignoring the character payload]; keep
3186 some modifiers (so that they will be processed by the binding
3187 system [on top of the character payload]; strip modifiers [so
3188 that `self-insert' is going to be triggered with the character
3189 payload]).
3191 The default below should cover 99.9999% of cases:
3192 (a) strip Alt- in the hairy case only;
3193 (stripping = not ignoring)
3194 (l) for lAlt-lCtrl, ignore the char in simple cases only;
3195 (g) for what looks like AltGr, ignore the modifiers;
3196 (d) for what looks like lCtrl-rCtrl-Alt (probably
3197 AltGr-rCtrl), ignore the character in simple cases only;
3198 (b) for other cases of Ctrl-Alt, ignore the character in
3199 simple cases only.
3201 Essentially, in all hairy cases, and in looks-like-AltGr case,
3202 we keep the character, ignoring the modifiers. In all the
3203 other cases, we ignore the delivered character. */
3204 #define S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD "aldb"
3205 #define S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS ""
3206 if (strchr(S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD,
3207 type_CtrlAlt[hairy]))
3208 return 0;
3209 /* If in neither list, report all the modifiers we see COMBINED
3210 WITH the reported character. */
3211 if (strchr(S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS,
3212 type_CtrlAlt[hairy]))
3213 strip_ExtraMods = 0;
3216 if (strip_ExtraMods)
3217 wmsg.dwModifiers = wmsg.dwModifiers & shift_modifier;
3219 signal_user_input ();
3220 while (count--)
3222 FPRINTF_WM_CHARS((stderr, "unichar %#06x\n", *b));
3223 my_post_msg (&wmsg, hwnd, WM_UNICHAR, *b++, lParam);
3225 if (!ctrl_cnt) /* Process ALSO as ctrl */
3226 return 1;
3227 else
3228 FPRINTF_WM_CHARS((stderr, "extra ctrl char\n"));
3229 return -1;
3231 else if (is_dead >= 0)
3233 FPRINTF_WM_CHARS((stderr, "dead %#06x\n", is_dead));
3234 after_deadkey = is_dead;
3235 return 1;
3237 return 0;
3240 /* Main window procedure */
3242 static LRESULT CALLBACK
3243 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
3245 struct frame *f;
3246 struct w32_display_info *dpyinfo = &one_w32_display_info;
3247 W32Msg wmsg;
3248 int windows_translate;
3249 int key;
3251 /* Note that it is okay to call x_window_to_frame, even though we are
3252 not running in the main lisp thread, because frame deletion
3253 requires the lisp thread to synchronize with this thread. Thus, if
3254 a frame struct is returned, it can be used without concern that the
3255 lisp thread might make it disappear while we are using it.
3257 NB. Walking the frame list in this thread is safe (as long as
3258 writes of Lisp_Object slots are atomic, which they are on Windows).
3259 Although delete-frame can destructively modify the frame list while
3260 we are walking it, a garbage collection cannot occur until after
3261 delete-frame has synchronized with this thread.
3263 It is also safe to use functions that make GDI calls, such as
3264 w32_clear_rect, because these functions must obtain a DC handle
3265 from the frame struct using get_frame_dc which is thread-aware. */
3267 switch (msg)
3269 case WM_ERASEBKGND:
3270 f = x_window_to_frame (dpyinfo, hwnd);
3271 if (f)
3273 HDC hdc = get_frame_dc (f);
3274 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
3275 w32_clear_rect (f, hdc, &wmsg.rect);
3276 release_frame_dc (f, hdc);
3278 #if defined (W32_DEBUG_DISPLAY)
3279 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
3281 wmsg.rect.left, wmsg.rect.top,
3282 wmsg.rect.right, wmsg.rect.bottom));
3283 #endif /* W32_DEBUG_DISPLAY */
3285 return 1;
3286 case WM_PALETTECHANGED:
3287 /* ignore our own changes */
3288 if ((HWND)wParam != hwnd)
3290 f = x_window_to_frame (dpyinfo, hwnd);
3291 if (f)
3292 /* get_frame_dc will realize our palette and force all
3293 frames to be redrawn if needed. */
3294 release_frame_dc (f, get_frame_dc (f));
3296 return 0;
3297 case WM_PAINT:
3299 PAINTSTRUCT paintStruct;
3300 RECT update_rect;
3301 memset (&update_rect, 0, sizeof (update_rect));
3303 f = x_window_to_frame (dpyinfo, hwnd);
3304 if (f == 0)
3306 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
3307 return 0;
3310 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
3311 fails. Apparently this can happen under some
3312 circumstances. */
3313 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
3315 enter_crit ();
3316 BeginPaint (hwnd, &paintStruct);
3318 /* The rectangles returned by GetUpdateRect and BeginPaint
3319 do not always match. Play it safe by assuming both areas
3320 are invalid. */
3321 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
3323 #if defined (W32_DEBUG_DISPLAY)
3324 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
3326 wmsg.rect.left, wmsg.rect.top,
3327 wmsg.rect.right, wmsg.rect.bottom));
3328 DebPrint ((" [update region is %d,%d-%d,%d]\n",
3329 update_rect.left, update_rect.top,
3330 update_rect.right, update_rect.bottom));
3331 #endif
3332 EndPaint (hwnd, &paintStruct);
3333 leave_crit ();
3335 /* Change the message type to prevent Windows from
3336 combining WM_PAINT messages in the Lisp thread's queue,
3337 since Windows assumes that each message queue is
3338 dedicated to one frame and does not bother checking
3339 that hwnd matches before combining them. */
3340 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
3342 return 0;
3345 /* If GetUpdateRect returns 0 (meaning there is no update
3346 region), assume the whole window needs to be repainted. */
3347 GetClientRect (hwnd, &wmsg.rect);
3348 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3349 return 0;
3352 case WM_INPUTLANGCHANGE:
3353 /* Inform lisp thread of keyboard layout changes. */
3354 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3356 /* The state of the finite automaton is separate per every input
3357 language environment (so it does not change when one switches
3358 to a different window with the same environment). Moreover,
3359 the experiments show that the state is not remembered when
3360 one switches back to the pre-previous environment. */
3361 after_deadkey = -1;
3363 /* XXXX??? What follows is a COMPLETE misunderstanding of Windows! */
3365 /* Clear dead keys in the keyboard state; for simplicity only
3366 preserve modifier key states. */
3368 int i;
3369 BYTE keystate[256];
3371 GetKeyboardState (keystate);
3372 for (i = 0; i < 256; i++)
3373 if (1
3374 && i != VK_SHIFT
3375 && i != VK_LSHIFT
3376 && i != VK_RSHIFT
3377 && i != VK_CAPITAL
3378 && i != VK_NUMLOCK
3379 && i != VK_SCROLL
3380 && i != VK_CONTROL
3381 && i != VK_LCONTROL
3382 && i != VK_RCONTROL
3383 && i != VK_MENU
3384 && i != VK_LMENU
3385 && i != VK_RMENU
3386 && i != VK_LWIN
3387 && i != VK_RWIN)
3388 keystate[i] = 0;
3389 SetKeyboardState (keystate);
3391 goto dflt;
3393 case WM_HOTKEY:
3394 /* Synchronize hot keys with normal input. */
3395 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3396 return (0);
3398 case WM_KEYUP:
3399 case WM_SYSKEYUP:
3400 record_keyup (wParam, lParam);
3401 goto dflt;
3403 case WM_KEYDOWN:
3404 case WM_SYSKEYDOWN:
3405 /* Ignore keystrokes we fake ourself; see below. */
3406 if (dpyinfo->faked_key == wParam)
3408 dpyinfo->faked_key = 0;
3409 /* Make sure TranslateMessage sees them though (as long as
3410 they don't produce WM_CHAR messages). This ensures that
3411 indicator lights are toggled promptly on Windows 9x, for
3412 example. */
3413 if (wParam < 256 && lispy_function_keys[wParam])
3415 windows_translate = 1;
3416 goto translate;
3418 return 0;
3421 /* Synchronize modifiers with current keystroke. */
3422 sync_modifiers ();
3423 record_keydown (wParam, lParam);
3424 if (w32_use_fallback_wm_chars_method)
3425 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3427 windows_translate = 0;
3429 switch (wParam)
3431 case VK_LWIN:
3432 if (NILP (Vw32_pass_lwindow_to_system))
3434 /* Prevent system from acting on keyup (which opens the
3435 Start menu if no other key was pressed) by simulating a
3436 press of Space which we will ignore. */
3437 if (GetAsyncKeyState (wParam) & 1)
3439 if (NUMBERP (Vw32_phantom_key_code))
3440 key = XUINT (Vw32_phantom_key_code) & 255;
3441 else
3442 key = VK_SPACE;
3443 dpyinfo->faked_key = key;
3444 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3447 if (!NILP (Vw32_lwindow_modifier))
3448 return 0;
3449 break;
3450 case VK_RWIN:
3451 if (NILP (Vw32_pass_rwindow_to_system))
3453 if (GetAsyncKeyState (wParam) & 1)
3455 if (NUMBERP (Vw32_phantom_key_code))
3456 key = XUINT (Vw32_phantom_key_code) & 255;
3457 else
3458 key = VK_SPACE;
3459 dpyinfo->faked_key = key;
3460 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3463 if (!NILP (Vw32_rwindow_modifier))
3464 return 0;
3465 break;
3466 case VK_APPS:
3467 if (!NILP (Vw32_apps_modifier))
3468 return 0;
3469 break;
3470 case VK_MENU:
3471 if (NILP (Vw32_pass_alt_to_system))
3472 /* Prevent DefWindowProc from activating the menu bar if an
3473 Alt key is pressed and released by itself. */
3474 return 0;
3475 windows_translate = 1;
3476 break;
3477 case VK_CAPITAL:
3478 /* Decide whether to treat as modifier or function key. */
3479 if (NILP (Vw32_enable_caps_lock))
3480 goto disable_lock_key;
3481 windows_translate = 1;
3482 break;
3483 case VK_NUMLOCK:
3484 /* Decide whether to treat as modifier or function key. */
3485 if (NILP (Vw32_enable_num_lock))
3486 goto disable_lock_key;
3487 windows_translate = 1;
3488 break;
3489 case VK_SCROLL:
3490 /* Decide whether to treat as modifier or function key. */
3491 if (NILP (Vw32_scroll_lock_modifier))
3492 goto disable_lock_key;
3493 windows_translate = 1;
3494 break;
3495 disable_lock_key:
3496 /* Ensure the appropriate lock key state (and indicator light)
3497 remains in the same state. We do this by faking another
3498 press of the relevant key. Apparently, this really is the
3499 only way to toggle the state of the indicator lights. */
3500 dpyinfo->faked_key = wParam;
3501 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3502 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3503 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3504 KEYEVENTF_EXTENDEDKEY | 0, 0);
3505 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3506 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3507 /* Ensure indicator lights are updated promptly on Windows 9x
3508 (TranslateMessage apparently does this), after forwarding
3509 input event. */
3510 post_character_message (hwnd, msg, wParam, lParam,
3511 w32_get_key_modifiers (wParam, lParam));
3512 windows_translate = 1;
3513 break;
3514 case VK_CONTROL:
3515 case VK_SHIFT:
3516 case VK_PROCESSKEY: /* Generated by IME. */
3517 windows_translate = 1;
3518 break;
3519 case VK_CANCEL:
3520 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3521 which is confusing for purposes of key binding; convert
3522 VK_CANCEL events into VK_PAUSE events. */
3523 wParam = VK_PAUSE;
3524 break;
3525 case VK_PAUSE:
3526 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3527 for purposes of key binding; convert these back into
3528 VK_NUMLOCK events, at least when we want to see NumLock key
3529 presses. (Note that there is never any possibility that
3530 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3531 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3532 wParam = VK_NUMLOCK;
3533 break;
3534 default:
3535 if (w32_unicode_gui && !w32_use_fallback_wm_chars_method)
3537 /* If this event generates characters or deadkeys, do
3538 not interpret it as a "raw combination of modifiers
3539 and keysym". Hide deadkeys, and use the generated
3540 character(s) instead of the keysym. (Backward
3541 compatibility: exceptions for numpad keys generating
3542 0-9 . , / * - +, and for extra-Alt combined with a
3543 non-Latin char.)
3545 Try to not report modifiers which have effect on
3546 which character or deadkey is generated.
3548 Example (contrived): if rightAlt-? generates f (on a
3549 Cyrillic keyboard layout), and Ctrl, leftAlt do not
3550 affect the generated character, one wants to report
3551 Ctrl-leftAlt-f if the user presses
3552 Ctrl-leftAlt-rightAlt-?. */
3553 int res;
3554 #if 0
3555 /* Some of WM_CHAR may be fed to us directly, some are
3556 results of TranslateMessage(). Using 0 as the first
3557 argument (in a separate call) might help us
3558 distinguish these two cases.
3560 However, the keypress feeders would most probably
3561 expect the "standard" message pump, when
3562 TranslateMessage() is called on EVERY KeyDown/KeyUp
3563 event. So they may feed us Down-Ctrl Down-FAKE
3564 Char-o and expect us to recognize it as Ctrl-o.
3565 Using 0 as the first argument would interfere with
3566 this. */
3567 deliver_wm_chars (0, hwnd, msg, wParam, lParam, 1);
3568 #endif
3569 /* Processing the generated WM_CHAR messages *WHILE* we
3570 handle KEYDOWN/UP event is the best choice, since
3571 without any fuss, we know all 3 of: scancode, virtual
3572 keycode, and expansion. (Additionally, one knows
3573 boundaries of expansion of different keypresses.) */
3574 res = deliver_wm_chars (1, hwnd, msg, wParam, lParam, 1);
3575 windows_translate = -( res != 0 );
3576 if (res > 0) /* Bound to character(s) or a deadkey */
3577 break;
3578 /* deliver_wm_chars may make some branches after this vestigal. */
3580 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3581 /* If not defined as a function key, change it to a WM_CHAR message. */
3582 if (wParam > 255 || !lispy_function_keys[wParam])
3584 DWORD modifiers = construct_console_modifiers ();
3586 if (!NILP (Vw32_recognize_altgr)
3587 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3589 /* Always let TranslateMessage handle AltGr key chords;
3590 for some reason, ToAscii doesn't always process AltGr
3591 chords correctly. */
3592 windows_translate = 1;
3594 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3596 /* Handle key chords including any modifiers other
3597 than shift directly, in order to preserve as much
3598 modifier information as possible. */
3599 if ('A' <= wParam && wParam <= 'Z')
3601 /* Don't translate modified alphabetic keystrokes,
3602 so the user doesn't need to constantly switch
3603 layout to type control or meta keystrokes when
3604 the normal layout translates alphabetic
3605 characters to non-ascii characters. */
3606 if (!modifier_set (VK_SHIFT))
3607 wParam += ('a' - 'A');
3608 msg = WM_CHAR;
3610 else
3612 /* Try to handle other keystrokes by determining the
3613 base character (ie. translating the base key plus
3614 shift modifier). */
3615 int add;
3616 KEY_EVENT_RECORD key;
3618 key.bKeyDown = TRUE;
3619 key.wRepeatCount = 1;
3620 key.wVirtualKeyCode = wParam;
3621 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3622 key.uChar.AsciiChar = 0;
3623 key.dwControlKeyState = modifiers;
3625 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3626 /* 0 means an unrecognized keycode, negative means
3627 dead key. Ignore both. */
3628 while (--add >= 0)
3630 /* Forward asciified character sequence. */
3631 post_character_message
3632 (hwnd, WM_CHAR,
3633 (unsigned char) key.uChar.AsciiChar, lParam,
3634 w32_get_key_modifiers (wParam, lParam));
3635 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3637 return 0;
3640 else
3642 /* Let TranslateMessage handle everything else. */
3643 windows_translate = 1;
3648 if (windows_translate == -1)
3649 break;
3650 translate:
3651 if (windows_translate)
3653 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3654 windows_msg.time = GetMessageTime ();
3655 TranslateMessage (&windows_msg);
3656 goto dflt;
3659 /* Fall through */
3661 case WM_SYSCHAR:
3662 case WM_CHAR:
3663 if (wParam > 255 )
3665 W32Msg wmsg;
3667 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3668 signal_user_input ();
3669 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3672 else
3673 post_character_message (hwnd, msg, wParam, lParam,
3674 w32_get_key_modifiers (wParam, lParam));
3675 break;
3677 case WM_UNICHAR:
3678 /* WM_UNICHAR looks promising from the docs, but the exact
3679 circumstances in which TranslateMessage sends it is one of those
3680 Microsoft secret API things that EU and US courts are supposed
3681 to have put a stop to already. Spy++ shows it being sent to Notepad
3682 and other MS apps, but never to Emacs.
3684 Some third party IMEs send it in accordance with the official
3685 documentation though, so handle it here.
3687 UNICODE_NOCHAR is used to test for support for this message.
3688 TRUE indicates that the message is supported. */
3689 if (wParam == UNICODE_NOCHAR)
3690 return TRUE;
3693 W32Msg wmsg;
3694 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3695 signal_user_input ();
3696 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3698 break;
3700 case WM_IME_CHAR:
3701 /* If we can't get the IME result as Unicode, use default processing,
3702 which will at least allow characters decodable in the system locale
3703 get through. */
3704 if (!get_composition_string_fn)
3705 goto dflt;
3707 else if (!ignore_ime_char)
3709 wchar_t * buffer;
3710 int size, i;
3711 W32Msg wmsg;
3712 HIMC context = get_ime_context_fn (hwnd);
3713 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3714 /* Get buffer size. */
3715 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3716 buffer = alloca (size);
3717 size = get_composition_string_fn (context, GCS_RESULTSTR,
3718 buffer, size);
3719 release_ime_context_fn (hwnd, context);
3721 signal_user_input ();
3722 for (i = 0; i < size / sizeof (wchar_t); i++)
3724 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3725 lParam);
3727 /* Ignore the messages for the rest of the
3728 characters in the string that was output above. */
3729 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3731 else
3732 ignore_ime_char--;
3734 break;
3736 case WM_IME_STARTCOMPOSITION:
3737 if (!set_ime_composition_window_fn)
3738 goto dflt;
3739 else
3741 COMPOSITIONFORM form;
3742 HIMC context;
3743 struct window *w;
3745 /* Implementation note: The code below does something that
3746 one shouldn't do: it accesses the window object from a
3747 separate thread, while the main (a.k.a. "Lisp") thread
3748 runs and can legitimately delete and even GC it. That is
3749 why we are extra careful not to futz with a window that
3750 is different from the one recorded when the system caret
3751 coordinates were last modified. That is also why we are
3752 careful not to move the IME window if the window
3753 described by W was deleted, as indicated by its buffer
3754 field being reset to nil. */
3755 f = x_window_to_frame (dpyinfo, hwnd);
3756 if (!(f && FRAME_LIVE_P (f)))
3757 goto dflt;
3758 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3759 /* Punt if someone changed the frame's selected window
3760 behind our back. */
3761 if (w != w32_system_caret_window)
3762 goto dflt;
3764 form.dwStyle = CFS_RECT;
3765 form.ptCurrentPos.x = w32_system_caret_x;
3766 form.ptCurrentPos.y = w32_system_caret_y;
3768 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3769 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3770 + w32_system_caret_hdr_height);
3771 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3772 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3773 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3774 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3775 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3776 - w32_system_caret_mode_height);
3778 /* Punt if the window was deleted behind our back. */
3779 if (!BUFFERP (w->contents))
3780 goto dflt;
3782 context = get_ime_context_fn (hwnd);
3784 if (!context)
3785 goto dflt;
3787 set_ime_composition_window_fn (context, &form);
3788 release_ime_context_fn (hwnd, context);
3790 /* We should "goto dflt" here to pass WM_IME_STARTCOMPOSITION to
3791 DefWindowProc, so that the composition window will actually
3792 be displayed. But doing so causes trouble with displaying
3793 dialog boxes, such as the file selection dialog or font
3794 selection dialog. So something else is needed to fix the
3795 former without breaking the latter. See bug#11732. */
3796 break;
3798 case WM_IME_ENDCOMPOSITION:
3799 ignore_ime_char = 0;
3800 goto dflt;
3802 /* Simulate middle mouse button events when left and right buttons
3803 are used together, but only if user has two button mouse. */
3804 case WM_LBUTTONDOWN:
3805 case WM_RBUTTONDOWN:
3806 if (w32_num_mouse_buttons > 2)
3807 goto handle_plain_button;
3810 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3811 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3813 if (button_state & this)
3814 return 0;
3816 if (button_state == 0)
3817 SetCapture (hwnd);
3819 button_state |= this;
3821 if (button_state & other)
3823 if (mouse_button_timer)
3825 KillTimer (hwnd, mouse_button_timer);
3826 mouse_button_timer = 0;
3828 /* Generate middle mouse event instead. */
3829 msg = WM_MBUTTONDOWN;
3830 button_state |= MMOUSE;
3832 else if (button_state & MMOUSE)
3834 /* Ignore button event if we've already generated a
3835 middle mouse down event. This happens if the
3836 user releases and press one of the two buttons
3837 after we've faked a middle mouse event. */
3838 return 0;
3840 else
3842 /* Flush out saved message. */
3843 post_msg (&saved_mouse_button_msg);
3845 wmsg.dwModifiers = w32_get_modifiers ();
3846 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3847 signal_user_input ();
3849 /* Clear message buffer. */
3850 saved_mouse_button_msg.msg.hwnd = 0;
3852 else
3854 /* Hold onto message for now. */
3855 mouse_button_timer =
3856 SetTimer (hwnd, MOUSE_BUTTON_ID,
3857 w32_mouse_button_tolerance, NULL);
3858 saved_mouse_button_msg.msg.hwnd = hwnd;
3859 saved_mouse_button_msg.msg.message = msg;
3860 saved_mouse_button_msg.msg.wParam = wParam;
3861 saved_mouse_button_msg.msg.lParam = lParam;
3862 saved_mouse_button_msg.msg.time = GetMessageTime ();
3863 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3866 return 0;
3868 case WM_LBUTTONUP:
3869 case WM_RBUTTONUP:
3870 if (w32_num_mouse_buttons > 2)
3871 goto handle_plain_button;
3874 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3875 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3877 if ((button_state & this) == 0)
3878 return 0;
3880 button_state &= ~this;
3882 if (button_state & MMOUSE)
3884 /* Only generate event when second button is released. */
3885 if ((button_state & other) == 0)
3887 msg = WM_MBUTTONUP;
3888 button_state &= ~MMOUSE;
3890 if (button_state) emacs_abort ();
3892 else
3893 return 0;
3895 else
3897 /* Flush out saved message if necessary. */
3898 if (saved_mouse_button_msg.msg.hwnd)
3900 post_msg (&saved_mouse_button_msg);
3903 wmsg.dwModifiers = w32_get_modifiers ();
3904 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3905 signal_user_input ();
3907 /* Always clear message buffer and cancel timer. */
3908 saved_mouse_button_msg.msg.hwnd = 0;
3909 KillTimer (hwnd, mouse_button_timer);
3910 mouse_button_timer = 0;
3912 if (button_state == 0)
3913 ReleaseCapture ();
3915 return 0;
3917 case WM_XBUTTONDOWN:
3918 case WM_XBUTTONUP:
3919 if (w32_pass_extra_mouse_buttons_to_system)
3920 goto dflt;
3921 /* else fall through and process them. */
3922 case WM_MBUTTONDOWN:
3923 case WM_MBUTTONUP:
3924 handle_plain_button:
3926 BOOL up;
3927 int button;
3929 /* Ignore middle and extra buttons as long as the menu is active. */
3930 f = x_window_to_frame (dpyinfo, hwnd);
3931 if (f && f->output_data.w32->menubar_active)
3932 return 0;
3934 if (parse_button (msg, HIWORD (wParam), &button, &up))
3936 if (up) ReleaseCapture ();
3937 else SetCapture (hwnd);
3938 button = (button == 0) ? LMOUSE :
3939 ((button == 1) ? MMOUSE : RMOUSE);
3940 if (up)
3941 button_state &= ~button;
3942 else
3943 button_state |= button;
3947 wmsg.dwModifiers = w32_get_modifiers ();
3948 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3949 signal_user_input ();
3951 /* Need to return true for XBUTTON messages, false for others,
3952 to indicate that we processed the message. */
3953 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3955 case WM_MOUSEMOVE:
3956 f = x_window_to_frame (dpyinfo, hwnd);
3957 if (f)
3959 /* Ignore mouse movements as long as the menu is active.
3960 These movements are processed by the window manager
3961 anyway, and it's wrong to handle them as if they happened
3962 on the underlying frame. */
3963 if (f->output_data.w32->menubar_active)
3964 return 0;
3966 /* If the mouse moved, and the mouse pointer is invisible,
3967 make it visible again. We do this here so as to be able
3968 to show the mouse pointer even when the main
3969 (a.k.a. "Lisp") thread is busy doing something. */
3970 static int last_x, last_y;
3971 int x = GET_X_LPARAM (lParam);
3972 int y = GET_Y_LPARAM (lParam);
3974 if (f->pointer_invisible
3975 && (x != last_x || y != last_y))
3976 f->pointer_invisible = false;
3978 last_x = x;
3979 last_y = y;
3982 /* If the mouse has just moved into the frame, start tracking
3983 it, so we will be notified when it leaves the frame. Mouse
3984 tracking only works under W98 and NT4 and later. On earlier
3985 versions, there is no way of telling when the mouse leaves the
3986 frame, so we just have to put up with help-echo and mouse
3987 highlighting remaining while the frame is not active. */
3988 if (track_mouse_event_fn && !track_mouse_window
3989 /* If the menu bar is active, turning on tracking of mouse
3990 movement events might send these events to the tooltip
3991 frame, if the user happens to move the mouse pointer over
3992 the tooltip. But since we don't process events for
3993 tooltip frames, this causes Windows to present a
3994 hourglass cursor, which is ugly and unexpected. So don't
3995 enable tracking mouse events in this case; they will be
3996 restarted when the menu pops down. (Confusingly, the
3997 menubar_active member of f->output_data.w32, tested
3998 above, is only set when a menu was popped up _not_ from
3999 the frame's menu bar, but via x-popup-menu.) */
4000 && !menubar_in_use)
4002 TRACKMOUSEEVENT tme;
4003 tme.cbSize = sizeof (tme);
4004 tme.dwFlags = TME_LEAVE;
4005 tme.hwndTrack = hwnd;
4006 tme.dwHoverTime = HOVER_DEFAULT;
4008 track_mouse_event_fn (&tme);
4009 track_mouse_window = hwnd;
4011 case WM_HSCROLL:
4012 case WM_VSCROLL:
4013 if (w32_mouse_move_interval <= 0
4014 || (msg == WM_MOUSEMOVE && button_state == 0))
4016 wmsg.dwModifiers = w32_get_modifiers ();
4017 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4018 return 0;
4021 /* Hang onto mouse move and scroll messages for a bit, to avoid
4022 sending such events to Emacs faster than it can process them.
4023 If we get more events before the timer from the first message
4024 expires, we just replace the first message. */
4026 if (saved_mouse_move_msg.msg.hwnd == 0)
4027 mouse_move_timer =
4028 SetTimer (hwnd, MOUSE_MOVE_ID,
4029 w32_mouse_move_interval, NULL);
4031 /* Hold onto message for now. */
4032 saved_mouse_move_msg.msg.hwnd = hwnd;
4033 saved_mouse_move_msg.msg.message = msg;
4034 saved_mouse_move_msg.msg.wParam = wParam;
4035 saved_mouse_move_msg.msg.lParam = lParam;
4036 saved_mouse_move_msg.msg.time = GetMessageTime ();
4037 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4039 return 0;
4041 case WM_MOUSEWHEEL:
4042 case WM_DROPFILES:
4043 wmsg.dwModifiers = w32_get_modifiers ();
4044 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4045 signal_user_input ();
4046 return 0;
4048 case WM_APPCOMMAND:
4049 if (w32_pass_multimedia_buttons_to_system)
4050 goto dflt;
4051 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
4052 case WM_MOUSEHWHEEL:
4053 wmsg.dwModifiers = w32_get_modifiers ();
4054 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4055 signal_user_input ();
4056 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
4057 handled, to prevent the system trying to handle it by faking
4058 scroll bar events. */
4059 return 1;
4061 case WM_TIMER:
4062 /* Flush out saved messages if necessary. */
4063 if (wParam == mouse_button_timer)
4065 if (saved_mouse_button_msg.msg.hwnd)
4067 post_msg (&saved_mouse_button_msg);
4068 signal_user_input ();
4069 saved_mouse_button_msg.msg.hwnd = 0;
4071 KillTimer (hwnd, mouse_button_timer);
4072 mouse_button_timer = 0;
4074 else if (wParam == mouse_move_timer)
4076 if (saved_mouse_move_msg.msg.hwnd)
4078 post_msg (&saved_mouse_move_msg);
4079 saved_mouse_move_msg.msg.hwnd = 0;
4081 KillTimer (hwnd, mouse_move_timer);
4082 mouse_move_timer = 0;
4084 else if (wParam == menu_free_timer)
4086 KillTimer (hwnd, menu_free_timer);
4087 menu_free_timer = 0;
4088 f = x_window_to_frame (dpyinfo, hwnd);
4089 /* If a popup menu is active, don't wipe its strings. */
4090 if (menubar_in_use
4091 && current_popup_menu == NULL)
4093 /* Free memory used by owner-drawn and help-echo strings. */
4094 w32_free_menu_strings (hwnd);
4095 if (f)
4096 f->output_data.w32->menubar_active = 0;
4097 menubar_in_use = 0;
4100 return 0;
4102 case WM_NCACTIVATE:
4103 /* Windows doesn't send us focus messages when putting up and
4104 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4105 The only indication we get that something happened is receiving
4106 this message afterwards. So this is a good time to reset our
4107 keyboard modifiers' state. */
4108 reset_modifiers ();
4109 goto dflt;
4111 case WM_INITMENU:
4112 button_state = 0;
4113 ReleaseCapture ();
4114 /* We must ensure menu bar is fully constructed and up to date
4115 before allowing user interaction with it. To achieve this
4116 we send this message to the lisp thread and wait for a
4117 reply (whose value is not actually needed) to indicate that
4118 the menu bar is now ready for use, so we can now return.
4120 To remain responsive in the meantime, we enter a nested message
4121 loop that can process all other messages.
4123 However, we skip all this if the message results from calling
4124 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4125 thread a message because it is blocked on us at this point. We
4126 set menubar_active before calling TrackPopupMenu to indicate
4127 this (there is no possibility of confusion with real menubar
4128 being active). */
4130 f = x_window_to_frame (dpyinfo, hwnd);
4131 if (f
4132 && (f->output_data.w32->menubar_active
4133 /* We can receive this message even in the absence of a
4134 menubar (ie. when the system menu is activated) - in this
4135 case we do NOT want to forward the message, otherwise it
4136 will cause the menubar to suddenly appear when the user
4137 had requested it to be turned off! */
4138 || f->output_data.w32->menubar_widget == NULL))
4139 return 0;
4142 deferred_msg msg_buf;
4144 /* Detect if message has already been deferred; in this case
4145 we cannot return any sensible value to ignore this. */
4146 if (find_deferred_msg (hwnd, msg) != NULL)
4147 emacs_abort ();
4149 menubar_in_use = 1;
4151 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4154 case WM_EXITMENULOOP:
4155 f = x_window_to_frame (dpyinfo, hwnd);
4157 /* If a menu is still active, check again after a short delay,
4158 since Windows often (always?) sends the WM_EXITMENULOOP
4159 before the corresponding WM_COMMAND message.
4160 Don't do this if a popup menu is active, since it is only
4161 menubar menus that require cleaning up in this way.
4163 if (f && menubar_in_use && current_popup_menu == NULL)
4164 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4166 /* If hourglass cursor should be displayed, display it now. */
4167 if (f && f->output_data.w32->hourglass_p)
4168 SetCursor (f->output_data.w32->hourglass_cursor);
4170 goto dflt;
4172 case WM_MENUSELECT:
4173 /* Direct handling of help_echo in menus. Should be safe now
4174 that we generate the help_echo by placing a help event in the
4175 keyboard buffer. */
4177 HMENU menu = (HMENU) lParam;
4178 UINT menu_item = (UINT) LOWORD (wParam);
4179 UINT flags = (UINT) HIWORD (wParam);
4181 w32_menu_display_help (hwnd, menu, menu_item, flags);
4183 return 0;
4185 case WM_MEASUREITEM:
4186 f = x_window_to_frame (dpyinfo, hwnd);
4187 if (f)
4189 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4191 if (pMis->CtlType == ODT_MENU)
4193 /* Work out dimensions for popup menu titles. */
4194 char * title = (char *) pMis->itemData;
4195 HDC hdc = GetDC (hwnd);
4196 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4197 LOGFONT menu_logfont;
4198 HFONT old_font;
4199 SIZE size;
4201 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4202 menu_logfont.lfWeight = FW_BOLD;
4203 menu_font = CreateFontIndirect (&menu_logfont);
4204 old_font = SelectObject (hdc, menu_font);
4206 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4207 if (title)
4209 if (unicode_append_menu)
4210 GetTextExtentPoint32W (hdc, (WCHAR *) title,
4211 wcslen ((WCHAR *) title),
4212 &size);
4213 else
4214 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4216 pMis->itemWidth = size.cx;
4217 if (pMis->itemHeight < size.cy)
4218 pMis->itemHeight = size.cy;
4220 else
4221 pMis->itemWidth = 0;
4223 SelectObject (hdc, old_font);
4224 DeleteObject (menu_font);
4225 ReleaseDC (hwnd, hdc);
4226 return TRUE;
4229 return 0;
4231 case WM_DRAWITEM:
4232 f = x_window_to_frame (dpyinfo, hwnd);
4233 if (f)
4235 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4237 if (pDis->CtlType == ODT_MENU)
4239 /* Draw popup menu title. */
4240 char * title = (char *) pDis->itemData;
4241 if (title)
4243 HDC hdc = pDis->hDC;
4244 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4245 LOGFONT menu_logfont;
4246 HFONT old_font;
4248 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4249 menu_logfont.lfWeight = FW_BOLD;
4250 menu_font = CreateFontIndirect (&menu_logfont);
4251 old_font = SelectObject (hdc, menu_font);
4253 /* Always draw title as if not selected. */
4254 if (unicode_append_menu)
4255 ExtTextOutW (hdc,
4256 pDis->rcItem.left
4257 + GetSystemMetrics (SM_CXMENUCHECK),
4258 pDis->rcItem.top,
4259 ETO_OPAQUE, &pDis->rcItem,
4260 (WCHAR *) title,
4261 wcslen ((WCHAR *) title), NULL);
4262 else
4263 ExtTextOut (hdc,
4264 pDis->rcItem.left
4265 + GetSystemMetrics (SM_CXMENUCHECK),
4266 pDis->rcItem.top,
4267 ETO_OPAQUE, &pDis->rcItem,
4268 title, strlen (title), NULL);
4270 SelectObject (hdc, old_font);
4271 DeleteObject (menu_font);
4273 return TRUE;
4276 return 0;
4278 #if 0
4279 /* Still not right - can't distinguish between clicks in the
4280 client area of the frame from clicks forwarded from the scroll
4281 bars - may have to hook WM_NCHITTEST to remember the mouse
4282 position and then check if it is in the client area ourselves. */
4283 case WM_MOUSEACTIVATE:
4284 /* Discard the mouse click that activates a frame, allowing the
4285 user to click anywhere without changing point (or worse!).
4286 Don't eat mouse clicks on scrollbars though!! */
4287 if (LOWORD (lParam) == HTCLIENT )
4288 return MA_ACTIVATEANDEAT;
4289 goto dflt;
4290 #endif
4292 case WM_MOUSELEAVE:
4293 /* No longer tracking mouse. */
4294 track_mouse_window = NULL;
4296 case WM_ACTIVATEAPP:
4297 case WM_ACTIVATE:
4298 case WM_WINDOWPOSCHANGED:
4299 case WM_SHOWWINDOW:
4300 /* Inform lisp thread that a frame might have just been obscured
4301 or exposed, so should recheck visibility of all frames. */
4302 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4303 goto dflt;
4305 case WM_SETFOCUS:
4306 dpyinfo->faked_key = 0;
4307 reset_modifiers ();
4308 register_hot_keys (hwnd);
4309 goto command;
4310 case WM_KILLFOCUS:
4311 unregister_hot_keys (hwnd);
4312 button_state = 0;
4313 ReleaseCapture ();
4314 /* Relinquish the system caret. */
4315 if (w32_system_caret_hwnd)
4317 w32_visible_system_caret_hwnd = NULL;
4318 w32_system_caret_hwnd = NULL;
4319 DestroyCaret ();
4321 goto command;
4322 case WM_COMMAND:
4323 menubar_in_use = 0;
4324 f = x_window_to_frame (dpyinfo, hwnd);
4325 if (f && HIWORD (wParam) == 0)
4327 if (menu_free_timer)
4329 KillTimer (hwnd, menu_free_timer);
4330 menu_free_timer = 0;
4333 case WM_MOVE:
4334 case WM_SIZE:
4335 command:
4336 wmsg.dwModifiers = w32_get_modifiers ();
4337 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4338 goto dflt;
4340 case WM_DESTROY:
4341 CoUninitialize ();
4342 return 0;
4344 case WM_CLOSE:
4345 wmsg.dwModifiers = w32_get_modifiers ();
4346 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4347 return 0;
4349 case WM_WINDOWPOSCHANGING:
4350 /* Don't restrict the sizing of any kind of frames. If the window
4351 manager doesn't, there's no reason to do it ourselves. */
4352 #if 0
4353 if (frame_resize_pixelwise || hwnd == tip_window)
4354 #endif
4355 return 0;
4357 #if 0
4358 /* Don't restrict the sizing of fullscreened frames, allowing them to be
4359 flush with the sides of the screen. */
4360 f = x_window_to_frame (dpyinfo, hwnd);
4361 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
4362 return 0;
4365 WINDOWPLACEMENT wp;
4366 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4368 wp.length = sizeof (WINDOWPLACEMENT);
4369 GetWindowPlacement (hwnd, &wp);
4371 if (wp.showCmd != SW_SHOWMAXIMIZED && wp.showCmd != SW_SHOWMINIMIZED
4372 && (lppos->flags & SWP_NOSIZE) == 0)
4374 RECT rect;
4375 int wdiff;
4376 int hdiff;
4377 DWORD font_width;
4378 DWORD line_height;
4379 DWORD internal_border;
4380 DWORD vscrollbar_extra;
4381 DWORD hscrollbar_extra;
4382 RECT wr;
4384 wp.length = sizeof (wp);
4385 GetWindowRect (hwnd, &wr);
4387 enter_crit ();
4389 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4390 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4391 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4392 vscrollbar_extra = GetWindowLong (hwnd, WND_VSCROLLBAR_INDEX);
4393 hscrollbar_extra = GetWindowLong (hwnd, WND_HSCROLLBAR_INDEX);
4395 leave_crit ();
4397 memset (&rect, 0, sizeof (rect));
4398 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4399 GetMenu (hwnd) != NULL);
4401 /* Force width and height of client area to be exact
4402 multiples of the character cell dimensions. */
4403 wdiff = (lppos->cx - (rect.right - rect.left)
4404 - 2 * internal_border - vscrollbar_extra)
4405 % font_width;
4406 hdiff = (lppos->cy - (rect.bottom - rect.top)
4407 - 2 * internal_border - hscrollbar_extra)
4408 % line_height;
4410 if (wdiff || hdiff)
4412 /* For right/bottom sizing we can just fix the sizes.
4413 However for top/left sizing we will need to fix the X
4414 and Y positions as well. */
4416 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
4417 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
4419 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
4420 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
4422 if (wp.showCmd != SW_SHOWMAXIMIZED
4423 && (lppos->flags & SWP_NOMOVE) == 0)
4425 if (lppos->x != wr.left || lppos->y != wr.top)
4427 lppos->x += wdiff;
4428 lppos->y += hdiff;
4430 else
4432 lppos->flags |= SWP_NOMOVE;
4436 return 0;
4441 goto dflt;
4442 #endif
4444 case WM_GETMINMAXINFO:
4445 /* Hack to allow resizing the Emacs frame above the screen size.
4446 Note that Windows 9x limits coordinates to 16-bits. */
4447 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
4448 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
4449 return 0;
4451 case WM_SETCURSOR:
4452 if (LOWORD (lParam) == HTCLIENT)
4454 f = x_window_to_frame (dpyinfo, hwnd);
4455 if (f)
4457 if (f->output_data.w32->hourglass_p
4458 && !menubar_in_use && !current_popup_menu)
4459 SetCursor (f->output_data.w32->hourglass_cursor);
4460 else if (f->pointer_invisible)
4461 SetCursor (NULL);
4462 else
4463 SetCursor (f->output_data.w32->current_cursor);
4466 return 0;
4468 goto dflt;
4470 case WM_EMACS_SETCURSOR:
4472 Cursor cursor = (Cursor) wParam;
4473 f = x_window_to_frame (dpyinfo, hwnd);
4474 if (f && cursor)
4476 f->output_data.w32->current_cursor = cursor;
4477 /* Don't change the cursor while menu-bar menu is in use. */
4478 if (!f->output_data.w32->menubar_active
4479 && !f->output_data.w32->hourglass_p)
4481 if (f->pointer_invisible)
4482 SetCursor (NULL);
4483 else
4484 SetCursor (cursor);
4487 return 0;
4490 case WM_EMACS_SHOWCURSOR:
4492 ShowCursor ((BOOL) wParam);
4494 return 0;
4497 case WM_EMACS_CREATEVSCROLLBAR:
4498 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
4499 (struct scroll_bar *) lParam);
4501 case WM_EMACS_CREATEHSCROLLBAR:
4502 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
4503 (struct scroll_bar *) lParam);
4505 case WM_EMACS_SHOWWINDOW:
4506 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4508 case WM_EMACS_BRINGTOTOP:
4509 case WM_EMACS_SETFOREGROUND:
4511 HWND foreground_window;
4512 DWORD foreground_thread, retval;
4514 /* On NT 5.0, and apparently Windows 98, it is necessary to
4515 attach to the thread that currently has focus in order to
4516 pull the focus away from it. */
4517 foreground_window = GetForegroundWindow ();
4518 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4519 if (!foreground_window
4520 || foreground_thread == GetCurrentThreadId ()
4521 || !AttachThreadInput (GetCurrentThreadId (),
4522 foreground_thread, TRUE))
4523 foreground_thread = 0;
4525 retval = SetForegroundWindow ((HWND) wParam);
4526 if (msg == WM_EMACS_BRINGTOTOP)
4527 retval = BringWindowToTop ((HWND) wParam);
4529 /* Detach from the previous foreground thread. */
4530 if (foreground_thread)
4531 AttachThreadInput (GetCurrentThreadId (),
4532 foreground_thread, FALSE);
4534 return retval;
4537 case WM_EMACS_SETWINDOWPOS:
4539 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4540 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4541 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4544 case WM_EMACS_DESTROYWINDOW:
4545 DragAcceptFiles ((HWND) wParam, FALSE);
4546 return DestroyWindow ((HWND) wParam);
4548 case WM_EMACS_HIDE_CARET:
4549 return HideCaret (hwnd);
4551 case WM_EMACS_SHOW_CARET:
4552 return ShowCaret (hwnd);
4554 case WM_EMACS_DESTROY_CARET:
4555 w32_system_caret_hwnd = NULL;
4556 w32_visible_system_caret_hwnd = NULL;
4557 return DestroyCaret ();
4559 case WM_EMACS_TRACK_CARET:
4560 /* If there is currently no system caret, create one. */
4561 if (w32_system_caret_hwnd == NULL)
4563 /* Use the default caret width, and avoid changing it
4564 unnecessarily, as it confuses screen reader software. */
4565 w32_system_caret_hwnd = hwnd;
4566 CreateCaret (hwnd, NULL, 0,
4567 w32_system_caret_height);
4570 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4571 return 0;
4572 /* Ensure visible caret gets turned on when requested. */
4573 else if (w32_use_visible_system_caret
4574 && w32_visible_system_caret_hwnd != hwnd)
4576 w32_visible_system_caret_hwnd = hwnd;
4577 return ShowCaret (hwnd);
4579 /* Ensure visible caret gets turned off when requested. */
4580 else if (!w32_use_visible_system_caret
4581 && w32_visible_system_caret_hwnd)
4583 w32_visible_system_caret_hwnd = NULL;
4584 return HideCaret (hwnd);
4586 else
4587 return 1;
4589 case WM_EMACS_TRACKPOPUPMENU:
4591 UINT flags;
4592 POINT *pos;
4593 int retval;
4594 pos = (POINT *)lParam;
4595 flags = TPM_CENTERALIGN;
4596 if (button_state & LMOUSE)
4597 flags |= TPM_LEFTBUTTON;
4598 else if (button_state & RMOUSE)
4599 flags |= TPM_RIGHTBUTTON;
4601 /* Remember we did a SetCapture on the initial mouse down event,
4602 so for safety, we make sure the capture is canceled now. */
4603 ReleaseCapture ();
4604 button_state = 0;
4606 /* Use menubar_active to indicate that WM_INITMENU is from
4607 TrackPopupMenu below, and should be ignored. */
4608 f = x_window_to_frame (dpyinfo, hwnd);
4609 if (f)
4610 f->output_data.w32->menubar_active = 1;
4612 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4613 0, hwnd, NULL))
4615 MSG amsg;
4616 /* Eat any mouse messages during popupmenu */
4617 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4618 PM_REMOVE));
4619 /* Get the menu selection, if any */
4620 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4622 retval = LOWORD (amsg.wParam);
4624 else
4626 retval = 0;
4629 else
4631 retval = -1;
4634 return retval;
4636 case WM_EMACS_FILENOTIFY:
4637 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4638 return 1;
4640 default:
4641 /* Check for messages registered at runtime. */
4642 if (msg == msh_mousewheel)
4644 wmsg.dwModifiers = w32_get_modifiers ();
4645 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4646 signal_user_input ();
4647 return 0;
4650 dflt:
4651 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4654 /* The most common default return code for handled messages is 0. */
4655 return 0;
4658 static void
4659 my_create_window (struct frame * f)
4661 MSG msg;
4662 static int coords[2];
4663 Lisp_Object left, top;
4664 struct w32_display_info *dpyinfo = &one_w32_display_info;
4666 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
4667 anything that is not a number and is not Qunbound. */
4668 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
4669 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
4670 if (EQ (left, Qunbound))
4671 coords[0] = CW_USEDEFAULT;
4672 else
4673 coords[0] = XINT (left);
4674 if (EQ (top, Qunbound))
4675 coords[1] = CW_USEDEFAULT;
4676 else
4677 coords[1] = XINT (top);
4679 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
4680 (WPARAM)f, (LPARAM)coords))
4681 emacs_abort ();
4682 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4686 /* Create a tooltip window. Unlike my_create_window, we do not do this
4687 indirectly via the Window thread, as we do not need to process Window
4688 messages for the tooltip. Creating tooltips indirectly also creates
4689 deadlocks when tooltips are created for menu items. */
4690 static void
4691 my_create_tip_window (struct frame *f)
4693 RECT rect;
4695 rect.left = rect.top = 0;
4696 rect.right = FRAME_PIXEL_WIDTH (f);
4697 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4699 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4700 FRAME_EXTERNAL_MENU_BAR (f));
4702 tip_window = FRAME_W32_WINDOW (f)
4703 = CreateWindow (EMACS_CLASS,
4704 f->namebuf,
4705 f->output_data.w32->dwStyle,
4706 f->left_pos,
4707 f->top_pos,
4708 rect.right - rect.left,
4709 rect.bottom - rect.top,
4710 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4711 NULL,
4712 hinst,
4713 NULL);
4715 if (tip_window)
4717 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4718 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4719 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4720 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4722 /* Tip frames have no scrollbars. */
4723 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
4724 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
4726 /* Do this to discard the default setting specified by our parent. */
4727 ShowWindow (tip_window, SW_HIDE);
4732 /* Create and set up the w32 window for frame F. */
4734 static void
4735 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
4737 block_input ();
4739 /* Use the resource name as the top-level window name
4740 for looking up resources. Make a non-Lisp copy
4741 for the window manager, so GC relocation won't bother it.
4743 Elsewhere we specify the window name for the window manager. */
4744 f->namebuf = xlispstrdup (Vx_resource_name);
4746 my_create_window (f);
4748 validate_x_resource_name ();
4750 /* x_set_name normally ignores requests to set the name if the
4751 requested name is the same as the current name. This is the one
4752 place where that assumption isn't correct; f->name is set, but
4753 the server hasn't been told. */
4755 Lisp_Object name;
4756 int explicit = f->explicit_name;
4758 f->explicit_name = 0;
4759 name = f->name;
4760 fset_name (f, Qnil);
4761 x_set_name (f, name, explicit);
4764 unblock_input ();
4766 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4767 initialize_frame_menubar (f);
4769 if (FRAME_W32_WINDOW (f) == 0)
4770 error ("Unable to create window");
4773 /* Handle the icon stuff for this window. Perhaps later we might
4774 want an x_set_icon_position which can be called interactively as
4775 well. */
4777 static void
4778 x_icon (struct frame *f, Lisp_Object parms)
4780 Lisp_Object icon_x, icon_y;
4781 struct w32_display_info *dpyinfo = &one_w32_display_info;
4783 /* Set the position of the icon. Note that Windows 95 groups all
4784 icons in the tray. */
4785 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4786 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4787 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4789 CHECK_NUMBER (icon_x);
4790 CHECK_NUMBER (icon_y);
4792 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4793 error ("Both left and top icon corners of icon must be specified");
4795 block_input ();
4797 #if 0 /* TODO */
4798 /* Start up iconic or window? */
4799 x_wm_set_window_state
4800 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4801 ? IconicState
4802 : NormalState));
4804 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4805 ? f->icon_name
4806 : f->name)));
4807 #endif
4809 unblock_input ();
4813 static void
4814 x_make_gc (struct frame *f)
4816 XGCValues gc_values;
4818 block_input ();
4820 /* Create the GC's of this frame.
4821 Note that many default values are used. */
4823 /* Normal video */
4824 gc_values.font = FRAME_FONT (f);
4826 /* Cursor has cursor-color background, background-color foreground. */
4827 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4828 gc_values.background = f->output_data.w32->cursor_pixel;
4829 f->output_data.w32->cursor_gc
4830 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4831 (GCFont | GCForeground | GCBackground),
4832 &gc_values);
4834 /* Reliefs. */
4835 f->output_data.w32->white_relief.gc = 0;
4836 f->output_data.w32->black_relief.gc = 0;
4838 unblock_input ();
4842 /* Handler for signals raised during x_create_frame and
4843 x_create_tip_frame. FRAME is the frame which is partially
4844 constructed. */
4846 static Lisp_Object
4847 unwind_create_frame (Lisp_Object frame)
4849 struct frame *f = XFRAME (frame);
4851 /* If frame is ``official'', nothing to do. */
4852 if (NILP (Fmemq (frame, Vframe_list)))
4854 #ifdef GLYPH_DEBUG
4855 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4857 /* If the frame's image cache refcount is still the same as our
4858 private shadow variable, it means we are unwinding a frame
4859 for which we didn't yet call init_frame_faces, where the
4860 refcount is incremented. Therefore, we increment it here, so
4861 that free_frame_faces, called in x_free_frame_resources
4862 below, will not mistakenly decrement the counter that was not
4863 incremented yet to account for this new frame. */
4864 if (FRAME_IMAGE_CACHE (f) != NULL
4865 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
4866 FRAME_IMAGE_CACHE (f)->refcount++;
4867 #endif
4869 x_free_frame_resources (f);
4870 free_glyphs (f);
4872 #ifdef GLYPH_DEBUG
4873 /* Check that reference counts are indeed correct. */
4874 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4875 eassert ((dpyinfo->terminal->image_cache == NULL
4876 && image_cache_refcount == 0)
4877 || (dpyinfo->terminal->image_cache != NULL
4878 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
4879 #endif
4880 return Qt;
4883 return Qnil;
4886 static void
4887 do_unwind_create_frame (Lisp_Object frame)
4889 unwind_create_frame (frame);
4892 static void
4893 unwind_create_frame_1 (Lisp_Object val)
4895 inhibit_lisp_code = val;
4898 static void
4899 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4901 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4902 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4903 RES_TYPE_STRING);
4904 Lisp_Object font;
4905 if (EQ (font_param, Qunbound))
4906 font_param = Qnil;
4907 font = !NILP (font_param) ? font_param
4908 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4910 if (!STRINGP (font))
4912 int i;
4913 static char *names[]
4914 = { "Courier New-10",
4915 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4916 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4917 "Fixedsys",
4918 NULL };
4920 for (i = 0; names[i]; i++)
4922 font = font_open_by_name (f, build_unibyte_string (names[i]));
4923 if (! NILP (font))
4924 break;
4926 if (NILP (font))
4927 error ("No suitable font was found");
4929 else if (!NILP (font_param))
4931 /* Remember the explicit font parameter, so we can re-apply it after
4932 we've applied the `default' face settings. */
4933 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4935 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4938 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4939 1, 1, 0,
4940 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4941 Return an Emacs frame object.
4942 PARAMETERS is an alist of frame parameters.
4943 If the parameters specify that the frame should not have a minibuffer,
4944 and do not specify a specific minibuffer window to use,
4945 then `default-minibuffer-frame' must be a frame whose minibuffer can
4946 be shared by the new frame.
4948 This function is an internal primitive--use `make-frame' instead. */)
4949 (Lisp_Object parameters)
4951 struct frame *f;
4952 Lisp_Object frame, tem;
4953 Lisp_Object name;
4954 bool minibuffer_only = false;
4955 long window_prompting = 0;
4956 ptrdiff_t count = SPECPDL_INDEX ();
4957 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4958 Lisp_Object display;
4959 struct w32_display_info *dpyinfo = NULL;
4960 Lisp_Object parent;
4961 struct kboard *kb;
4963 if (!FRAME_W32_P (SELECTED_FRAME ())
4964 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4965 error ("Cannot create a GUI frame in a -nw session");
4967 /* Make copy of frame parameters because the original is in pure
4968 storage now. */
4969 parameters = Fcopy_alist (parameters);
4971 /* Use this general default value to start with
4972 until we know if this frame has a specified name. */
4973 Vx_resource_name = Vinvocation_name;
4975 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4976 if (EQ (display, Qunbound))
4977 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4978 if (EQ (display, Qunbound))
4979 display = Qnil;
4980 dpyinfo = check_x_display_info (display);
4981 kb = dpyinfo->terminal->kboard;
4983 if (!dpyinfo->terminal->name)
4984 error ("Terminal is not live, can't create new frames on it");
4986 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4987 if (!STRINGP (name)
4988 && ! EQ (name, Qunbound)
4989 && ! NILP (name))
4990 error ("Invalid frame name--not a string or nil");
4992 if (STRINGP (name))
4993 Vx_resource_name = name;
4995 /* See if parent window is specified. */
4996 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4997 if (EQ (parent, Qunbound))
4998 parent = Qnil;
4999 if (! NILP (parent))
5000 CHECK_NUMBER (parent);
5002 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5003 /* No need to protect DISPLAY because that's not used after passing
5004 it to make_frame_without_minibuffer. */
5005 frame = Qnil;
5006 GCPRO4 (parameters, parent, name, frame);
5007 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5008 RES_TYPE_SYMBOL);
5009 if (EQ (tem, Qnone) || NILP (tem))
5010 f = make_frame_without_minibuffer (Qnil, kb, display);
5011 else if (EQ (tem, Qonly))
5013 f = make_minibuffer_frame ();
5014 minibuffer_only = true;
5016 else if (WINDOWP (tem))
5017 f = make_frame_without_minibuffer (tem, kb, display);
5018 else
5019 f = make_frame (true);
5021 XSETFRAME (frame, f);
5023 /* By default, make scrollbars the system standard width and height. */
5024 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5025 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5027 f->terminal = dpyinfo->terminal;
5029 f->output_method = output_w32;
5030 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5031 FRAME_FONTSET (f) = -1;
5033 fset_icon_name
5034 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5035 RES_TYPE_STRING));
5036 if (! STRINGP (f->icon_name))
5037 fset_icon_name (f, Qnil);
5039 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5041 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5042 record_unwind_protect (do_unwind_create_frame, frame);
5044 #ifdef GLYPH_DEBUG
5045 image_cache_refcount =
5046 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5047 dpyinfo_refcount = dpyinfo->reference_count;
5048 #endif /* GLYPH_DEBUG */
5050 /* Specify the parent under which to make this window. */
5051 if (!NILP (parent))
5053 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5054 pointer from integer of different size. */
5055 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5056 f->output_data.w32->explicit_parent = true;
5058 else
5060 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5061 f->output_data.w32->explicit_parent = false;
5064 /* Set the name; the functions to which we pass f expect the name to
5065 be set. */
5066 if (EQ (name, Qunbound) || NILP (name))
5068 fset_name (f, build_string (dpyinfo->w32_id_name));
5069 f->explicit_name = false;
5071 else
5073 fset_name (f, name);
5074 f->explicit_name = true;
5075 /* Use the frame's title when getting resources for this frame. */
5076 specbind (Qx_resource_name, name);
5079 if (uniscribe_available)
5080 register_font_driver (&uniscribe_font_driver, f);
5081 register_font_driver (&w32font_driver, f);
5083 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5084 "fontBackend", "FontBackend", RES_TYPE_STRING);
5086 /* Extract the window parameters from the supplied values
5087 that are needed to determine window geometry. */
5088 x_default_font_parameter (f, parameters);
5090 x_default_parameter (f, parameters, Qborder_width, make_number (2),
5091 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5093 /* We recognize either internalBorderWidth or internalBorder
5094 (which is what xterm calls it). */
5095 if (NILP (Fassq (Qinternal_border_width, parameters)))
5097 Lisp_Object value;
5099 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5100 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5101 if (! EQ (value, Qunbound))
5102 parameters = Fcons (Fcons (Qinternal_border_width, value),
5103 parameters);
5105 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5106 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5107 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5108 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5109 NULL, NULL, RES_TYPE_NUMBER);
5110 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5111 NULL, NULL, RES_TYPE_NUMBER);
5112 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5113 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5114 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5115 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5117 /* Also do the stuff which must be set before the window exists. */
5118 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5119 "foreground", "Foreground", RES_TYPE_STRING);
5120 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5121 "background", "Background", RES_TYPE_STRING);
5122 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5123 "pointerColor", "Foreground", RES_TYPE_STRING);
5124 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5125 "borderColor", "BorderColor", RES_TYPE_STRING);
5126 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5127 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5128 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5129 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5130 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5131 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5132 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5133 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5134 /* Process alpha here (Bug#16619). */
5135 x_default_parameter (f, parameters, Qalpha, Qnil,
5136 "alpha", "Alpha", RES_TYPE_NUMBER);
5138 /* Init faces first since we need the frame's column width/line
5139 height in various occasions. */
5140 init_frame_faces (f);
5142 /* The following call of change_frame_size is needed since otherwise
5143 x_set_tool_bar_lines will already work with the character sizes
5144 installed by init_frame_faces while the frame's pixel size is
5145 still calculated from a character size of 1 and we subsequently
5146 hit the (height >= 0) assertion in window_box_height.
5148 The non-pixelwise code apparently worked around this because it
5149 had one frame line vs one toolbar line which left us with a zero
5150 root window height which was obviously wrong as well ... */
5151 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5152 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5153 Qx_create_frame_1);
5155 /* The X resources controlling the menu-bar and tool-bar are
5156 processed specially at startup, and reflected in the mode
5157 variables; ignore them here. */
5158 x_default_parameter (f, parameters, Qmenu_bar_lines,
5159 NILP (Vmenu_bar_mode)
5160 ? make_number (0) : make_number (1),
5161 NULL, NULL, RES_TYPE_NUMBER);
5162 x_default_parameter (f, parameters, Qtool_bar_lines,
5163 NILP (Vtool_bar_mode)
5164 ? make_number (0) : make_number (1),
5165 NULL, NULL, RES_TYPE_NUMBER);
5167 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5168 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5169 x_default_parameter (f, parameters, Qtitle, Qnil,
5170 "title", "Title", RES_TYPE_STRING);
5172 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5173 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5175 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5176 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5177 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5178 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5179 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5180 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5181 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5183 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5185 window_prompting = x_figure_window_size (f, parameters, true);
5187 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5188 f->no_split = minibuffer_only || EQ (tem, Qt);
5190 w32_window (f, window_prompting, minibuffer_only);
5191 x_icon (f, parameters);
5193 x_make_gc (f);
5195 /* Now consider the frame official. */
5196 f->terminal->reference_count++;
5197 FRAME_DISPLAY_INFO (f)->reference_count++;
5198 Vframe_list = Fcons (frame, Vframe_list);
5200 /* We need to do this after creating the window, so that the
5201 icon-creation functions can say whose icon they're describing. */
5202 x_default_parameter (f, parameters, Qicon_type, Qnil,
5203 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5205 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5206 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5207 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5208 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5209 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5210 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5211 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5212 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5213 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
5214 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
5216 /* Allow x_set_window_size, now. */
5217 f->can_x_set_window_size = true;
5219 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
5220 Qx_create_frame_2);
5222 /* Tell the server what size and position, etc, we want, and how
5223 badly we want them. This should be done after we have the menu
5224 bar so that its size can be taken into account. */
5225 block_input ();
5226 x_wm_set_size_hint (f, window_prompting, false);
5227 unblock_input ();
5229 /* Process fullscreen parameter here in the hope that normalizing a
5230 fullheight/fullwidth frame will produce the size set by the last
5231 adjust_frame_size call. */
5232 x_default_parameter (f, parameters, Qfullscreen, Qnil,
5233 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5235 /* Make the window appear on the frame and enable display, unless
5236 the caller says not to. However, with explicit parent, Emacs
5237 cannot control visibility, so don't try. */
5238 if (! f->output_data.w32->explicit_parent)
5240 Lisp_Object visibility;
5242 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5243 if (EQ (visibility, Qunbound))
5244 visibility = Qt;
5246 if (EQ (visibility, Qicon))
5247 x_iconify_frame (f);
5248 else if (! NILP (visibility))
5249 x_make_frame_visible (f);
5250 else
5251 /* Must have been Qnil. */
5255 /* Initialize `default-minibuffer-frame' in case this is the first
5256 frame on this terminal. */
5257 if (FRAME_HAS_MINIBUF_P (f)
5258 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
5259 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
5260 kset_default_minibuffer_frame (kb, frame);
5262 /* All remaining specified parameters, which have not been "used"
5263 by x_get_arg and friends, now go in the misc. alist of the frame. */
5264 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
5265 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
5266 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
5268 UNGCPRO;
5270 /* Make sure windows on this frame appear in calls to next-window
5271 and similar functions. */
5272 Vwindow_list = Qnil;
5274 return unbind_to (count, frame);
5277 /* FRAME is used only to get a handle on the X display. We don't pass the
5278 display info directly because we're called from frame.c, which doesn't
5279 know about that structure. */
5280 Lisp_Object
5281 x_get_focus_frame (struct frame *frame)
5283 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
5284 Lisp_Object xfocus;
5285 if (! dpyinfo->w32_focus_frame)
5286 return Qnil;
5288 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5289 return xfocus;
5292 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
5293 doc: /* Internal function called by `color-defined-p', which see.
5294 \(Note that the Nextstep version of this function ignores FRAME.) */)
5295 (Lisp_Object color, Lisp_Object frame)
5297 XColor foo;
5298 struct frame *f = decode_window_system_frame (frame);
5300 CHECK_STRING (color);
5302 if (w32_defined_color (f, SDATA (color), &foo, false))
5303 return Qt;
5304 else
5305 return Qnil;
5308 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
5309 doc: /* Internal function called by `color-values', which see. */)
5310 (Lisp_Object color, Lisp_Object frame)
5312 XColor foo;
5313 struct frame *f = decode_window_system_frame (frame);
5315 CHECK_STRING (color);
5317 if (w32_defined_color (f, SDATA (color), &foo, false))
5318 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
5319 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
5320 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
5321 else
5322 return Qnil;
5325 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
5326 doc: /* Internal function called by `display-color-p', which see. */)
5327 (Lisp_Object display)
5329 struct w32_display_info *dpyinfo = check_x_display_info (display);
5331 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
5332 return Qnil;
5334 return Qt;
5337 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
5338 Sx_display_grayscale_p, 0, 1, 0,
5339 doc: /* Return t if DISPLAY supports shades of gray.
5340 Note that color displays do support shades of gray.
5341 The optional argument DISPLAY specifies which display to ask about.
5342 DISPLAY should be either a frame or a display name (a string).
5343 If omitted or nil, that stands for the selected frame's display. */)
5344 (Lisp_Object display)
5346 struct w32_display_info *dpyinfo = check_x_display_info (display);
5348 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
5349 return Qnil;
5351 return Qt;
5354 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
5355 Sx_display_pixel_width, 0, 1, 0,
5356 doc: /* Return the width in pixels of DISPLAY.
5357 The optional argument DISPLAY specifies which display to ask about.
5358 DISPLAY should be either a frame or a display name (a string).
5359 If omitted or nil, that stands for the selected frame's display.
5361 On \"multi-monitor\" setups this refers to the pixel width for all
5362 physical monitors associated with DISPLAY. To get information for
5363 each physical monitor, use `display-monitor-attributes-list'. */)
5364 (Lisp_Object display)
5366 struct w32_display_info *dpyinfo = check_x_display_info (display);
5368 return make_number (x_display_pixel_width (dpyinfo));
5371 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
5372 Sx_display_pixel_height, 0, 1, 0,
5373 doc: /* Return the height in pixels of DISPLAY.
5374 The optional argument DISPLAY specifies which display to ask about.
5375 DISPLAY should be either a frame or a display name (a string).
5376 If omitted or nil, that stands for the selected frame's display.
5378 On \"multi-monitor\" setups this refers to the pixel height for all
5379 physical monitors associated with DISPLAY. To get information for
5380 each physical monitor, use `display-monitor-attributes-list'. */)
5381 (Lisp_Object display)
5383 struct w32_display_info *dpyinfo = check_x_display_info (display);
5385 return make_number (x_display_pixel_height (dpyinfo));
5388 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
5389 0, 1, 0,
5390 doc: /* Return the number of bitplanes of DISPLAY.
5391 The optional argument DISPLAY specifies which display to ask about.
5392 DISPLAY should be either a frame or a display name (a string).
5393 If omitted or nil, that stands for the selected frame's display. */)
5394 (Lisp_Object display)
5396 struct w32_display_info *dpyinfo = check_x_display_info (display);
5398 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
5401 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
5402 0, 1, 0,
5403 doc: /* Return the number of color cells of DISPLAY.
5404 The optional argument DISPLAY specifies which display to ask about.
5405 DISPLAY should be either a frame or a display name (a string).
5406 If omitted or nil, that stands for the selected frame's display. */)
5407 (Lisp_Object display)
5409 struct w32_display_info *dpyinfo = check_x_display_info (display);
5410 int cap;
5412 /* Don't use NCOLORS: it returns incorrect results under remote
5413 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
5414 * overflow and because probably is more meaningful on Windows
5415 * anyway. */
5417 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
5418 return make_number (cap);
5421 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
5422 Sx_server_max_request_size,
5423 0, 1, 0,
5424 doc: /* Return the maximum request size of the server of DISPLAY.
5425 The optional argument DISPLAY specifies which display to ask about.
5426 DISPLAY should be either a frame or a display name (a string).
5427 If omitted or nil, that stands for the selected frame's display. */)
5428 (Lisp_Object display)
5430 return make_number (1);
5433 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
5434 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
5436 \(Labeling every distributor as a "vendor" embodies the false assumption
5437 that operating systems cannot be developed and distributed noncommercially.)
5439 For GNU and Unix systems, this queries the X server software; for
5440 MS-Windows, this queries the OS.
5442 The optional argument TERMINAL specifies which display to ask about.
5443 TERMINAL should be a terminal object, a frame or a display name (a string).
5444 If omitted or nil, that stands for the selected frame's display. */)
5445 (Lisp_Object terminal)
5447 return build_string ("Microsoft Corp.");
5450 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
5451 doc: /* Return the version numbers of the GUI software on TERMINAL.
5452 The value is a list of three integers specifying the version of the GUI
5453 software in use.
5455 For GNU and Unix system, the first 2 numbers are the version of the X
5456 Protocol used on TERMINAL and the 3rd number is the distributor-specific
5457 release number. For MS-Windows, the 3 numbers report the version and
5458 the build number of the OS.
5460 See also the function `x-server-vendor'.
5462 The optional argument TERMINAL specifies which display to ask about.
5463 TERMINAL should be a terminal object, a frame or a display name (a string).
5464 If omitted or nil, that stands for the selected frame's display. */)
5465 (Lisp_Object terminal)
5467 return list3i (w32_major_version, w32_minor_version, w32_build_number);
5470 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
5471 doc: /* Return the number of screens on the server of DISPLAY.
5472 The optional argument DISPLAY specifies which display to ask about.
5473 DISPLAY should be either a frame or a display name (a string).
5474 If omitted or nil, that stands for the selected frame's display. */)
5475 (Lisp_Object display)
5477 return make_number (1);
5480 DEFUN ("x-display-mm-height", Fx_display_mm_height,
5481 Sx_display_mm_height, 0, 1, 0,
5482 doc: /* Return the height in millimeters of DISPLAY.
5483 The optional argument DISPLAY specifies which display to ask about.
5484 DISPLAY should be either a frame or a display name (a string).
5485 If omitted or nil, that stands for the selected frame's display.
5487 On \"multi-monitor\" setups this refers to the height in millimeters for
5488 all physical monitors associated with DISPLAY. To get information
5489 for each physical monitor, use `display-monitor-attributes-list'. */)
5490 (Lisp_Object display)
5492 struct w32_display_info *dpyinfo = check_x_display_info (display);
5493 HDC hdc;
5494 double mm_per_pixel;
5496 hdc = GetDC (NULL);
5497 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5498 / GetDeviceCaps (hdc, VERTRES));
5499 ReleaseDC (NULL, hdc);
5501 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5504 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5505 doc: /* Return the width in millimeters of DISPLAY.
5506 The optional argument DISPLAY specifies which display to ask about.
5507 DISPLAY should be either a frame or a display name (a string).
5508 If omitted or nil, that stands for the selected frame's display.
5510 On \"multi-monitor\" setups this refers to the width in millimeters for
5511 all physical monitors associated with TERMINAL. To get information
5512 for each physical monitor, use `display-monitor-attributes-list'. */)
5513 (Lisp_Object display)
5515 struct w32_display_info *dpyinfo = check_x_display_info (display);
5516 HDC hdc;
5517 double mm_per_pixel;
5519 hdc = GetDC (NULL);
5520 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5521 / GetDeviceCaps (hdc, HORZRES));
5522 ReleaseDC (NULL, hdc);
5524 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5527 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5528 Sx_display_backing_store, 0, 1, 0,
5529 doc: /* Return an indication of whether DISPLAY does backing store.
5530 The value may be `always', `when-mapped', or `not-useful'.
5531 The optional argument DISPLAY specifies which display to ask about.
5532 DISPLAY should be either a frame or a display name (a string).
5533 If omitted or nil, that stands for the selected frame's display. */)
5534 (Lisp_Object display)
5536 return intern ("not-useful");
5539 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5540 Sx_display_visual_class, 0, 1, 0,
5541 doc: /* Return the visual class of DISPLAY.
5542 The value is one of the symbols `static-gray', `gray-scale',
5543 `static-color', `pseudo-color', `true-color', or `direct-color'.
5545 The optional argument DISPLAY specifies which display to ask about.
5546 DISPLAY should be either a frame or a display name (a string).
5547 If omitted or nil, that stands for the selected frame's display. */)
5548 (Lisp_Object display)
5550 struct w32_display_info *dpyinfo = check_x_display_info (display);
5551 Lisp_Object result = Qnil;
5553 if (dpyinfo->has_palette)
5554 result = intern ("pseudo-color");
5555 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5556 result = intern ("static-grey");
5557 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5558 result = intern ("static-color");
5559 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5560 result = intern ("true-color");
5562 return result;
5565 DEFUN ("x-display-save-under", Fx_display_save_under,
5566 Sx_display_save_under, 0, 1, 0,
5567 doc: /* Return t if DISPLAY supports the save-under feature.
5568 The optional argument DISPLAY specifies which display to ask about.
5569 DISPLAY should be either a frame or a display name (a string).
5570 If omitted or nil, that stands for the selected frame's display. */)
5571 (Lisp_Object display)
5573 return Qnil;
5576 static BOOL CALLBACK ALIGN_STACK
5577 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5579 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5581 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5583 return TRUE;
5586 static Lisp_Object
5587 w32_display_monitor_attributes_list (void)
5589 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5590 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5591 int i, n_monitors;
5592 HMONITOR *monitors;
5593 struct gcpro gcpro1, gcpro2, gcpro3;
5595 if (!(enum_display_monitors_fn && get_monitor_info_fn
5596 && monitor_from_window_fn))
5597 return Qnil;
5599 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5600 (LPARAM) &monitor_list)
5601 || NILP (monitor_list))
5602 return Qnil;
5604 n_monitors = 0;
5605 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5606 n_monitors++;
5608 monitors = xmalloc (n_monitors * sizeof (*monitors));
5609 for (i = 0; i < n_monitors; i++)
5611 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5612 monitor_list = XCDR (monitor_list);
5615 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5616 FOR_EACH_FRAME (rest, frame)
5618 struct frame *f = XFRAME (frame);
5620 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5622 HMONITOR monitor =
5623 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5624 MONITOR_DEFAULT_TO_NEAREST);
5626 for (i = 0; i < n_monitors; i++)
5627 if (monitors[i] == monitor)
5628 break;
5630 if (i < n_monitors)
5631 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5635 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5637 for (i = 0; i < n_monitors; i++)
5639 Lisp_Object geometry, workarea, name, attributes = Qnil;
5640 HDC hdc;
5641 int width_mm, height_mm;
5642 struct MONITOR_INFO_EX mi;
5644 mi.cbSize = sizeof (mi);
5645 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5646 continue;
5648 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5649 if (hdc == NULL)
5650 continue;
5651 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5652 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5653 DeleteDC (hdc);
5655 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5656 attributes);
5658 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5660 attributes = Fcons (Fcons (Qname, name), attributes);
5662 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5663 attributes);
5665 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5666 mi.rcWork.right - mi.rcWork.left,
5667 mi.rcWork.bottom - mi.rcWork.top);
5668 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5670 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5671 mi.rcMonitor.right - mi.rcMonitor.left,
5672 mi.rcMonitor.bottom - mi.rcMonitor.top);
5673 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5675 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5676 primary_monitor_attributes = attributes;
5677 else
5678 attributes_list = Fcons (attributes, attributes_list);
5681 if (!NILP (primary_monitor_attributes))
5682 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5684 UNGCPRO;
5686 xfree (monitors);
5688 return attributes_list;
5691 static Lisp_Object
5692 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5694 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5695 HDC hdc;
5696 double mm_per_pixel;
5697 int pixel_width, pixel_height, width_mm, height_mm;
5698 RECT workarea_rect;
5700 /* Fallback: treat (possibly) multiple physical monitors as if they
5701 formed a single monitor as a whole. This should provide a
5702 consistent result at least on single monitor environments. */
5703 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5704 attributes);
5706 frames = Qnil;
5707 FOR_EACH_FRAME (rest, frame)
5709 struct frame *f = XFRAME (frame);
5711 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5712 frames = Fcons (frame, frames);
5714 attributes = Fcons (Fcons (Qframes, frames), attributes);
5716 pixel_width = x_display_pixel_width (dpyinfo);
5717 pixel_height = x_display_pixel_height (dpyinfo);
5719 hdc = GetDC (NULL);
5720 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5721 / GetDeviceCaps (hdc, HORZRES));
5722 width_mm = pixel_width * mm_per_pixel + 0.5;
5723 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5724 / GetDeviceCaps (hdc, VERTRES));
5725 height_mm = pixel_height * mm_per_pixel + 0.5;
5726 ReleaseDC (NULL, hdc);
5727 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5728 attributes);
5730 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5731 we don't care. */
5732 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5733 GetSystemMetrics (SM_YVIRTUALSCREEN),
5734 pixel_width, pixel_height);
5735 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5736 workarea = list4i (workarea_rect.left, workarea_rect.top,
5737 workarea_rect.right - workarea_rect.left,
5738 workarea_rect.bottom - workarea_rect.top);
5739 else
5740 workarea = geometry;
5741 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5743 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5745 return list1 (attributes);
5748 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5749 Sw32_display_monitor_attributes_list,
5750 0, 1, 0,
5751 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5753 The optional argument DISPLAY specifies which display to ask about.
5754 DISPLAY should be either a frame or a display name (a string).
5755 If omitted or nil, that stands for the selected frame's display.
5757 Internal use only, use `display-monitor-attributes-list' instead. */)
5758 (Lisp_Object display)
5760 struct w32_display_info *dpyinfo = check_x_display_info (display);
5761 Lisp_Object attributes_list;
5763 block_input ();
5764 attributes_list = w32_display_monitor_attributes_list ();
5765 if (NILP (attributes_list))
5766 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5767 unblock_input ();
5769 return attributes_list;
5772 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5773 doc: /* Set the sound generated when the bell is rung.
5774 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5775 to use the corresponding system sound for the bell. The 'silent sound
5776 prevents Emacs from making any sound at all.
5777 SOUND is nil to use the normal beep. */)
5778 (Lisp_Object sound)
5780 CHECK_SYMBOL (sound);
5782 if (NILP (sound))
5783 sound_type = 0xFFFFFFFF;
5784 else if (EQ (sound, intern ("asterisk")))
5785 sound_type = MB_ICONASTERISK;
5786 else if (EQ (sound, intern ("exclamation")))
5787 sound_type = MB_ICONEXCLAMATION;
5788 else if (EQ (sound, intern ("hand")))
5789 sound_type = MB_ICONHAND;
5790 else if (EQ (sound, intern ("question")))
5791 sound_type = MB_ICONQUESTION;
5792 else if (EQ (sound, intern ("ok")))
5793 sound_type = MB_OK;
5794 else if (EQ (sound, intern ("silent")))
5795 sound_type = MB_EMACS_SILENT;
5796 else
5797 sound_type = 0xFFFFFFFF;
5799 return sound;
5803 x_screen_planes (register struct frame *f)
5805 return FRAME_DISPLAY_INFO (f)->n_planes;
5808 /* Return the display structure for the display named NAME.
5809 Open a new connection if necessary. */
5811 struct w32_display_info *
5812 x_display_info_for_name (Lisp_Object name)
5814 struct w32_display_info *dpyinfo;
5816 CHECK_STRING (name);
5818 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5819 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5820 return dpyinfo;
5822 /* Use this general default value to start with. */
5823 Vx_resource_name = Vinvocation_name;
5825 validate_x_resource_name ();
5827 dpyinfo = w32_term_init (name, (unsigned char *)0,
5828 SSDATA (Vx_resource_name));
5830 if (dpyinfo == 0)
5831 error ("Cannot connect to server %s", SDATA (name));
5833 XSETFASTINT (Vwindow_system_version, w32_major_version);
5835 return dpyinfo;
5838 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5839 1, 3, 0, doc: /* Open a connection to a display server.
5840 DISPLAY is the name of the display to connect to.
5841 Optional second arg XRM-STRING is a string of resources in xrdb format.
5842 If the optional third arg MUST-SUCCEED is non-nil,
5843 terminate Emacs if we can't open the connection.
5844 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5845 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5847 unsigned char *xrm_option;
5848 struct w32_display_info *dpyinfo;
5850 CHECK_STRING (display);
5852 /* Signal an error in order to encourage correct use from callers.
5853 * If we ever support multiple window systems in the same Emacs,
5854 * we'll need callers to be precise about what window system they
5855 * want. */
5857 if (strcmp (SSDATA (display), "w32") != 0)
5858 error ("The name of the display in this Emacs must be \"w32\"");
5860 /* If initialization has already been done, return now to avoid
5861 overwriting critical parts of one_w32_display_info. */
5862 if (window_system_available (NULL))
5863 return Qnil;
5865 if (! NILP (xrm_string))
5866 CHECK_STRING (xrm_string);
5868 /* Allow color mapping to be defined externally; first look in user's
5869 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5871 Lisp_Object color_file;
5872 struct gcpro gcpro1;
5874 color_file = build_string ("~/rgb.txt");
5876 GCPRO1 (color_file);
5878 if (NILP (Ffile_readable_p (color_file)))
5879 color_file =
5880 Fexpand_file_name (build_string ("rgb.txt"),
5881 Fsymbol_value (intern ("data-directory")));
5883 Vw32_color_map = Fx_load_color_file (color_file);
5885 UNGCPRO;
5887 if (NILP (Vw32_color_map))
5888 Vw32_color_map = w32_default_color_map ();
5890 /* Merge in system logical colors. */
5891 add_system_logical_colors_to_map (&Vw32_color_map);
5893 if (! NILP (xrm_string))
5894 xrm_option = SDATA (xrm_string);
5895 else
5896 xrm_option = (unsigned char *) 0;
5898 /* Use this general default value to start with. */
5899 /* First remove .exe suffix from invocation-name - it looks ugly. */
5901 char basename[ MAX_PATH ], *str;
5903 lispstpcpy (basename, Vinvocation_name);
5904 str = strrchr (basename, '.');
5905 if (str) *str = 0;
5906 Vinvocation_name = build_string (basename);
5908 Vx_resource_name = Vinvocation_name;
5910 validate_x_resource_name ();
5912 /* This is what opens the connection and sets x_current_display.
5913 This also initializes many symbols, such as those used for input. */
5914 dpyinfo = w32_term_init (display, xrm_option,
5915 SSDATA (Vx_resource_name));
5917 if (dpyinfo == 0)
5919 if (!NILP (must_succeed))
5920 fatal ("Cannot connect to server %s.\n",
5921 SDATA (display));
5922 else
5923 error ("Cannot connect to server %s", SDATA (display));
5926 XSETFASTINT (Vwindow_system_version, w32_major_version);
5927 return Qnil;
5930 DEFUN ("x-close-connection", Fx_close_connection,
5931 Sx_close_connection, 1, 1, 0,
5932 doc: /* Close the connection to DISPLAY's server.
5933 For DISPLAY, specify either a frame or a display name (a string).
5934 If DISPLAY is nil, that stands for the selected frame's display. */)
5935 (Lisp_Object display)
5937 struct w32_display_info *dpyinfo = check_x_display_info (display);
5939 if (dpyinfo->reference_count > 0)
5940 error ("Display still has frames on it");
5942 block_input ();
5943 x_destroy_all_bitmaps (dpyinfo);
5945 x_delete_display (dpyinfo);
5946 unblock_input ();
5948 return Qnil;
5951 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5952 doc: /* Return the list of display names that Emacs has connections to. */)
5953 (void)
5955 Lisp_Object result = Qnil;
5956 struct w32_display_info *wdi;
5958 for (wdi = x_display_list; wdi; wdi = wdi->next)
5959 result = Fcons (XCAR (wdi->name_list_element), result);
5961 return result;
5964 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5965 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5966 This function only has an effect on X Windows. With MS Windows, it is
5967 defined but does nothing.
5969 If ON is nil, allow buffering of requests.
5970 Turning on synchronization prohibits the Xlib routines from buffering
5971 requests and seriously degrades performance, but makes debugging much
5972 easier.
5973 The optional second argument TERMINAL specifies which display to act on.
5974 TERMINAL should be a terminal object, a frame or a display name (a string).
5975 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5976 (Lisp_Object on, Lisp_Object display)
5978 return Qnil;
5983 /***********************************************************************
5984 Window properties
5985 ***********************************************************************/
5987 #if 0 /* TODO : port window properties to W32 */
5989 DEFUN ("x-change-window-property", Fx_change_window_property,
5990 Sx_change_window_property, 2, 6, 0,
5991 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5992 PROP must be a string. VALUE may be a string or a list of conses,
5993 numbers and/or strings. If an element in the list is a string, it is
5994 converted to an atom and the value of the Atom is used. If an element
5995 is a cons, it is converted to a 32 bit number where the car is the 16
5996 top bits and the cdr is the lower 16 bits.
5998 FRAME nil or omitted means use the selected frame.
5999 If TYPE is given and non-nil, it is the name of the type of VALUE.
6000 If TYPE is not given or nil, the type is STRING.
6001 FORMAT gives the size in bits of each element if VALUE is a list.
6002 It must be one of 8, 16 or 32.
6003 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6004 If OUTER-P is non-nil, the property is changed for the outer X window of
6005 FRAME. Default is to change on the edit X window. */)
6006 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6007 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6009 struct frame *f = decode_window_system_frame (frame);
6010 Atom prop_atom;
6012 CHECK_STRING (prop);
6013 CHECK_STRING (value);
6015 block_input ();
6016 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6017 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6018 prop_atom, XA_STRING, 8, PropModeReplace,
6019 SDATA (value), SCHARS (value));
6021 /* Make sure the property is set when we return. */
6022 XFlush (FRAME_W32_DISPLAY (f));
6023 unblock_input ();
6025 return value;
6029 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6030 Sx_delete_window_property, 1, 2, 0,
6031 doc: /* Remove window property PROP from X window of FRAME.
6032 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6033 (Lisp_Object prop, Lisp_Object frame)
6035 struct frame *f = decode_window_system_frame (frame);
6036 Atom prop_atom;
6038 CHECK_STRING (prop);
6039 block_input ();
6040 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6041 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6043 /* Make sure the property is removed when we return. */
6044 XFlush (FRAME_W32_DISPLAY (f));
6045 unblock_input ();
6047 return prop;
6051 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6052 1, 6, 0,
6053 doc: /* Value is the value of window property PROP on FRAME.
6054 If FRAME is nil or omitted, use the selected frame.
6056 On X Windows, the following optional arguments are also accepted:
6057 If TYPE is nil or omitted, get the property as a string.
6058 Otherwise TYPE is the name of the atom that denotes the type expected.
6059 If SOURCE is non-nil, get the property on that window instead of from
6060 FRAME. The number 0 denotes the root window.
6061 If DELETE-P is non-nil, delete the property after retrieving it.
6062 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6064 On MS Windows, this function accepts but ignores those optional arguments.
6066 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6067 no value of TYPE (always string in the MS Windows case). */)
6068 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6069 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6071 struct frame *f = decode_window_system_frame (frame);
6072 Atom prop_atom;
6073 int rc;
6074 Lisp_Object prop_value = Qnil;
6075 char *tmp_data = NULL;
6076 Atom actual_type;
6077 int actual_format;
6078 unsigned long actual_size, bytes_remaining;
6080 CHECK_STRING (prop);
6081 block_input ();
6082 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6083 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6084 prop_atom, 0, 0, False, XA_STRING,
6085 &actual_type, &actual_format, &actual_size,
6086 &bytes_remaining, (unsigned char **) &tmp_data);
6087 if (rc == Success)
6089 int size = bytes_remaining;
6091 XFree (tmp_data);
6092 tmp_data = NULL;
6094 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6095 prop_atom, 0, bytes_remaining,
6096 False, XA_STRING,
6097 &actual_type, &actual_format,
6098 &actual_size, &bytes_remaining,
6099 (unsigned char **) &tmp_data);
6100 if (rc == Success)
6101 prop_value = make_string (tmp_data, size);
6103 XFree (tmp_data);
6106 unblock_input ();
6108 return prop_value;
6110 return Qnil;
6113 #endif /* TODO */
6115 /***********************************************************************
6116 Tool tips
6117 ***********************************************************************/
6119 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
6120 Lisp_Object, Lisp_Object);
6121 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6122 Lisp_Object, int, int, int *, int *);
6124 /* The frame of a currently visible tooltip. */
6126 Lisp_Object tip_frame;
6128 /* If non-nil, a timer started that hides the last tooltip when it
6129 fires. */
6131 Lisp_Object tip_timer;
6132 Window tip_window;
6134 /* If non-nil, a vector of 3 elements containing the last args
6135 with which x-show-tip was called. See there. */
6137 Lisp_Object last_show_tip_args;
6140 static void
6141 unwind_create_tip_frame (Lisp_Object frame)
6143 Lisp_Object deleted;
6145 deleted = unwind_create_frame (frame);
6146 if (EQ (deleted, Qt))
6148 tip_window = NULL;
6149 tip_frame = Qnil;
6154 /* Create a frame for a tooltip on the display described by DPYINFO.
6155 PARMS is a list of frame parameters. TEXT is the string to
6156 display in the tip frame. Value is the frame.
6158 Note that functions called here, esp. x_default_parameter can
6159 signal errors, for instance when a specified color name is
6160 undefined. We have to make sure that we're in a consistent state
6161 when this happens. */
6163 static Lisp_Object
6164 x_create_tip_frame (struct w32_display_info *dpyinfo,
6165 Lisp_Object parms, Lisp_Object text)
6167 struct frame *f;
6168 Lisp_Object frame;
6169 Lisp_Object name;
6170 long window_prompting = 0;
6171 int width, height;
6172 ptrdiff_t count = SPECPDL_INDEX ();
6173 struct gcpro gcpro1, gcpro2, gcpro3;
6174 struct kboard *kb;
6175 bool face_change_before = face_change;
6176 Lisp_Object buffer;
6177 struct buffer *old_buffer;
6179 /* Use this general default value to start with until we know if
6180 this frame has a specified name. */
6181 Vx_resource_name = Vinvocation_name;
6183 kb = dpyinfo->terminal->kboard;
6185 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6186 avoid destructive changes behind our caller's back. */
6187 parms = Fcopy_alist (parms);
6189 /* Get the name of the frame to use for resource lookup. */
6190 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6191 if (!STRINGP (name)
6192 && !EQ (name, Qunbound)
6193 && !NILP (name))
6194 error ("Invalid frame name--not a string or nil");
6195 Vx_resource_name = name;
6197 frame = Qnil;
6198 GCPRO3 (parms, name, frame);
6199 /* Make a frame without minibuffer nor mode-line. */
6200 f = make_frame (false);
6201 f->wants_modeline = 0;
6202 XSETFRAME (frame, f);
6204 AUTO_STRING (tip, " *tip*");
6205 buffer = Fget_buffer_create (tip);
6206 /* Use set_window_buffer instead of Fset_window_buffer (see
6207 discussion of bug#11984, bug#12025, bug#12026). */
6208 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, false, false);
6209 old_buffer = current_buffer;
6210 set_buffer_internal_1 (XBUFFER (buffer));
6211 bset_truncate_lines (current_buffer, Qnil);
6212 specbind (Qinhibit_read_only, Qt);
6213 specbind (Qinhibit_modification_hooks, Qt);
6214 Ferase_buffer ();
6215 Finsert (1, &text);
6216 set_buffer_internal_1 (old_buffer);
6218 record_unwind_protect (unwind_create_tip_frame, frame);
6220 /* By setting the output method, we're essentially saying that
6221 the frame is live, as per FRAME_LIVE_P. If we get a signal
6222 from this point on, x_destroy_window might screw up reference
6223 counts etc. */
6224 f->terminal = dpyinfo->terminal;
6225 f->output_method = output_w32;
6226 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6228 FRAME_FONTSET (f) = -1;
6229 fset_icon_name (f, Qnil);
6231 #ifdef GLYPH_DEBUG
6232 image_cache_refcount =
6233 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6234 dpyinfo_refcount = dpyinfo->reference_count;
6235 #endif /* GLYPH_DEBUG */
6236 FRAME_KBOARD (f) = kb;
6237 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6238 f->output_data.w32->explicit_parent = false;
6240 /* Set the name; the functions to which we pass f expect the name to
6241 be set. */
6242 if (EQ (name, Qunbound) || NILP (name))
6244 fset_name (f, build_string (dpyinfo->w32_id_name));
6245 f->explicit_name = false;
6247 else
6249 fset_name (f, name);
6250 f->explicit_name = true;
6251 /* use the frame's title when getting resources for this frame. */
6252 specbind (Qx_resource_name, name);
6255 if (uniscribe_available)
6256 register_font_driver (&uniscribe_font_driver, f);
6257 register_font_driver (&w32font_driver, f);
6259 x_default_parameter (f, parms, Qfont_backend, Qnil,
6260 "fontBackend", "FontBackend", RES_TYPE_STRING);
6262 /* Extract the window parameters from the supplied values
6263 that are needed to determine window geometry. */
6264 x_default_font_parameter (f, parms);
6266 x_default_parameter (f, parms, Qborder_width, make_number (2),
6267 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6268 /* This defaults to 2 in order to match xterm. We recognize either
6269 internalBorderWidth or internalBorder (which is what xterm calls
6270 it). */
6271 if (NILP (Fassq (Qinternal_border_width, parms)))
6273 Lisp_Object value;
6275 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6276 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
6277 if (! EQ (value, Qunbound))
6278 parms = Fcons (Fcons (Qinternal_border_width, value),
6279 parms);
6281 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6282 "internalBorderWidth", "internalBorderWidth",
6283 RES_TYPE_NUMBER);
6284 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
6285 NULL, NULL, RES_TYPE_NUMBER);
6286 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
6287 NULL, NULL, RES_TYPE_NUMBER);
6289 /* Also do the stuff which must be set before the window exists. */
6290 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6291 "foreground", "Foreground", RES_TYPE_STRING);
6292 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6293 "background", "Background", RES_TYPE_STRING);
6294 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6295 "pointerColor", "Foreground", RES_TYPE_STRING);
6296 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6297 "cursorColor", "Foreground", RES_TYPE_STRING);
6298 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6299 "borderColor", "BorderColor", RES_TYPE_STRING);
6301 /* Init faces before x_default_parameter is called for the
6302 scroll-bar-width parameter because otherwise we end up in
6303 init_iterator with a null face cache, which should not happen. */
6304 init_frame_faces (f);
6306 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6307 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6309 window_prompting = x_figure_window_size (f, parms, false);
6311 /* No fringes on tip frame. */
6312 f->fringe_cols = 0;
6313 f->left_fringe_width = 0;
6314 f->right_fringe_width = 0;
6316 block_input ();
6317 my_create_tip_window (f);
6318 unblock_input ();
6320 x_make_gc (f);
6322 x_default_parameter (f, parms, Qauto_raise, Qnil,
6323 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6324 x_default_parameter (f, parms, Qauto_lower, Qnil,
6325 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6326 x_default_parameter (f, parms, Qcursor_type, Qbox,
6327 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6328 /* Process alpha here (Bug#17344). */
6329 x_default_parameter (f, parms, Qalpha, Qnil,
6330 "alpha", "Alpha", RES_TYPE_NUMBER);
6332 /* Dimensions, especially FRAME_LINES (f), must be done via
6333 change_frame_size. Change will not be effected unless different
6334 from the current FRAME_LINES (f). */
6335 width = FRAME_COLS (f);
6336 height = FRAME_LINES (f);
6337 SET_FRAME_COLS (f, 0);
6338 SET_FRAME_LINES (f, 0);
6339 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
6340 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
6342 /* Add `tooltip' frame parameter's default value. */
6343 if (NILP (Fframe_parameter (frame, Qtooltip)))
6344 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
6346 /* Set up faces after all frame parameters are known. This call
6347 also merges in face attributes specified for new frames.
6349 Frame parameters may be changed if .Xdefaults contains
6350 specifications for the default font. For example, if there is an
6351 `Emacs.default.attributeBackground: pink', the `background-color'
6352 attribute of the frame get's set, which let's the internal border
6353 of the tooltip frame appear in pink. Prevent this. */
6355 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
6356 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
6357 Lisp_Object colors = Qnil;
6359 /* Set tip_frame here, so that */
6360 tip_frame = frame;
6361 call2 (Qface_set_after_frame_default, frame, Qnil);
6363 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
6364 colors = Fcons (Fcons (Qbackground_color, bg), colors);
6365 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
6366 colors = Fcons (Fcons (Qforeground_color, fg), colors);
6368 if (!NILP (colors))
6369 Fmodify_frame_parameters (frame, colors);
6372 f->no_split = true;
6374 UNGCPRO;
6376 /* Now that the frame is official, it counts as a reference to
6377 its display. */
6378 FRAME_DISPLAY_INFO (f)->reference_count++;
6379 f->terminal->reference_count++;
6381 /* It is now ok to make the frame official even if we get an error
6382 below. And the frame needs to be on Vframe_list or making it
6383 visible won't work. */
6384 Vframe_list = Fcons (frame, Vframe_list);
6385 f->can_x_set_window_size = true;
6387 /* Setting attributes of faces of the tooltip frame from resources
6388 and similar will set face_change, which leads to the
6389 clearing of all current matrices. Since this isn't necessary
6390 here, avoid it by resetting face_change to the value it
6391 had before we created the tip frame. */
6392 face_change = face_change_before;
6394 /* Discard the unwind_protect. */
6395 return unbind_to (count, frame);
6399 /* Compute where to display tip frame F. PARMS is the list of frame
6400 parameters for F. DX and DY are specified offsets from the current
6401 location of the mouse. WIDTH and HEIGHT are the width and height
6402 of the tooltip. Return coordinates relative to the root window of
6403 the display in *ROOT_X and *ROOT_Y. */
6405 static void
6406 compute_tip_xy (struct frame *f,
6407 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
6408 int width, int height, int *root_x, int *root_y)
6410 Lisp_Object left, top, right, bottom;
6411 int min_x, min_y, max_x, max_y;
6413 /* User-specified position? */
6414 left = Fcdr (Fassq (Qleft, parms));
6415 top = Fcdr (Fassq (Qtop, parms));
6416 right = Fcdr (Fassq (Qright, parms));
6417 bottom = Fcdr (Fassq (Qbottom, parms));
6419 /* Move the tooltip window where the mouse pointer is. Resize and
6420 show it. */
6421 if ((!INTEGERP (left) && !INTEGERP (right))
6422 || (!INTEGERP (top) && !INTEGERP (bottom)))
6424 POINT pt;
6426 /* Default min and max values. */
6427 min_x = 0;
6428 min_y = 0;
6429 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
6430 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
6432 block_input ();
6433 GetCursorPos (&pt);
6434 *root_x = pt.x;
6435 *root_y = pt.y;
6436 unblock_input ();
6438 /* If multiple monitor support is available, constrain the tip onto
6439 the current monitor. This improves the above by allowing negative
6440 co-ordinates if monitor positions are such that they are valid, and
6441 snaps a tooltip onto a single monitor if we are close to the edge
6442 where it would otherwise flow onto the other monitor (or into
6443 nothingness if there is a gap in the overlap). */
6444 if (monitor_from_point_fn && get_monitor_info_fn)
6446 struct MONITOR_INFO info;
6447 HMONITOR monitor
6448 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
6449 info.cbSize = sizeof (info);
6451 if (get_monitor_info_fn (monitor, &info))
6453 min_x = info.rcWork.left;
6454 min_y = info.rcWork.top;
6455 max_x = info.rcWork.right;
6456 max_y = info.rcWork.bottom;
6461 if (INTEGERP (top))
6462 *root_y = XINT (top);
6463 else if (INTEGERP (bottom))
6464 *root_y = XINT (bottom) - height;
6465 else if (*root_y + XINT (dy) <= min_y)
6466 *root_y = min_y; /* Can happen for negative dy */
6467 else if (*root_y + XINT (dy) + height <= max_y)
6468 /* It fits below the pointer */
6469 *root_y += XINT (dy);
6470 else if (height + XINT (dy) + min_y <= *root_y)
6471 /* It fits above the pointer. */
6472 *root_y -= height + XINT (dy);
6473 else
6474 /* Put it on the top. */
6475 *root_y = min_y;
6477 if (INTEGERP (left))
6478 *root_x = XINT (left);
6479 else if (INTEGERP (right))
6480 *root_y = XINT (right) - width;
6481 else if (*root_x + XINT (dx) <= min_x)
6482 *root_x = 0; /* Can happen for negative dx */
6483 else if (*root_x + XINT (dx) + width <= max_x)
6484 /* It fits to the right of the pointer. */
6485 *root_x += XINT (dx);
6486 else if (width + XINT (dx) + min_x <= *root_x)
6487 /* It fits to the left of the pointer. */
6488 *root_x -= width + XINT (dx);
6489 else
6490 /* Put it left justified on the screen -- it ought to fit that way. */
6491 *root_x = min_x;
6495 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
6496 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
6497 A tooltip window is a small window displaying a string.
6499 This is an internal function; Lisp code should call `tooltip-show'.
6501 FRAME nil or omitted means use the selected frame.
6503 PARMS is an optional list of frame parameters which can be
6504 used to change the tooltip's appearance.
6506 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6507 means use the default timeout of 5 seconds.
6509 If the list of frame parameters PARMS contains a `left' parameter,
6510 display the tooltip at that x-position. If the list of frame parameters
6511 PARMS contains no `left' but a `right' parameter, display the tooltip
6512 right-adjusted at that x-position. Otherwise display it at the
6513 x-position of the mouse, with offset DX added (default is 5 if DX isn't
6514 specified).
6516 Likewise for the y-position: If a `top' frame parameter is specified, it
6517 determines the position of the upper edge of the tooltip window. If a
6518 `bottom' parameter but no `top' frame parameter is specified, it
6519 determines the position of the lower edge of the tooltip window.
6520 Otherwise display the tooltip window at the y-position of the mouse,
6521 with offset DY added (default is -10).
6523 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6524 Text larger than the specified size is clipped. */)
6525 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6527 struct frame *f;
6528 struct window *w;
6529 int root_x, root_y;
6530 struct buffer *old_buffer;
6531 struct text_pos pos;
6532 int i, width, height;
6533 bool seen_reversed_p;
6534 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
6535 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6536 ptrdiff_t count = SPECPDL_INDEX ();
6538 specbind (Qinhibit_redisplay, Qt);
6540 GCPRO4 (string, parms, frame, timeout);
6542 CHECK_STRING (string);
6543 f = decode_window_system_frame (frame);
6544 if (NILP (timeout))
6545 timeout = make_number (5);
6546 else
6547 CHECK_NATNUM (timeout);
6549 if (NILP (dx))
6550 dx = make_number (5);
6551 else
6552 CHECK_NUMBER (dx);
6554 if (NILP (dy))
6555 dy = make_number (-10);
6556 else
6557 CHECK_NUMBER (dy);
6559 if (NILP (last_show_tip_args))
6560 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6562 if (!NILP (tip_frame))
6564 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6565 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6566 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6568 if (EQ (frame, last_frame)
6569 && !NILP (Fequal (last_string, string))
6570 && !NILP (Fequal (last_parms, parms)))
6572 struct frame *f = XFRAME (tip_frame);
6574 /* Only DX and DY have changed. */
6575 if (!NILP (tip_timer))
6577 Lisp_Object timer = tip_timer;
6578 tip_timer = Qnil;
6579 call1 (Qcancel_timer, timer);
6582 block_input ();
6583 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6584 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6586 /* Put tooltip in topmost group and in position. */
6587 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6588 root_x, root_y, 0, 0,
6589 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6591 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6592 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6593 0, 0, 0, 0,
6594 SWP_NOMOVE | SWP_NOSIZE
6595 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6597 unblock_input ();
6598 goto start_timer;
6602 /* Hide a previous tip, if any. */
6603 Fx_hide_tip ();
6605 ASET (last_show_tip_args, 0, string);
6606 ASET (last_show_tip_args, 1, frame);
6607 ASET (last_show_tip_args, 2, parms);
6609 /* Add default values to frame parameters. */
6610 if (NILP (Fassq (Qname, parms)))
6611 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6612 if (NILP (Fassq (Qinternal_border_width, parms)))
6613 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6614 if (NILP (Fassq (Qright_divider_width, parms)))
6615 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6616 if (NILP (Fassq (Qbottom_divider_width, parms)))
6617 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6618 if (NILP (Fassq (Qborder_width, parms)))
6619 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6620 if (NILP (Fassq (Qborder_color, parms)))
6621 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6622 if (NILP (Fassq (Qbackground_color, parms)))
6623 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6624 parms);
6626 /* Block input until the tip has been fully drawn, to avoid crashes
6627 when drawing tips in menus. */
6628 block_input ();
6630 /* Create a frame for the tooltip, and record it in the global
6631 variable tip_frame. */
6632 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6633 f = XFRAME (frame);
6635 /* Set up the frame's root window. */
6636 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6637 w->left_col = 0;
6638 w->top_line = 0;
6639 w->pixel_left = 0;
6640 w->pixel_top = 0;
6642 if (CONSP (Vx_max_tooltip_size)
6643 && INTEGERP (XCAR (Vx_max_tooltip_size))
6644 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6645 && INTEGERP (XCDR (Vx_max_tooltip_size))
6646 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6648 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6649 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6651 else
6653 w->total_cols = 80;
6654 w->total_lines = 40;
6657 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6658 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6660 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6661 adjust_frame_glyphs (f);
6662 w->pseudo_window_p = true;
6664 /* Display the tooltip text in a temporary buffer. */
6665 old_buffer = current_buffer;
6666 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6667 bset_truncate_lines (current_buffer, Qnil);
6668 clear_glyph_matrix (w->desired_matrix);
6669 clear_glyph_matrix (w->current_matrix);
6670 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6671 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6673 /* Compute width and height of the tooltip. */
6674 width = height = 0;
6675 seen_reversed_p = false;
6676 for (i = 0; i < w->desired_matrix->nrows; ++i)
6678 struct glyph_row *row = &w->desired_matrix->rows[i];
6679 struct glyph *last;
6680 int row_width;
6682 /* Stop at the first empty row at the end. */
6683 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6684 break;
6686 /* Let the row go over the full width of the frame. */
6687 row->full_width_p = true;
6689 row_width = row->pixel_width;
6690 if (row->used[TEXT_AREA])
6692 if (!row->reversed_p)
6694 /* There's a glyph at the end of rows that is used to
6695 place the cursor there. Don't include the width of
6696 this glyph. */
6697 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6698 if (NILP (last->object))
6699 row_width -= last->pixel_width;
6701 else
6703 /* There could be a stretch glyph at the beginning of R2L
6704 rows that is produced by extend_face_to_end_of_line.
6705 Don't count that glyph. */
6706 struct glyph *g = row->glyphs[TEXT_AREA];
6708 if (g->type == STRETCH_GLYPH && NILP (g->object))
6710 row_width -= g->pixel_width;
6711 seen_reversed_p = true;
6716 height += row->height;
6717 width = max (width, row_width);
6720 /* If we've seen partial-length R2L rows, we need to re-adjust the
6721 tool-tip frame width and redisplay it again, to avoid over-wide
6722 tips due to the stretch glyph that extends R2L lines to full
6723 width of the frame. */
6724 if (seen_reversed_p)
6726 /* PXW: Why do we do the pixel-to-cols conversion only if
6727 seen_reversed_p holds? Don't we have to set other fields of
6728 the window/frame structure?
6730 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6731 not in pixels. */
6732 w->pixel_width = width;
6733 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6734 w->total_cols = width;
6735 FRAME_TOTAL_COLS (f) = width;
6736 SET_FRAME_WIDTH (f, width);
6737 adjust_frame_glyphs (f);
6738 w->pseudo_window_p = 1;
6739 clear_glyph_matrix (w->desired_matrix);
6740 clear_glyph_matrix (w->current_matrix);
6741 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6742 width = height = 0;
6743 /* Recompute width and height of the tooltip. */
6744 for (i = 0; i < w->desired_matrix->nrows; ++i)
6746 struct glyph_row *row = &w->desired_matrix->rows[i];
6747 struct glyph *last;
6748 int row_width;
6750 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6751 break;
6752 row->full_width_p = true;
6753 row_width = row->pixel_width;
6754 if (row->used[TEXT_AREA] && !row->reversed_p)
6756 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6757 if (NILP (last->object))
6758 row_width -= last->pixel_width;
6761 height += row->height;
6762 width = max (width, row_width);
6766 /* Add the frame's internal border to the width and height the w32
6767 window should have. */
6768 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6769 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6771 /* Move the tooltip window where the mouse pointer is. Resize and
6772 show it.
6774 PXW: This should use the frame's pixel coordinates. */
6775 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6778 /* Adjust Window size to take border into account. */
6779 RECT rect;
6780 rect.left = rect.top = 0;
6781 rect.right = width;
6782 rect.bottom = height;
6783 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6784 FRAME_EXTERNAL_MENU_BAR (f));
6786 /* Position and size tooltip, and put it in the topmost group.
6787 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6788 peculiarity of w32 display: without it, some fonts cause the
6789 last character of the tip to be truncated or wrapped around to
6790 the next line. */
6791 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6792 root_x, root_y,
6793 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6794 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6796 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6797 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6798 0, 0, 0, 0,
6799 SWP_NOMOVE | SWP_NOSIZE
6800 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6802 /* Let redisplay know that we have made the frame visible already. */
6803 SET_FRAME_VISIBLE (f, 1);
6805 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6808 /* Draw into the window. */
6809 w->must_be_updated_p = true;
6810 update_single_window (w);
6812 unblock_input ();
6814 /* Restore original current buffer. */
6815 set_buffer_internal_1 (old_buffer);
6816 windows_or_buffers_changed = old_windows_or_buffers_changed;
6818 start_timer:
6819 /* Let the tip disappear after timeout seconds. */
6820 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6821 intern ("x-hide-tip"));
6823 UNGCPRO;
6824 return unbind_to (count, Qnil);
6828 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6829 doc: /* Hide the current tooltip window, if there is any.
6830 Value is t if tooltip was open, nil otherwise. */)
6831 (void)
6833 ptrdiff_t count;
6834 Lisp_Object deleted, frame, timer;
6835 struct gcpro gcpro1, gcpro2;
6837 /* Return quickly if nothing to do. */
6838 if (NILP (tip_timer) && NILP (tip_frame))
6839 return Qnil;
6841 frame = tip_frame;
6842 timer = tip_timer;
6843 GCPRO2 (frame, timer);
6844 tip_frame = tip_timer = deleted = Qnil;
6846 count = SPECPDL_INDEX ();
6847 specbind (Qinhibit_redisplay, Qt);
6848 specbind (Qinhibit_quit, Qt);
6850 if (!NILP (timer))
6851 call1 (Qcancel_timer, timer);
6853 if (FRAMEP (frame))
6855 delete_frame (frame, Qnil);
6856 deleted = Qt;
6859 UNGCPRO;
6860 return unbind_to (count, deleted);
6863 /***********************************************************************
6864 File selection dialog
6865 ***********************************************************************/
6867 #define FILE_NAME_TEXT_FIELD edt1
6868 #define FILE_NAME_COMBO_BOX cmb13
6869 #define FILE_NAME_LIST lst1
6871 /* Callback for altering the behavior of the Open File dialog.
6872 Makes the Filename text field contain "Current Directory" and be
6873 read-only when "Directories" is selected in the filter. This
6874 allows us to work around the fact that the standard Open File
6875 dialog does not support directories. */
6876 static UINT_PTR CALLBACK
6877 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6879 if (msg == WM_NOTIFY)
6881 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6882 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6883 int dropdown_changed;
6884 int dir_index;
6885 #ifdef NTGUI_UNICODE
6886 const int use_unicode = 1;
6887 #else /* !NTGUI_UNICODE */
6888 int use_unicode = w32_unicode_filenames;
6889 #endif /* NTGUI_UNICODE */
6891 /* Detect when the Filter dropdown is changed. */
6892 if (use_unicode)
6893 dropdown_changed =
6894 notify_w->hdr.code == CDN_TYPECHANGE
6895 || notify_w->hdr.code == CDN_INITDONE;
6896 else
6897 dropdown_changed =
6898 notify_a->hdr.code == CDN_TYPECHANGE
6899 || notify_a->hdr.code == CDN_INITDONE;
6900 if (dropdown_changed)
6902 HWND dialog = GetParent (hwnd);
6903 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6904 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6905 int hdr_code;
6907 /* At least on Windows 7, the above attempt to get the window handle
6908 to the File Name Text Field fails. The following code does the
6909 job though. Note that this code is based on my examination of the
6910 window hierarchy using Microsoft Spy++. bk */
6911 if (edit_control == NULL)
6913 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6914 if (tmp)
6916 tmp = GetWindow (tmp, GW_CHILD);
6917 if (tmp)
6918 edit_control = GetWindow (tmp, GW_CHILD);
6922 /* Directories is in index 2. */
6923 if (use_unicode)
6925 dir_index = notify_w->lpOFN->nFilterIndex;
6926 hdr_code = notify_w->hdr.code;
6928 else
6930 dir_index = notify_a->lpOFN->nFilterIndex;
6931 hdr_code = notify_a->hdr.code;
6933 if (dir_index == 2)
6935 if (use_unicode)
6936 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6937 (LPARAM)L"Current Directory");
6938 else
6939 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6940 (LPARAM)"Current Directory");
6941 EnableWindow (edit_control, FALSE);
6942 /* Note that at least on Windows 7, the above call to EnableWindow
6943 disables the window that would ordinarily have focus. If we
6944 do not set focus to some other window here, focus will land in
6945 no man's land and the user will be unable to tab through the
6946 dialog box (pressing tab will only result in a beep).
6947 Avoid that problem by setting focus to the list here. */
6948 if (hdr_code == CDN_INITDONE)
6949 SetFocus (list);
6951 else
6953 /* Don't override default filename on init done. */
6954 if (hdr_code == CDN_TYPECHANGE)
6956 if (use_unicode)
6957 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6958 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6959 else
6960 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6961 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6963 EnableWindow (edit_control, TRUE);
6967 return 0;
6970 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6971 doc: /* Read file name, prompting with PROMPT in directory DIR.
6972 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6973 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6974 or directory must exist.
6976 This function is only defined on NS, MS Windows, and X Windows with the
6977 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6978 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6979 On Windows 7 and later, the file selection dialog "remembers" the last
6980 directory where the user selected a file, and will open that directory
6981 instead of DIR on subsequent invocations of this function with the same
6982 value of DIR as in previous invocations; this is standard Windows behavior. */)
6983 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6985 /* Filter index: 1: All Files, 2: Directories only */
6986 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6987 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6989 Lisp_Object filename = default_filename;
6990 struct frame *f = SELECTED_FRAME ();
6991 BOOL file_opened = FALSE;
6992 Lisp_Object orig_dir = dir;
6993 Lisp_Object orig_prompt = prompt;
6995 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6996 compatibility) we end up with the old file dialogs. Define a big
6997 enough struct for the new dialog to trick GetOpenFileName into
6998 giving us the new dialogs on newer versions of Windows. */
6999 struct {
7000 OPENFILENAMEW details;
7001 #if _WIN32_WINNT < 0x500 /* < win2k */
7002 PVOID pvReserved;
7003 DWORD dwReserved;
7004 DWORD FlagsEx;
7005 #endif /* < win2k */
7006 } new_file_details_w;
7008 #ifdef NTGUI_UNICODE
7009 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
7010 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7011 const int use_unicode = 1;
7012 #else /* not NTGUI_UNICODE */
7013 struct {
7014 OPENFILENAMEA details;
7015 #if _WIN32_WINNT < 0x500 /* < win2k */
7016 PVOID pvReserved;
7017 DWORD dwReserved;
7018 DWORD FlagsEx;
7019 #endif /* < win2k */
7020 } new_file_details_a;
7021 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7022 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7023 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7024 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7025 int use_unicode = w32_unicode_filenames;
7026 wchar_t *prompt_w;
7027 char *prompt_a;
7028 int len;
7029 char fname_ret[MAX_UTF8_PATH];
7030 #endif /* NTGUI_UNICODE */
7032 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
7033 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
7036 struct gcpro gcpro1, gcpro2;
7037 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
7039 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7040 system file encoding expected by the platform APIs (e.g. Cygwin's
7041 POSIX implementation) may not be the same as the encoding expected
7042 by the Windows "ANSI" APIs! */
7044 CHECK_STRING (prompt);
7045 CHECK_STRING (dir);
7047 dir = Fexpand_file_name (dir, Qnil);
7049 if (STRINGP (filename))
7050 filename = Ffile_name_nondirectory (filename);
7051 else
7052 filename = empty_unibyte_string;
7054 #ifdef CYGWIN
7055 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7056 if (SCHARS (filename) > 0)
7057 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7058 #endif
7060 CHECK_STRING (dir);
7061 CHECK_STRING (filename);
7063 /* The code in file_dialog_callback that attempts to set the text
7064 of the file name edit window when handling the CDN_INITDONE
7065 WM_NOTIFY message does not work. Setting filename to "Current
7066 Directory" in the only_dir_p case here does work however. */
7067 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7068 filename = build_string ("Current Directory");
7070 /* Convert the values we've computed so far to system form. */
7071 #ifdef NTGUI_UNICODE
7072 to_unicode (prompt, &prompt);
7073 to_unicode (dir, &dir);
7074 to_unicode (filename, &filename);
7075 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7076 report_file_error ("filename too long", default_filename);
7078 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7079 #else /* !NTGUI_UNICODE */
7080 prompt = ENCODE_FILE (prompt);
7081 dir = ENCODE_FILE (dir);
7082 filename = ENCODE_FILE (filename);
7084 /* We modify these in-place, so make copies for safety. */
7085 dir = Fcopy_sequence (dir);
7086 unixtodos_filename (SDATA (dir));
7087 filename = Fcopy_sequence (filename);
7088 unixtodos_filename (SDATA (filename));
7089 if (SBYTES (filename) >= MAX_UTF8_PATH)
7090 report_file_error ("filename too long", default_filename);
7091 if (w32_unicode_filenames)
7093 filename_to_utf16 (SSDATA (dir), dir_w);
7094 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7096 /* filename_to_utf16 sets errno to ENOENT when the file
7097 name is too long or cannot be converted to UTF-16. */
7098 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7099 report_file_error ("filename too long", default_filename);
7101 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7102 SSDATA (prompt), -1, NULL, 0);
7103 if (len > 32768)
7104 len = 32768;
7105 prompt_w = alloca (len * sizeof (wchar_t));
7106 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7107 SSDATA (prompt), -1, prompt_w, len);
7109 else
7111 filename_to_ansi (SSDATA (dir), dir_a);
7112 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7114 /* filename_to_ansi sets errno to ENOENT when the file
7115 name is too long or cannot be converted to UTF-16. */
7116 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7117 report_file_error ("filename too long", default_filename);
7119 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7120 SSDATA (prompt), -1, NULL, 0);
7121 if (len > 32768)
7122 len = 32768;
7123 prompt_w = alloca (len * sizeof (wchar_t));
7124 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7125 SSDATA (prompt), -1, prompt_w, len);
7126 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7127 if (len > 32768)
7128 len = 32768;
7129 prompt_a = alloca (len);
7130 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7132 #endif /* NTGUI_UNICODE */
7134 /* Fill in the structure for the call to GetOpenFileName below.
7135 For NTGUI_UNICODE builds (which run only on NT), we just use
7136 the actual size of the structure. For non-NTGUI_UNICODE
7137 builds, we tell the OS we're using an old version of the
7138 structure if the OS isn't new enough to support the newer
7139 version. */
7140 if (use_unicode)
7142 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7143 if (w32_major_version > 4 && w32_major_version < 95)
7144 file_details_w->lStructSize = sizeof (new_file_details_w);
7145 else
7146 file_details_w->lStructSize = sizeof (*file_details_w);
7147 /* Set up the inout parameter for the selected file name. */
7148 file_details_w->lpstrFile = filename_buf_w;
7149 file_details_w->nMaxFile =
7150 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7151 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7152 /* Undocumented Bug in Common File Dialog:
7153 If a filter is not specified, shell links are not resolved. */
7154 file_details_w->lpstrFilter = filter_w;
7155 #ifdef NTGUI_UNICODE
7156 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7157 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7158 #else
7159 file_details_w->lpstrInitialDir = dir_w;
7160 file_details_w->lpstrTitle = prompt_w;
7161 #endif
7162 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7163 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7164 | OFN_EXPLORER | OFN_ENABLEHOOK);
7165 if (!NILP (mustmatch))
7167 /* Require that the path to the parent directory exists. */
7168 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7169 /* If we are looking for a file, require that it exists. */
7170 if (NILP (only_dir_p))
7171 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7174 #ifndef NTGUI_UNICODE
7175 else
7177 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7178 if (w32_major_version > 4 && w32_major_version < 95)
7179 file_details_a->lStructSize = sizeof (new_file_details_a);
7180 else
7181 file_details_a->lStructSize = sizeof (*file_details_a);
7182 file_details_a->lpstrFile = filename_buf_a;
7183 file_details_a->nMaxFile =
7184 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7185 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7186 file_details_a->lpstrFilter = filter_a;
7187 file_details_a->lpstrInitialDir = dir_a;
7188 file_details_a->lpstrTitle = prompt_a;
7189 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7190 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7191 | OFN_EXPLORER | OFN_ENABLEHOOK);
7192 if (!NILP (mustmatch))
7194 /* Require that the path to the parent directory exists. */
7195 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7196 /* If we are looking for a file, require that it exists. */
7197 if (NILP (only_dir_p))
7198 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7201 #endif /* !NTGUI_UNICODE */
7204 int count = SPECPDL_INDEX ();
7205 /* Prevent redisplay. */
7206 specbind (Qinhibit_redisplay, Qt);
7207 block_input ();
7208 if (use_unicode)
7210 file_details_w->lpfnHook = file_dialog_callback;
7212 file_opened = GetOpenFileNameW (file_details_w);
7214 #ifndef NTGUI_UNICODE
7215 else
7217 file_details_a->lpfnHook = file_dialog_callback;
7219 file_opened = GetOpenFileNameA (file_details_a);
7221 #endif /* !NTGUI_UNICODE */
7222 unblock_input ();
7223 unbind_to (count, Qnil);
7226 if (file_opened)
7228 /* Get an Emacs string from the value Windows gave us. */
7229 #ifdef NTGUI_UNICODE
7230 filename = from_unicode_buffer (filename_buf_w);
7231 #else /* !NTGUI_UNICODE */
7232 if (use_unicode)
7233 filename_from_utf16 (filename_buf_w, fname_ret);
7234 else
7235 filename_from_ansi (filename_buf_a, fname_ret);
7236 dostounix_filename (fname_ret);
7237 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7238 #endif /* NTGUI_UNICODE */
7240 #ifdef CYGWIN
7241 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7242 #endif /* CYGWIN */
7244 /* Strip the dummy filename off the end of the string if we
7245 added it to select a directory. */
7246 if ((use_unicode && file_details_w->nFilterIndex == 2)
7247 #ifndef NTGUI_UNICODE
7248 || (!use_unicode && file_details_a->nFilterIndex == 2)
7249 #endif
7251 filename = Ffile_name_directory (filename);
7253 /* User canceled the dialog without making a selection. */
7254 else if (!CommDlgExtendedError ())
7255 filename = Qnil;
7256 /* An error occurred, fallback on reading from the mini-buffer. */
7257 else
7258 filename = Fcompleting_read (
7259 orig_prompt,
7260 intern ("read-file-name-internal"),
7261 orig_dir,
7262 mustmatch,
7263 orig_dir,
7264 Qfile_name_history,
7265 default_filename,
7266 Qnil);
7268 UNGCPRO;
7271 /* Make "Cancel" equivalent to C-g. */
7272 if (NILP (filename))
7273 Fsignal (Qquit, Qnil);
7275 RETURN_UNGCPRO (filename);
7279 #ifdef WINDOWSNT
7280 /* Moving files to the system recycle bin.
7281 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
7282 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
7283 Ssystem_move_file_to_trash, 1, 1, 0,
7284 doc: /* Move file or directory named FILENAME to the recycle bin. */)
7285 (Lisp_Object filename)
7287 Lisp_Object handler;
7288 Lisp_Object encoded_file;
7289 Lisp_Object operation;
7291 operation = Qdelete_file;
7292 if (!NILP (Ffile_directory_p (filename))
7293 && NILP (Ffile_symlink_p (filename)))
7295 operation = intern ("delete-directory");
7296 filename = Fdirectory_file_name (filename);
7299 /* Must have fully qualified file names for moving files to Recycle
7300 Bin. */
7301 filename = Fexpand_file_name (filename, Qnil);
7303 handler = Ffind_file_name_handler (filename, operation);
7304 if (!NILP (handler))
7305 return call2 (handler, operation, filename);
7306 else
7308 const char * path;
7309 int result;
7311 encoded_file = ENCODE_FILE (filename);
7313 path = map_w32_filename (SDATA (encoded_file), NULL);
7315 /* The Unicode version of SHFileOperation is not supported on
7316 Windows 9X. */
7317 if (w32_unicode_filenames && os_subtype != OS_9X)
7319 SHFILEOPSTRUCTW file_op_w;
7320 /* We need one more element beyond MAX_PATH because this is
7321 a list of file names, with the last element double-null
7322 terminated. */
7323 wchar_t tmp_path_w[MAX_PATH + 1];
7325 memset (tmp_path_w, 0, sizeof (tmp_path_w));
7326 filename_to_utf16 (path, tmp_path_w);
7328 /* On Windows, write permission is required to delete/move files. */
7329 _wchmod (tmp_path_w, 0666);
7331 memset (&file_op_w, 0, sizeof (file_op_w));
7332 file_op_w.hwnd = HWND_DESKTOP;
7333 file_op_w.wFunc = FO_DELETE;
7334 file_op_w.pFrom = tmp_path_w;
7335 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7336 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7337 file_op_w.fAnyOperationsAborted = FALSE;
7339 result = SHFileOperationW (&file_op_w);
7341 else
7343 SHFILEOPSTRUCTA file_op_a;
7344 char tmp_path_a[MAX_PATH + 1];
7346 memset (tmp_path_a, 0, sizeof (tmp_path_a));
7347 filename_to_ansi (path, tmp_path_a);
7349 /* If a file cannot be represented in ANSI codepage, don't
7350 let them inadvertently delete other files because some
7351 characters are interpreted as a wildcards. */
7352 if (_mbspbrk (tmp_path_a, "?*"))
7353 result = ERROR_FILE_NOT_FOUND;
7354 else
7356 _chmod (tmp_path_a, 0666);
7358 memset (&file_op_a, 0, sizeof (file_op_a));
7359 file_op_a.hwnd = HWND_DESKTOP;
7360 file_op_a.wFunc = FO_DELETE;
7361 file_op_a.pFrom = tmp_path_a;
7362 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7363 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7364 file_op_a.fAnyOperationsAborted = FALSE;
7366 result = SHFileOperationA (&file_op_a);
7369 if (result != 0)
7370 report_file_error ("Removing old name", list1 (filename));
7372 return Qnil;
7375 #endif /* WINDOWSNT */
7378 /***********************************************************************
7379 w32 specialized functions
7380 ***********************************************************************/
7382 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
7383 Sw32_send_sys_command, 1, 2, 0,
7384 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
7385 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
7386 to minimize), #xf120 to restore frame to original size, and #xf100
7387 to activate the menubar for keyboard access. #xf140 activates the
7388 screen saver if defined.
7390 If optional parameter FRAME is not specified, use selected frame. */)
7391 (Lisp_Object command, Lisp_Object frame)
7393 struct frame *f = decode_window_system_frame (frame);
7395 CHECK_NUMBER (command);
7397 if (FRAME_W32_P (f))
7398 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
7400 return Qnil;
7403 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
7404 doc: /* Get Windows to perform OPERATION on DOCUMENT.
7405 This is a wrapper around the ShellExecute system function, which
7406 invokes the application registered to handle OPERATION for DOCUMENT.
7408 OPERATION is either nil or a string that names a supported operation.
7409 What operations can be used depends on the particular DOCUMENT and its
7410 handler application, but typically it is one of the following common
7411 operations:
7413 \"open\" - open DOCUMENT, which could be a file, a directory, or an
7414 executable program (application). If it is an application,
7415 that application is launched in the current buffer's default
7416 directory. Otherwise, the application associated with
7417 DOCUMENT is launched in the buffer's default directory.
7418 \"opennew\" - like \"open\", but instruct the application to open
7419 DOCUMENT in a new window.
7420 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
7421 \"print\" - print DOCUMENT, which must be a file.
7422 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
7423 The printer should be provided in PARAMETERS, see below.
7424 \"explore\" - start the Windows Explorer on DOCUMENT.
7425 \"edit\" - launch an editor and open DOCUMENT for editing; which
7426 editor is launched depends on the association for the
7427 specified DOCUMENT.
7428 \"find\" - initiate search starting from DOCUMENT, which must specify
7429 a directory.
7430 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
7431 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
7432 the clipboard.
7433 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
7434 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
7435 which must be a directory.
7436 \"pastelink\"
7437 - create a shortcut in DOCUMENT (which must be a directory)
7438 the file or directory whose name is in the clipboard.
7439 \"runas\" - run DOCUMENT, which must be an excutable file, with
7440 elevated privileges (a.k.a. \"as Administrator\").
7441 \"properties\"
7442 - open the property sheet dialog for DOCUMENT.
7443 nil - invoke the default OPERATION, or \"open\" if default is
7444 not defined or unavailable.
7446 DOCUMENT is typically the name of a document file or a URL, but can
7447 also be an executable program to run, or a directory to open in the
7448 Windows Explorer. If it is a file or a directory, it must be a local
7449 one; this function does not support remote file names.
7451 If DOCUMENT is an executable program, the optional third arg PARAMETERS
7452 can be a string containing command line parameters, separated by blanks,
7453 that will be passed to the program. Some values of OPERATION also require
7454 parameters (e.g., \"printto\" requires the printer address). Otherwise,
7455 PARAMETERS should be nil or unspecified. Note that double quote characters
7456 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
7458 Optional fourth argument SHOW-FLAG can be used to control how the
7459 application will be displayed when it is invoked. If SHOW-FLAG is nil
7460 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
7461 specified, otherwise it is an integer between 0 and 11 representing
7462 a ShowWindow flag:
7464 0 - start hidden
7465 1 - start as normal-size window
7466 3 - start in a maximized window
7467 6 - start in a minimized window
7468 10 - start as the application itself specifies; this is the default. */)
7469 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
7471 char *errstr;
7472 Lisp_Object current_dir = BVAR (current_buffer, directory);;
7473 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
7474 #ifdef CYGWIN
7475 intptr_t result;
7476 #else
7477 int use_unicode = w32_unicode_filenames;
7478 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
7479 Lisp_Object absdoc, handler;
7480 BOOL success;
7481 struct gcpro gcpro1;
7482 #endif
7484 CHECK_STRING (document);
7486 #ifdef CYGWIN
7487 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
7488 document = Fcygwin_convert_file_name_to_windows (document, Qt);
7490 /* Encode filename, current directory and parameters. */
7491 current_dir = GUI_ENCODE_FILE (current_dir);
7492 document = GUI_ENCODE_FILE (document);
7493 doc_w = GUI_SDATA (document);
7494 if (STRINGP (parameters))
7496 parameters = GUI_ENCODE_SYSTEM (parameters);
7497 params_w = GUI_SDATA (parameters);
7499 if (STRINGP (operation))
7501 operation = GUI_ENCODE_SYSTEM (operation);
7502 ops_w = GUI_SDATA (operation);
7504 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7505 GUI_SDATA (current_dir),
7506 (INTEGERP (show_flag)
7507 ? XINT (show_flag) : SW_SHOWDEFAULT));
7509 if (result > 32)
7510 return Qt;
7512 switch (result)
7514 case SE_ERR_ACCESSDENIED:
7515 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7516 break;
7517 case SE_ERR_ASSOCINCOMPLETE:
7518 case SE_ERR_NOASSOC:
7519 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7520 break;
7521 case SE_ERR_DDEBUSY:
7522 case SE_ERR_DDEFAIL:
7523 errstr = w32_strerror (ERROR_DDE_FAIL);
7524 break;
7525 case SE_ERR_DDETIMEOUT:
7526 errstr = w32_strerror (ERROR_TIMEOUT);
7527 break;
7528 case SE_ERR_DLLNOTFOUND:
7529 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7530 break;
7531 case SE_ERR_FNF:
7532 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7533 break;
7534 case SE_ERR_OOM:
7535 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7536 break;
7537 case SE_ERR_PNF:
7538 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7539 break;
7540 case SE_ERR_SHARE:
7541 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7542 break;
7543 default:
7544 errstr = w32_strerror (0);
7545 break;
7548 #else /* !CYGWIN */
7550 const char file_url_str[] = "file:///";
7551 const int file_url_len = sizeof (file_url_str) - 1;
7552 int doclen;
7554 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
7556 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
7557 start a thread in some rare system configurations, for
7558 unknown reasons. That thread is started in the context of
7559 the Emacs process, but out of control of our code, and seems
7560 to never exit afterwards. Each such thread reserves 8MB of
7561 stack space (because that's the value recorded in the Emacs
7562 executable at link time: Emacs needs a large stack). So a
7563 large enough number of invocations of w32-shell-execute can
7564 potentially cause the Emacs process to run out of available
7565 address space, which is nasty. To work around this, we
7566 convert such URLs to local file names, which seems to prevent
7567 those threads from starting. See bug #20220. */
7568 char *p = SSDATA (document) + file_url_len;
7570 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
7571 document = Fsubstring_no_properties (document,
7572 make_number (file_url_len), Qnil);
7574 /* We have a situation here. If DOCUMENT is a relative file name,
7575 but its name includes leading directories, i.e. it lives not in
7576 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7577 will fail to find it. So we need to make the file name is
7578 absolute. But DOCUMENT does not have to be a file, it can be a
7579 URL, for example. So we make it absolute only if it is an
7580 existing file; if it is a file that does not exist, tough. */
7581 GCPRO1 (absdoc);
7582 absdoc = Fexpand_file_name (document, Qnil);
7583 /* Don't call file handlers for file-exists-p, since they might
7584 attempt to access the file, which could fail or produce undesired
7585 consequences, see bug#16558 for an example. */
7586 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7587 if (NILP (handler))
7589 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7591 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7593 /* ShellExecute fails if DOCUMENT is a UNC with forward
7594 slashes (expand-file-name above converts all backslashes
7595 to forward slashes). Now that we know DOCUMENT is a
7596 file, we can mirror all forward slashes into backslashes. */
7597 unixtodos_filename (SSDATA (absdoc_encoded));
7598 document = absdoc_encoded;
7600 else
7601 document = ENCODE_FILE (document);
7603 else
7604 document = ENCODE_FILE (document);
7605 UNGCPRO;
7607 current_dir = ENCODE_FILE (current_dir);
7608 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
7609 be a URL that is not limited to MAX_PATH chararcters. */
7610 doclen = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7611 SSDATA (document), -1, NULL, 0);
7612 doc_w = xmalloc (doclen * sizeof (wchar_t));
7613 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7614 SSDATA (document), -1, doc_w, doclen);
7615 if (use_unicode)
7617 wchar_t current_dir_w[MAX_PATH];
7618 SHELLEXECUTEINFOW shexinfo_w;
7620 /* Encode the current directory and parameters, and convert
7621 operation to UTF-16. */
7622 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7623 if (STRINGP (parameters))
7625 int len;
7627 parameters = ENCODE_SYSTEM (parameters);
7628 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7629 SSDATA (parameters), -1, NULL, 0);
7630 if (len > 32768)
7631 len = 32768;
7632 params_w = alloca (len * sizeof (wchar_t));
7633 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7634 SSDATA (parameters), -1, params_w, len);
7635 params_w[len - 1] = 0;
7637 if (STRINGP (operation))
7639 /* Assume OPERATION is pure ASCII. */
7640 const char *s = SSDATA (operation);
7641 wchar_t *d;
7642 int len = SBYTES (operation) + 1;
7644 if (len > 32768)
7645 len = 32768;
7646 d = ops_w = alloca (len * sizeof (wchar_t));
7647 while (d < ops_w + len - 1)
7648 *d++ = *s++;
7649 *d = 0;
7652 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7653 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7654 able to invoke verbs from shortcut menu extensions, not just
7655 static verbs listed in the Registry. */
7656 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7657 shexinfo_w.cbSize = sizeof (shexinfo_w);
7658 shexinfo_w.fMask =
7659 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7660 shexinfo_w.hwnd = NULL;
7661 shexinfo_w.lpVerb = ops_w;
7662 shexinfo_w.lpFile = doc_w;
7663 shexinfo_w.lpParameters = params_w;
7664 shexinfo_w.lpDirectory = current_dir_w;
7665 shexinfo_w.nShow =
7666 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7667 success = ShellExecuteExW (&shexinfo_w);
7668 xfree (doc_w);
7670 else
7672 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7673 SHELLEXECUTEINFOA shexinfo_a;
7674 int codepage = codepage_for_filenames (NULL);
7675 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
7676 NULL, NULL);
7678 doc_a = xmalloc (ldoc_a);
7679 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
7680 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7681 if (STRINGP (parameters))
7683 parameters = ENCODE_SYSTEM (parameters);
7684 params_a = SSDATA (parameters);
7686 if (STRINGP (operation))
7688 /* Assume OPERATION is pure ASCII. */
7689 ops_a = SSDATA (operation);
7691 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7692 shexinfo_a.cbSize = sizeof (shexinfo_a);
7693 shexinfo_a.fMask =
7694 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7695 shexinfo_a.hwnd = NULL;
7696 shexinfo_a.lpVerb = ops_a;
7697 shexinfo_a.lpFile = doc_a;
7698 shexinfo_a.lpParameters = params_a;
7699 shexinfo_a.lpDirectory = current_dir_a;
7700 shexinfo_a.nShow =
7701 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7702 success = ShellExecuteExA (&shexinfo_a);
7703 xfree (doc_w);
7704 xfree (doc_a);
7707 if (success)
7708 return Qt;
7710 errstr = w32_strerror (0);
7712 #endif /* !CYGWIN */
7714 /* The error string might be encoded in the locale's encoding. */
7715 if (!NILP (Vlocale_coding_system))
7717 Lisp_Object decoded =
7718 code_convert_string_norecord (build_unibyte_string (errstr),
7719 Vlocale_coding_system, 0);
7720 errstr = SSDATA (decoded);
7722 error ("ShellExecute failed: %s", errstr);
7725 /* Lookup virtual keycode from string representing the name of a
7726 non-ascii keystroke into the corresponding virtual key, using
7727 lispy_function_keys. */
7728 static int
7729 lookup_vk_code (char *key)
7731 int i;
7733 for (i = 0; i < 256; i++)
7734 if (lispy_function_keys[i]
7735 && strcmp (lispy_function_keys[i], key) == 0)
7736 return i;
7738 return -1;
7741 /* Convert a one-element vector style key sequence to a hot key
7742 definition. */
7743 static Lisp_Object
7744 w32_parse_hot_key (Lisp_Object key)
7746 /* Copied from Fdefine_key and store_in_keymap. */
7747 register Lisp_Object c;
7748 int vk_code;
7749 int lisp_modifiers;
7750 int w32_modifiers;
7751 struct gcpro gcpro1;
7753 CHECK_VECTOR (key);
7755 if (ASIZE (key) != 1)
7756 return Qnil;
7758 GCPRO1 (key);
7760 c = AREF (key, 0);
7762 if (CONSP (c) && lucid_event_type_list_p (c))
7763 c = Fevent_convert_list (c);
7765 UNGCPRO;
7767 if (! INTEGERP (c) && ! SYMBOLP (c))
7768 error ("Key definition is invalid");
7770 /* Work out the base key and the modifiers. */
7771 if (SYMBOLP (c))
7773 c = parse_modifiers (c);
7774 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7775 c = Fcar (c);
7776 if (!SYMBOLP (c))
7777 emacs_abort ();
7778 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7780 else if (INTEGERP (c))
7782 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7783 /* Many ascii characters are their own virtual key code. */
7784 vk_code = XINT (c) & CHARACTERBITS;
7787 if (vk_code < 0 || vk_code > 255)
7788 return Qnil;
7790 if ((lisp_modifiers & meta_modifier) != 0
7791 && !NILP (Vw32_alt_is_meta))
7792 lisp_modifiers |= alt_modifier;
7794 /* Supply defs missing from mingw32. */
7795 #ifndef MOD_ALT
7796 #define MOD_ALT 0x0001
7797 #define MOD_CONTROL 0x0002
7798 #define MOD_SHIFT 0x0004
7799 #define MOD_WIN 0x0008
7800 #endif
7802 /* Convert lisp modifiers to Windows hot-key form. */
7803 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7804 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7805 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7806 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7808 return HOTKEY (vk_code, w32_modifiers);
7811 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7812 Sw32_register_hot_key, 1, 1, 0,
7813 doc: /* Register KEY as a hot-key combination.
7814 Certain key combinations like Alt-Tab are reserved for system use on
7815 Windows, and therefore are normally intercepted by the system. However,
7816 most of these key combinations can be received by registering them as
7817 hot-keys, overriding their special meaning.
7819 KEY must be a one element key definition in vector form that would be
7820 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7821 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7822 is always interpreted as the Windows modifier keys.
7824 The return value is the hotkey-id if registered, otherwise nil. */)
7825 (Lisp_Object key)
7827 key = w32_parse_hot_key (key);
7829 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7831 /* Reuse an empty slot if possible. */
7832 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7834 /* Safe to add new key to list, even if we have focus. */
7835 if (NILP (item))
7836 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7837 else
7838 XSETCAR (item, key);
7840 /* Notify input thread about new hot-key definition, so that it
7841 takes effect without needing to switch focus. */
7842 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7843 (WPARAM) XINT (key), 0);
7846 return key;
7849 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7850 Sw32_unregister_hot_key, 1, 1, 0,
7851 doc: /* Unregister KEY as a hot-key combination. */)
7852 (Lisp_Object key)
7854 Lisp_Object item;
7856 if (!INTEGERP (key))
7857 key = w32_parse_hot_key (key);
7859 item = Fmemq (key, w32_grabbed_keys);
7861 if (!NILP (item))
7863 LPARAM lparam;
7865 eassert (CONSP (item));
7866 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
7867 so that it works in a --with-wide-int build as well. */
7868 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
7870 /* Notify input thread about hot-key definition being removed, so
7871 that it takes effect without needing focus switch. */
7872 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7873 (WPARAM) XINT (XCAR (item)), lparam))
7875 MSG msg;
7876 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7878 return Qt;
7880 return Qnil;
7883 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7884 Sw32_registered_hot_keys, 0, 0, 0,
7885 doc: /* Return list of registered hot-key IDs. */)
7886 (void)
7888 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7891 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7892 Sw32_reconstruct_hot_key, 1, 1, 0,
7893 doc: /* Convert hot-key ID to a lisp key combination.
7894 usage: (w32-reconstruct-hot-key ID) */)
7895 (Lisp_Object hotkeyid)
7897 int vk_code, w32_modifiers;
7898 Lisp_Object key;
7900 CHECK_NUMBER (hotkeyid);
7902 vk_code = HOTKEY_VK_CODE (hotkeyid);
7903 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7905 if (vk_code < 256 && lispy_function_keys[vk_code])
7906 key = intern (lispy_function_keys[vk_code]);
7907 else
7908 key = make_number (vk_code);
7910 key = Fcons (key, Qnil);
7911 if (w32_modifiers & MOD_SHIFT)
7912 key = Fcons (Qshift, key);
7913 if (w32_modifiers & MOD_CONTROL)
7914 key = Fcons (Qctrl, key);
7915 if (w32_modifiers & MOD_ALT)
7916 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7917 if (w32_modifiers & MOD_WIN)
7918 key = Fcons (Qhyper, key);
7920 return key;
7923 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7924 Sw32_toggle_lock_key, 1, 2, 0,
7925 doc: /* Toggle the state of the lock key KEY.
7926 KEY can be `capslock', `kp-numlock', or `scroll'.
7927 If the optional parameter NEW-STATE is a number, then the state of KEY
7928 is set to off if the low bit of NEW-STATE is zero, otherwise on.
7929 If NEW-STATE is omitted or nil, the function toggles the state,
7931 Value is the new state of the key, or nil if the function failed
7932 to change the state. */)
7933 (Lisp_Object key, Lisp_Object new_state)
7935 int vk_code;
7936 LPARAM lparam;
7938 if (EQ (key, intern ("capslock")))
7939 vk_code = VK_CAPITAL;
7940 else if (EQ (key, intern ("kp-numlock")))
7941 vk_code = VK_NUMLOCK;
7942 else if (EQ (key, intern ("scroll")))
7943 vk_code = VK_SCROLL;
7944 else
7945 return Qnil;
7947 if (!dwWindowsThreadId)
7948 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7950 if (NILP (new_state))
7951 lparam = -1;
7952 else
7953 lparam = (XUINT (new_state)) & 1;
7954 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7955 (WPARAM) vk_code, lparam))
7957 MSG msg;
7958 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7959 return make_number (msg.wParam);
7961 return Qnil;
7964 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7965 2, 2, 0,
7966 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7968 This is a direct interface to the Windows API FindWindow function. */)
7969 (Lisp_Object class, Lisp_Object name)
7971 HWND hnd;
7973 if (!NILP (class))
7974 CHECK_STRING (class);
7975 if (!NILP (name))
7976 CHECK_STRING (name);
7978 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7979 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7980 if (!hnd)
7981 return Qnil;
7982 return Qt;
7985 DEFUN ("w32-frame-menu-bar-size", Fw32_frame_menu_bar_size, Sw32_frame_menu_bar_size, 0, 1, 0,
7986 doc: /* Return sizes of menu bar on frame FRAME.
7987 The return value is a list of four elements: The current width and
7988 height of FRAME's menu bar in pixels, the height of one menu bar line in
7989 a wrapped menu bar in pixels, and the height of a single line menu bar
7990 in pixels.
7992 If FRAME is omitted or nil, the selected frame is used. */)
7993 (Lisp_Object frame)
7995 struct frame *f = decode_any_frame (frame);
7996 MENUBARINFO menu_bar;
7997 int width, height, single_height, wrapped_height;
7999 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8000 return Qnil;
8002 block_input ();
8004 single_height = GetSystemMetrics (SM_CYMENU);
8005 wrapped_height = GetSystemMetrics (SM_CYMENUSIZE);
8006 menu_bar.cbSize = sizeof (menu_bar);
8007 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8008 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8009 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8010 width = menu_bar.rcBar.right - menu_bar.rcBar.left;
8011 height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8013 unblock_input ();
8015 return list4 (make_number (width), make_number (height),
8016 make_number (wrapped_height), make_number (single_height));
8019 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
8020 doc: /* Return boundary rectangle of FRAME in screen coordinates.
8021 FRAME must be a live frame and defaults to the selected one.
8023 The boundary rectangle is a list of four elements, specifying the left,
8024 top, right and bottom screen coordinates of FRAME including menu and
8025 title bar and decorations. Optional argument CLIENT non-nil means to
8026 return the boundaries of the client rectangle which excludes menu and
8027 title bar and decorations. */)
8028 (Lisp_Object frame, Lisp_Object client)
8030 struct frame *f = decode_live_frame (frame);
8031 RECT rect;
8033 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8034 return Qnil;
8036 block_input ();
8038 if (!NILP (client))
8039 GetClientRect (FRAME_W32_WINDOW (f), &rect);
8040 else
8041 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
8043 unblock_input ();
8045 return list4 (make_number (rect.left), make_number (rect.top),
8046 make_number (rect.right), make_number (rect.bottom));
8049 DEFUN ("x-frame-geometry", Fx_frame_geometry, Sx_frame_geometry, 0, 1, 0,
8050 doc: /* Return geometric attributes of frame FRAME.
8051 FRAME must be a live frame and defaults to the selected one.
8053 The return value is an association list containing the following
8054 elements (all size values are in pixels).
8056 - `frame-outer-size' is a cons of the outer width and height of FRAME.
8057 The outer size includes the title bar and the external borders as well
8058 as any menu and/or tool bar of frame.
8060 - `border' is a cons of the horizontal and vertical width of FRAME's
8061 external borders.
8063 - `title-bar-height' is the height of the title bar of FRAME.
8065 - `menu-bar-external' if t means the menu bar is by default external
8066 (not included in the inner size of FRAME).
8068 - `menu-bar-size' is a cons of the width and height of the menu bar of
8069 FRAME.
8071 - `tool-bar-external' if t means the tool bar is by default external
8072 (not included in the inner size of FRAME).
8074 - `tool-bar-side' tells tells on which side the tool bar on FRAME is by
8075 default and can be one of `left', `top', `right' or `bottom'.
8077 - `tool-bar-size' is a cons of the width and height of the tool bar of
8078 FRAME.
8080 - `frame-inner-size' is a cons of the inner width and height of FRAME.
8081 This excludes FRAME's title bar and external border as well as any
8082 external menu and/or tool bar. */)
8083 (Lisp_Object frame)
8085 struct frame *f = decode_live_frame (frame);
8086 Lisp_Object geometry = Qnil;
8087 RECT frame_outer_edges, frame_inner_edges;
8088 MENUBARINFO menu_bar;
8089 int border_width, border_height, title_height;
8090 int single_bar_height, wrapped_bar_height, menu_bar_height;
8091 Lisp_Object fullscreen = Fframe_parameter (frame, Qfullscreen);
8093 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8094 return Qnil;
8096 block_input ();
8098 /* Outer frame rectangle, including outer borders and title bar. */
8099 GetWindowRect (FRAME_W32_WINDOW (f), &frame_outer_edges);
8100 /* Inner frame rectangle, excluding borders and title bar. */
8101 GetClientRect (FRAME_W32_WINDOW (f), &frame_inner_edges);
8102 /* Outer border. */
8103 border_width = GetSystemMetrics (SM_CXFRAME);
8104 border_height = GetSystemMetrics (SM_CYFRAME);
8105 /* Title bar. */
8106 title_height = GetSystemMetrics (SM_CYCAPTION);
8107 /* Menu bar. */
8108 menu_bar.cbSize = sizeof (menu_bar);
8109 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8110 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8111 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8112 single_bar_height = GetSystemMetrics (SM_CYMENU);
8113 wrapped_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8114 unblock_input ();
8116 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8117 /* Fix menu bar height reported by GetMenuBarInfo. */
8118 if (menu_bar_height > single_bar_height)
8119 /* A wrapped menu bar. */
8120 menu_bar_height += single_bar_height - wrapped_bar_height;
8121 else if (menu_bar_height > 0)
8122 /* A single line menu bar. */
8123 menu_bar_height = single_bar_height;
8125 return
8126 listn (CONSTYPE_HEAP, 10,
8127 Fcons (Qframe_position,
8128 Fcons (make_number (frame_outer_edges.left),
8129 make_number (frame_outer_edges.top))),
8130 Fcons (Qframe_outer_size,
8131 Fcons (make_number
8132 (frame_outer_edges.right - frame_outer_edges.left),
8133 make_number
8134 (frame_outer_edges.bottom - frame_outer_edges.top))),
8135 Fcons (Qexternal_border_size,
8136 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
8137 ? Fcons (make_number (0), make_number (0))
8138 : Fcons (make_number (border_width),
8139 make_number (border_height)))),
8140 Fcons (Qtitle_height,
8141 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
8142 ? make_number (0)
8143 : make_number (title_height))),
8144 Fcons (Qmenu_bar_external, Qt),
8145 Fcons (Qmenu_bar_size,
8146 Fcons (make_number
8147 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8148 make_number (menu_bar_height))),
8149 Fcons (Qtool_bar_external, Qnil),
8150 Fcons (Qtool_bar_position, Qtop),
8151 Fcons (Qtool_bar_size,
8152 Fcons (make_number (FRAME_TOOL_BAR_LINES (f)
8153 ? (FRAME_PIXEL_WIDTH (f)
8154 - 2 * FRAME_INTERNAL_BORDER_WIDTH (f))
8155 : 0),
8156 make_number (FRAME_TOOL_BAR_HEIGHT (f)))),
8157 Fcons (Qframe_inner_size,
8158 Fcons (make_number
8159 (frame_inner_edges.right - frame_inner_edges.left),
8160 make_number
8161 (frame_inner_edges.bottom - frame_inner_edges.top))));
8164 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
8165 doc: /* Get power status information from Windows system.
8167 The following %-sequences are provided:
8168 %L AC line status (verbose)
8169 %B Battery status (verbose)
8170 %b Battery status, empty means high, `-' means low,
8171 `!' means critical, and `+' means charging
8172 %p Battery load percentage
8173 %s Remaining time (to charge or discharge) in seconds
8174 %m Remaining time (to charge or discharge) in minutes
8175 %h Remaining time (to charge or discharge) in hours
8176 %t Remaining time (to charge or discharge) in the form `h:min' */)
8177 (void)
8179 Lisp_Object status = Qnil;
8181 SYSTEM_POWER_STATUS system_status;
8182 if (GetSystemPowerStatus (&system_status))
8184 Lisp_Object line_status, battery_status, battery_status_symbol;
8185 Lisp_Object load_percentage, seconds, minutes, hours, remain;
8187 long seconds_left = (long) system_status.BatteryLifeTime;
8189 if (system_status.ACLineStatus == 0)
8190 line_status = build_string ("off-line");
8191 else if (system_status.ACLineStatus == 1)
8192 line_status = build_string ("on-line");
8193 else
8194 line_status = build_string ("N/A");
8196 if (system_status.BatteryFlag & 128)
8198 battery_status = build_string ("N/A");
8199 battery_status_symbol = empty_unibyte_string;
8201 else if (system_status.BatteryFlag & 8)
8203 battery_status = build_string ("charging");
8204 battery_status_symbol = build_string ("+");
8205 if (system_status.BatteryFullLifeTime != -1L)
8206 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
8208 else if (system_status.BatteryFlag & 4)
8210 battery_status = build_string ("critical");
8211 battery_status_symbol = build_string ("!");
8213 else if (system_status.BatteryFlag & 2)
8215 battery_status = build_string ("low");
8216 battery_status_symbol = build_string ("-");
8218 else if (system_status.BatteryFlag & 1)
8220 battery_status = build_string ("high");
8221 battery_status_symbol = empty_unibyte_string;
8223 else
8225 battery_status = build_string ("medium");
8226 battery_status_symbol = empty_unibyte_string;
8229 if (system_status.BatteryLifePercent > 100)
8230 load_percentage = build_string ("N/A");
8231 else
8233 char buffer[16];
8234 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
8235 load_percentage = build_string (buffer);
8238 if (seconds_left < 0)
8239 seconds = minutes = hours = remain = build_string ("N/A");
8240 else
8242 long m;
8243 float h;
8244 char buffer[16];
8245 snprintf (buffer, 16, "%ld", seconds_left);
8246 seconds = build_string (buffer);
8248 m = seconds_left / 60;
8249 snprintf (buffer, 16, "%ld", m);
8250 minutes = build_string (buffer);
8252 h = seconds_left / 3600.0;
8253 snprintf (buffer, 16, "%3.1f", h);
8254 hours = build_string (buffer);
8256 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
8257 remain = build_string (buffer);
8260 status = listn (CONSTYPE_HEAP, 8,
8261 Fcons (make_number ('L'), line_status),
8262 Fcons (make_number ('B'), battery_status),
8263 Fcons (make_number ('b'), battery_status_symbol),
8264 Fcons (make_number ('p'), load_percentage),
8265 Fcons (make_number ('s'), seconds),
8266 Fcons (make_number ('m'), minutes),
8267 Fcons (make_number ('h'), hours),
8268 Fcons (make_number ('t'), remain));
8270 return status;
8274 #ifdef WINDOWSNT
8275 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
8276 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8277 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
8278 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8280 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8281 doc: /* Return storage information about the file system FILENAME is on.
8282 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8283 storage of the file system, FREE is the free storage, and AVAIL is the
8284 storage available to a non-superuser. All 3 numbers are in bytes.
8285 If the underlying system call fails, value is nil. */)
8286 (Lisp_Object filename)
8288 Lisp_Object encoded, value;
8290 CHECK_STRING (filename);
8291 filename = Fexpand_file_name (filename, Qnil);
8292 encoded = ENCODE_FILE (filename);
8294 value = Qnil;
8296 /* Determining the required information on Windows turns out, sadly,
8297 to be more involved than one would hope. The original Windows API
8298 call for this will return bogus information on some systems, but we
8299 must dynamically probe for the replacement api, since that was
8300 added rather late on. */
8302 HMODULE hKernel = GetModuleHandle ("kernel32");
8303 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
8304 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
8305 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
8306 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
8307 bool have_pfn_GetDiskFreeSpaceEx =
8308 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
8309 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
8311 /* On Windows, we may need to specify the root directory of the
8312 volume holding FILENAME. */
8313 char rootname[MAX_UTF8_PATH];
8314 wchar_t rootname_w[MAX_PATH];
8315 char rootname_a[MAX_PATH];
8316 char *name = SDATA (encoded);
8317 BOOL result;
8319 /* find the root name of the volume if given */
8320 if (isalpha (name[0]) && name[1] == ':')
8322 rootname[0] = name[0];
8323 rootname[1] = name[1];
8324 rootname[2] = '\\';
8325 rootname[3] = 0;
8327 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8329 char *str = rootname;
8330 int slashes = 4;
8333 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8334 break;
8335 *str++ = *name++;
8337 while ( *name );
8339 *str++ = '\\';
8340 *str = 0;
8343 if (w32_unicode_filenames)
8344 filename_to_utf16 (rootname, rootname_w);
8345 else
8346 filename_to_ansi (rootname, rootname_a);
8348 if (have_pfn_GetDiskFreeSpaceEx)
8350 /* Unsigned large integers cannot be cast to double, so
8351 use signed ones instead. */
8352 LARGE_INTEGER availbytes;
8353 LARGE_INTEGER freebytes;
8354 LARGE_INTEGER totalbytes;
8356 if (w32_unicode_filenames)
8357 result = pfn_GetDiskFreeSpaceExW (rootname_w,
8358 (ULARGE_INTEGER *)&availbytes,
8359 (ULARGE_INTEGER *)&totalbytes,
8360 (ULARGE_INTEGER *)&freebytes);
8361 else
8362 result = pfn_GetDiskFreeSpaceExA (rootname_a,
8363 (ULARGE_INTEGER *)&availbytes,
8364 (ULARGE_INTEGER *)&totalbytes,
8365 (ULARGE_INTEGER *)&freebytes);
8366 if (result)
8367 value = list3 (make_float ((double) totalbytes.QuadPart),
8368 make_float ((double) freebytes.QuadPart),
8369 make_float ((double) availbytes.QuadPart));
8371 else
8373 DWORD sectors_per_cluster;
8374 DWORD bytes_per_sector;
8375 DWORD free_clusters;
8376 DWORD total_clusters;
8378 if (w32_unicode_filenames)
8379 result = GetDiskFreeSpaceW (rootname_w,
8380 &sectors_per_cluster,
8381 &bytes_per_sector,
8382 &free_clusters,
8383 &total_clusters);
8384 else
8385 result = GetDiskFreeSpaceA (rootname_a,
8386 &sectors_per_cluster,
8387 &bytes_per_sector,
8388 &free_clusters,
8389 &total_clusters);
8390 if (result)
8391 value = list3 (make_float ((double) total_clusters
8392 * sectors_per_cluster * bytes_per_sector),
8393 make_float ((double) free_clusters
8394 * sectors_per_cluster * bytes_per_sector),
8395 make_float ((double) free_clusters
8396 * sectors_per_cluster * bytes_per_sector));
8400 return value;
8402 #endif /* WINDOWSNT */
8405 #ifdef WINDOWSNT
8406 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8407 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8408 (void)
8410 static char pname_buf[256];
8411 int err;
8412 HANDLE hPrn;
8413 PRINTER_INFO_2W *ppi2w = NULL;
8414 PRINTER_INFO_2A *ppi2a = NULL;
8415 DWORD dwNeeded = 0, dwReturned = 0;
8416 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
8417 char port_name[MAX_UTF8_PATH];
8419 /* Retrieve the default string from Win.ini (the registry).
8420 * String will be in form "printername,drivername,portname".
8421 * This is the most portable way to get the default printer. */
8422 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8423 return Qnil;
8424 /* printername precedes first "," character */
8425 strtok (pname_buf, ",");
8426 /* We want to know more than the printer name */
8427 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8428 return Qnil;
8429 /* GetPrinterW is not supported by unicows.dll. */
8430 if (w32_unicode_filenames && os_subtype != OS_9X)
8431 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
8432 else
8433 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
8434 if (dwNeeded == 0)
8436 ClosePrinter (hPrn);
8437 return Qnil;
8439 /* Call GetPrinter again with big enough memory block. */
8440 if (w32_unicode_filenames && os_subtype != OS_9X)
8442 /* Allocate memory for the PRINTER_INFO_2 struct. */
8443 ppi2w = xmalloc (dwNeeded);
8444 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
8445 ClosePrinter (hPrn);
8446 if (!err)
8448 xfree (ppi2w);
8449 return Qnil;
8452 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
8453 && ppi2w->pServerName)
8455 filename_from_utf16 (ppi2w->pServerName, server_name);
8456 filename_from_utf16 (ppi2w->pShareName, share_name);
8458 else
8460 server_name[0] = '\0';
8461 filename_from_utf16 (ppi2w->pPortName, port_name);
8464 else
8466 ppi2a = xmalloc (dwNeeded);
8467 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
8468 ClosePrinter (hPrn);
8469 if (!err)
8471 xfree (ppi2a);
8472 return Qnil;
8475 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
8476 && ppi2a->pServerName)
8478 filename_from_ansi (ppi2a->pServerName, server_name);
8479 filename_from_ansi (ppi2a->pShareName, share_name);
8481 else
8483 server_name[0] = '\0';
8484 filename_from_ansi (ppi2a->pPortName, port_name);
8488 if (server_name[0])
8490 /* a remote printer */
8491 if (server_name[0] == '\\')
8492 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
8493 share_name);
8494 else
8495 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
8496 share_name);
8497 pname_buf[sizeof (pname_buf) - 1] = '\0';
8499 else
8501 /* a local printer */
8502 strncpy (pname_buf, port_name, sizeof (pname_buf));
8503 pname_buf[sizeof (pname_buf) - 1] = '\0';
8504 /* `pPortName' can include several ports, delimited by ','.
8505 * we only use the first one. */
8506 strtok (pname_buf, ",");
8509 return DECODE_FILE (build_unibyte_string (pname_buf));
8511 #endif /* WINDOWSNT */
8514 /* Equivalent of strerror for W32 error codes. */
8515 char *
8516 w32_strerror (int error_no)
8518 static char buf[500];
8519 DWORD ret;
8521 if (error_no == 0)
8522 error_no = GetLastError ();
8524 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
8525 FORMAT_MESSAGE_IGNORE_INSERTS,
8526 NULL,
8527 error_no,
8528 0, /* choose most suitable language */
8529 buf, sizeof (buf), NULL);
8531 while (ret > 0 && (buf[ret - 1] == '\n' ||
8532 buf[ret - 1] == '\r' ))
8533 --ret;
8534 buf[ret] = '\0';
8535 if (!ret)
8536 sprintf (buf, "w32 error %u", error_no);
8538 return buf;
8541 /* For convenience when debugging. (You cannot call GetLastError
8542 directly from GDB: it will crash, because it uses the __stdcall
8543 calling convention, not the _cdecl convention assumed by GDB.) */
8544 DWORD
8545 w32_last_error (void)
8547 return GetLastError ();
8550 /* Cache information describing the NT system for later use. */
8551 void
8552 cache_system_info (void)
8554 union
8556 struct info
8558 char major;
8559 char minor;
8560 short platform;
8561 } info;
8562 DWORD data;
8563 } version;
8565 /* Cache the module handle of Emacs itself. */
8566 hinst = GetModuleHandle (NULL);
8568 /* Cache the version of the operating system. */
8569 version.data = GetVersion ();
8570 w32_major_version = version.info.major;
8571 w32_minor_version = version.info.minor;
8573 if (version.info.platform & 0x8000)
8574 os_subtype = OS_9X;
8575 else
8576 os_subtype = OS_NT;
8578 /* Cache page size, allocation unit, processor type, etc. */
8579 GetSystemInfo (&sysinfo_cache);
8580 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
8582 /* Cache os info. */
8583 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
8584 GetVersionEx (&osinfo_cache);
8586 w32_build_number = osinfo_cache.dwBuildNumber;
8587 if (os_subtype == OS_9X)
8588 w32_build_number &= 0xffff;
8590 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
8593 #ifdef EMACSDEBUG
8594 void
8595 _DebPrint (const char *fmt, ...)
8597 char buf[1024];
8598 va_list args;
8600 va_start (args, fmt);
8601 vsprintf (buf, fmt, args);
8602 va_end (args);
8603 #if CYGWIN
8604 fprintf (stderr, "%s", buf);
8605 #endif
8606 OutputDebugString (buf);
8608 #endif
8611 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
8613 int cur_state = (GetKeyState (vk_code) & 1);
8615 if (NILP (new_state)
8616 || (NUMBERP (new_state)
8617 && ((XUINT (new_state)) & 1) != cur_state))
8619 #ifdef WINDOWSNT
8620 faked_key = vk_code;
8621 #endif /* WINDOWSNT */
8623 keybd_event ((BYTE) vk_code,
8624 (BYTE) MapVirtualKey (vk_code, 0),
8625 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8626 keybd_event ((BYTE) vk_code,
8627 (BYTE) MapVirtualKey (vk_code, 0),
8628 KEYEVENTF_EXTENDEDKEY | 0, 0);
8629 keybd_event ((BYTE) vk_code,
8630 (BYTE) MapVirtualKey (vk_code, 0),
8631 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8632 cur_state = !cur_state;
8635 return cur_state;
8638 /* Translate console modifiers to emacs modifiers.
8639 German keyboard support (Kai Morgan Zeise 2/18/95). */
8641 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
8643 int retval = 0;
8645 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
8646 pressed, first remove those modifiers. */
8647 if (!NILP (Vw32_recognize_altgr)
8648 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8649 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8650 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
8652 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
8653 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
8655 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8657 retval |= ctrl_modifier;
8658 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8659 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8660 retval |= meta_modifier;
8663 if (mods & LEFT_WIN_PRESSED)
8664 retval |= w32_key_to_modifier (VK_LWIN);
8665 if (mods & RIGHT_WIN_PRESSED)
8666 retval |= w32_key_to_modifier (VK_RWIN);
8667 if (mods & APPS_PRESSED)
8668 retval |= w32_key_to_modifier (VK_APPS);
8669 if (mods & SCROLLLOCK_ON)
8670 retval |= w32_key_to_modifier (VK_SCROLL);
8672 /* Just in case someone wanted the original behavior, make it
8673 optional by setting w32-capslock-is-shiftlock to t. */
8674 if (NILP (Vw32_capslock_is_shiftlock)
8675 /* Keys that should _not_ be affected by CapsLock. */
8676 && ( (key == VK_BACK)
8677 || (key == VK_TAB)
8678 || (key == VK_CLEAR)
8679 || (key == VK_RETURN)
8680 || (key == VK_ESCAPE)
8681 || ((key >= VK_SPACE) && (key <= VK_HELP))
8682 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
8683 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
8686 /* Only consider shift state. */
8687 if ((mods & SHIFT_PRESSED) != 0)
8688 retval |= shift_modifier;
8690 else
8692 /* Ignore CapsLock state if not enabled. */
8693 if (NILP (Vw32_enable_caps_lock))
8694 mods &= ~CAPSLOCK_ON;
8695 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
8696 retval |= shift_modifier;
8699 return retval;
8702 /* The return code indicates key code size. cpID is the codepage to
8703 use for translation to Unicode; -1 means use the current console
8704 input codepage. */
8706 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
8708 unsigned int key_code = event->wVirtualKeyCode;
8709 unsigned int mods = event->dwControlKeyState;
8710 BYTE keystate[256];
8711 static BYTE ansi_code[4];
8712 static int isdead = 0;
8714 if (isdead == 2)
8716 event->uChar.AsciiChar = ansi_code[2];
8717 isdead = 0;
8718 return 1;
8720 if (event->uChar.AsciiChar != 0)
8721 return 1;
8723 memset (keystate, 0, sizeof (keystate));
8724 keystate[key_code] = 0x80;
8725 if (mods & SHIFT_PRESSED)
8726 keystate[VK_SHIFT] = 0x80;
8727 if (mods & CAPSLOCK_ON)
8728 keystate[VK_CAPITAL] = 1;
8729 /* If we recognize right-alt and left-ctrl as AltGr, set the key
8730 states accordingly before invoking ToAscii. */
8731 if (!NILP (Vw32_recognize_altgr)
8732 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
8734 keystate[VK_CONTROL] = 0x80;
8735 keystate[VK_LCONTROL] = 0x80;
8736 keystate[VK_MENU] = 0x80;
8737 keystate[VK_RMENU] = 0x80;
8740 #if 0
8741 /* Because of an OS bug, ToAscii corrupts the stack when called to
8742 convert a dead key in console mode on NT4. Unfortunately, trying
8743 to check for dead keys using MapVirtualKey doesn't work either -
8744 these functions apparently use internal information about keyboard
8745 layout which doesn't get properly updated in console programs when
8746 changing layout (though apparently it gets partly updated,
8747 otherwise ToAscii wouldn't crash). */
8748 if (is_dead_key (event->wVirtualKeyCode))
8749 return 0;
8750 #endif
8752 /* On NT, call ToUnicode instead and then convert to the current
8753 console input codepage. */
8754 if (os_subtype == OS_NT)
8756 WCHAR buf[128];
8758 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
8759 keystate, buf, 128, 0);
8760 if (isdead > 0)
8762 /* When we are called from the GUI message processing code,
8763 we are passed the current keyboard codepage, a positive
8764 number, to use below. */
8765 if (cpId == -1)
8766 cpId = GetConsoleCP ();
8768 event->uChar.UnicodeChar = buf[isdead - 1];
8769 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8770 ansi_code, 4, NULL, NULL);
8772 else
8773 isdead = 0;
8775 else
8777 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8778 keystate, (LPWORD) ansi_code, 0);
8781 if (isdead == 0)
8782 return 0;
8783 event->uChar.AsciiChar = ansi_code[0];
8784 return isdead;
8788 void
8789 w32_sys_ring_bell (struct frame *f)
8791 if (sound_type == 0xFFFFFFFF)
8793 Beep (666, 100);
8795 else if (sound_type == MB_EMACS_SILENT)
8797 /* Do nothing. */
8799 else
8800 MessageBeep (sound_type);
8803 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
8804 0, 0, 0,
8805 doc: /* Return non-nil when a menu-bar menu is being used.
8806 Internal use only. */)
8807 (void)
8809 return menubar_in_use ? Qt : Qnil;
8813 /***********************************************************************
8814 Initialization
8815 ***********************************************************************/
8817 /* Keep this list in the same order as frame_parms in frame.c.
8818 Use 0 for unsupported frame parameters. */
8820 frame_parm_handler w32_frame_parm_handlers[] =
8822 x_set_autoraise,
8823 x_set_autolower,
8824 x_set_background_color,
8825 x_set_border_color,
8826 x_set_border_width,
8827 x_set_cursor_color,
8828 x_set_cursor_type,
8829 x_set_font,
8830 x_set_foreground_color,
8831 x_set_icon_name,
8832 x_set_icon_type,
8833 x_set_internal_border_width,
8834 x_set_right_divider_width,
8835 x_set_bottom_divider_width,
8836 x_set_menu_bar_lines,
8837 x_set_mouse_color,
8838 x_explicitly_set_name,
8839 x_set_scroll_bar_width,
8840 x_set_scroll_bar_height,
8841 x_set_title,
8842 x_set_unsplittable,
8843 x_set_vertical_scroll_bars,
8844 x_set_horizontal_scroll_bars,
8845 x_set_visibility,
8846 x_set_tool_bar_lines,
8847 0, /* x_set_scroll_bar_foreground, */
8848 0, /* x_set_scroll_bar_background, */
8849 x_set_screen_gamma,
8850 x_set_line_spacing,
8851 x_set_left_fringe,
8852 x_set_right_fringe,
8853 0, /* x_set_wait_for_wm, */
8854 x_set_fullscreen,
8855 x_set_font_backend,
8856 x_set_alpha,
8857 0, /* x_set_sticky */
8858 0, /* x_set_tool_bar_position */
8861 void
8862 syms_of_w32fns (void)
8864 globals_of_w32fns ();
8865 track_mouse_window = NULL;
8867 w32_visible_system_caret_hwnd = NULL;
8869 DEFSYM (Qundefined_color, "undefined-color");
8870 DEFSYM (Qcancel_timer, "cancel-timer");
8871 DEFSYM (Qhyper, "hyper");
8872 DEFSYM (Qsuper, "super");
8873 DEFSYM (Qmeta, "meta");
8874 DEFSYM (Qalt, "alt");
8875 DEFSYM (Qctrl, "ctrl");
8876 DEFSYM (Qcontrol, "control");
8877 DEFSYM (Qshift, "shift");
8878 DEFSYM (Qfont_param, "font-parameter");
8879 DEFSYM (Qgeometry, "geometry");
8880 DEFSYM (Qworkarea, "workarea");
8881 DEFSYM (Qmm_size, "mm-size");
8882 DEFSYM (Qframes, "frames");
8883 DEFSYM (Qtip_frame, "tip-frame");
8884 DEFSYM (Qunicode_sip, "unicode-sip");
8886 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
8887 DEFSYM (Qgnutls_dll, "gnutls");
8888 DEFSYM (Qlibxml2_dll, "libxml2");
8889 DEFSYM (Qserif, "serif");
8890 DEFSYM (Qzlib_dll, "zlib");
8892 Fput (Qundefined_color, Qerror_conditions,
8893 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8894 Fput (Qundefined_color, Qerror_message,
8895 build_pure_c_string ("Undefined color"));
8897 staticpro (&w32_grabbed_keys);
8898 w32_grabbed_keys = Qnil;
8900 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8901 doc: /* An array of color name mappings for Windows. */);
8902 Vw32_color_map = Qnil;
8904 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8905 doc: /* Non-nil if Alt key presses are passed on to Windows.
8906 When non-nil, for example, Alt pressed and released and then space will
8907 open the System menu. When nil, Emacs processes the Alt key events, and
8908 then silently swallows them. */);
8909 Vw32_pass_alt_to_system = Qnil;
8911 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8912 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8913 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8914 Vw32_alt_is_meta = Qt;
8916 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8917 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8918 w32_quit_key = 0;
8920 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8921 Vw32_pass_lwindow_to_system,
8922 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8924 When non-nil, the Start menu is opened by tapping the key.
8925 If you set this to nil, the left \"Windows\" key is processed by Emacs
8926 according to the value of `w32-lwindow-modifier', which see.
8928 Note that some combinations of the left \"Windows\" key with other keys are
8929 caught by Windows at low level, and so binding them in Emacs will have no
8930 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8931 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8932 the doc string of `w32-phantom-key-code'. */);
8933 Vw32_pass_lwindow_to_system = Qt;
8935 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8936 Vw32_pass_rwindow_to_system,
8937 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8939 When non-nil, the Start menu is opened by tapping the key.
8940 If you set this to nil, the right \"Windows\" key is processed by Emacs
8941 according to the value of `w32-rwindow-modifier', which see.
8943 Note that some combinations of the right \"Windows\" key with other keys are
8944 caught by Windows at low level, and so binding them in Emacs will have no
8945 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8946 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8947 the doc string of `w32-phantom-key-code'. */);
8948 Vw32_pass_rwindow_to_system = Qt;
8950 DEFVAR_LISP ("w32-phantom-key-code",
8951 Vw32_phantom_key_code,
8952 doc: /* Virtual key code used to generate \"phantom\" key presses.
8953 Value is a number between 0 and 255.
8955 Phantom key presses are generated in order to stop the system from
8956 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8957 `w32-pass-rwindow-to-system' is nil. */);
8958 /* Although 255 is technically not a valid key code, it works and
8959 means that this hack won't interfere with any real key code. */
8960 XSETINT (Vw32_phantom_key_code, 255);
8962 DEFVAR_LISP ("w32-enable-num-lock",
8963 Vw32_enable_num_lock,
8964 doc: /* If non-nil, the Num Lock key acts normally.
8965 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8966 Vw32_enable_num_lock = Qt;
8968 DEFVAR_LISP ("w32-enable-caps-lock",
8969 Vw32_enable_caps_lock,
8970 doc: /* If non-nil, the Caps Lock key acts normally.
8971 Set to nil to handle Caps Lock as the `capslock' key. */);
8972 Vw32_enable_caps_lock = Qt;
8974 DEFVAR_LISP ("w32-scroll-lock-modifier",
8975 Vw32_scroll_lock_modifier,
8976 doc: /* Modifier to use for the Scroll Lock ON state.
8977 The value can be hyper, super, meta, alt, control or shift for the
8978 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8979 Any other value will cause the Scroll Lock key to be ignored. */);
8980 Vw32_scroll_lock_modifier = Qnil;
8982 DEFVAR_LISP ("w32-lwindow-modifier",
8983 Vw32_lwindow_modifier,
8984 doc: /* Modifier to use for the left \"Windows\" key.
8985 The value can be hyper, super, meta, alt, control or shift for the
8986 respective modifier, or nil to appear as the `lwindow' key.
8987 Any other value will cause the key to be ignored. */);
8988 Vw32_lwindow_modifier = Qnil;
8990 DEFVAR_LISP ("w32-rwindow-modifier",
8991 Vw32_rwindow_modifier,
8992 doc: /* Modifier to use for the right \"Windows\" key.
8993 The value can be hyper, super, meta, alt, control or shift for the
8994 respective modifier, or nil to appear as the `rwindow' key.
8995 Any other value will cause the key to be ignored. */);
8996 Vw32_rwindow_modifier = Qnil;
8998 DEFVAR_LISP ("w32-apps-modifier",
8999 Vw32_apps_modifier,
9000 doc: /* Modifier to use for the \"Apps\" key.
9001 The value can be hyper, super, meta, alt, control or shift for the
9002 respective modifier, or nil to appear as the `apps' key.
9003 Any other value will cause the key to be ignored. */);
9004 Vw32_apps_modifier = Qnil;
9006 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
9007 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
9008 w32_enable_synthesized_fonts = 0;
9010 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
9011 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
9012 Vw32_enable_palette = Qt;
9014 DEFVAR_INT ("w32-mouse-button-tolerance",
9015 w32_mouse_button_tolerance,
9016 doc: /* Analogue of double click interval for faking middle mouse events.
9017 The value is the minimum time in milliseconds that must elapse between
9018 left and right button down events before they are considered distinct events.
9019 If both mouse buttons are depressed within this interval, a middle mouse
9020 button down event is generated instead. */);
9021 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
9023 DEFVAR_INT ("w32-mouse-move-interval",
9024 w32_mouse_move_interval,
9025 doc: /* Minimum interval between mouse move events.
9026 The value is the minimum time in milliseconds that must elapse between
9027 successive mouse move (or scroll bar drag) events before they are
9028 reported as lisp events. */);
9029 w32_mouse_move_interval = 0;
9031 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
9032 w32_pass_extra_mouse_buttons_to_system,
9033 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
9034 Recent versions of Windows support mice with up to five buttons.
9035 Since most applications don't support these extra buttons, most mouse
9036 drivers will allow you to map them to functions at the system level.
9037 If this variable is non-nil, Emacs will pass them on, allowing the
9038 system to handle them. */);
9039 w32_pass_extra_mouse_buttons_to_system = 0;
9041 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
9042 w32_pass_multimedia_buttons_to_system,
9043 doc: /* If non-nil, media buttons are passed to Windows.
9044 Some modern keyboards contain buttons for controlling media players, web
9045 browsers and other applications. Generally these buttons are handled on a
9046 system wide basis, but by setting this to nil they are made available
9047 to Emacs for binding. Depending on your keyboard, additional keys that
9048 may be available are:
9050 browser-back, browser-forward, browser-refresh, browser-stop,
9051 browser-search, browser-favorites, browser-home,
9052 mail, mail-reply, mail-forward, mail-send,
9053 app-1, app-2,
9054 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
9055 spell-check, correction-list, toggle-dictate-command,
9056 media-next, media-previous, media-stop, media-play-pause, media-select,
9057 media-play, media-pause, media-record, media-fast-forward, media-rewind,
9058 media-channel-up, media-channel-down,
9059 volume-mute, volume-up, volume-down,
9060 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
9061 bass-down, bass-boost, bass-up, treble-down, treble-up */);
9062 w32_pass_multimedia_buttons_to_system = 1;
9064 #if 0 /* TODO: Mouse cursor customization. */
9065 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
9066 doc: /* The shape of the pointer when over text.
9067 Changing the value does not affect existing frames
9068 unless you set the mouse color. */);
9069 Vx_pointer_shape = Qnil;
9071 Vx_nontext_pointer_shape = Qnil;
9073 Vx_mode_pointer_shape = Qnil;
9075 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
9076 doc: /* The shape of the pointer when Emacs is busy.
9077 This variable takes effect when you create a new frame
9078 or when you set the mouse color. */);
9079 Vx_hourglass_pointer_shape = Qnil;
9081 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
9082 Vx_sensitive_text_pointer_shape,
9083 doc: /* The shape of the pointer when over mouse-sensitive text.
9084 This variable takes effect when you create a new frame
9085 or when you set the mouse color. */);
9086 Vx_sensitive_text_pointer_shape = Qnil;
9088 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
9089 Vx_window_horizontal_drag_shape,
9090 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
9091 This variable takes effect when you create a new frame
9092 or when you set the mouse color. */);
9093 Vx_window_horizontal_drag_shape = Qnil;
9095 DEFVAR_LISP ("x-window-vertical-drag-cursor",
9096 Vx_window_vertical_drag_shape,
9097 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
9098 This variable takes effect when you create a new frame
9099 or when you set the mouse color. */);
9100 Vx_window_vertical_drag_shape = Qnil;
9101 #endif
9103 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
9104 doc: /* A string indicating the foreground color of the cursor box. */);
9105 Vx_cursor_fore_pixel = Qnil;
9107 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
9108 doc: /* Maximum size for tooltips.
9109 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
9110 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
9112 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
9113 doc: /* Non-nil if no window manager is in use.
9114 Emacs doesn't try to figure this out; this is always nil
9115 unless you set it to something else. */);
9116 /* We don't have any way to find this out, so set it to nil
9117 and maybe the user would like to set it to t. */
9118 Vx_no_window_manager = Qnil;
9120 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
9121 Vx_pixel_size_width_font_regexp,
9122 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
9124 Since Emacs gets width of a font matching with this regexp from
9125 PIXEL_SIZE field of the name, font finding mechanism gets faster for
9126 such a font. This is especially effective for such large fonts as
9127 Chinese, Japanese, and Korean. */);
9128 Vx_pixel_size_width_font_regexp = Qnil;
9130 DEFVAR_LISP ("w32-bdf-filename-alist",
9131 Vw32_bdf_filename_alist,
9132 doc: /* List of bdf fonts and their corresponding filenames. */);
9133 Vw32_bdf_filename_alist = Qnil;
9135 DEFVAR_BOOL ("w32-strict-fontnames",
9136 w32_strict_fontnames,
9137 doc: /* Non-nil means only use fonts that are exact matches for those requested.
9138 Default is nil, which allows old fontnames that are not XLFD compliant,
9139 and allows third-party CJK display to work by specifying false charset
9140 fields to trick Emacs into translating to Big5, SJIS etc.
9141 Setting this to t will prevent wrong fonts being selected when
9142 fontsets are automatically created. */);
9143 w32_strict_fontnames = 0;
9145 DEFVAR_BOOL ("w32-strict-painting",
9146 w32_strict_painting,
9147 doc: /* Non-nil means use strict rules for repainting frames.
9148 Set this to nil to get the old behavior for repainting; this should
9149 only be necessary if the default setting causes problems. */);
9150 w32_strict_painting = 1;
9152 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method"
9153 w32_use_fallback_wm_chars_method,
9154 doc: /* Non-nil means use old method of processing character keys.
9155 This is intended only for debugging of the new processing method.
9156 Default is nil.
9158 This variable has effect only on NT family of systems, not on Windows 9X. */);
9159 w32_use_fallback_wm_chars_method = 0;
9161 #if 0 /* TODO: Port to W32 */
9162 defsubr (&Sx_change_window_property);
9163 defsubr (&Sx_delete_window_property);
9164 defsubr (&Sx_window_property);
9165 #endif
9166 defsubr (&Sxw_display_color_p);
9167 defsubr (&Sx_display_grayscale_p);
9168 defsubr (&Sxw_color_defined_p);
9169 defsubr (&Sxw_color_values);
9170 defsubr (&Sx_server_max_request_size);
9171 defsubr (&Sx_server_vendor);
9172 defsubr (&Sx_server_version);
9173 defsubr (&Sx_display_pixel_width);
9174 defsubr (&Sx_display_pixel_height);
9175 defsubr (&Sx_display_mm_width);
9176 defsubr (&Sx_display_mm_height);
9177 defsubr (&Sx_display_screens);
9178 defsubr (&Sx_display_planes);
9179 defsubr (&Sx_display_color_cells);
9180 defsubr (&Sx_display_visual_class);
9181 defsubr (&Sx_display_backing_store);
9182 defsubr (&Sx_display_save_under);
9183 defsubr (&Sx_create_frame);
9184 defsubr (&Sx_open_connection);
9185 defsubr (&Sx_close_connection);
9186 defsubr (&Sx_display_list);
9187 defsubr (&Sx_frame_geometry);
9188 defsubr (&Sx_synchronize);
9190 /* W32 specific functions */
9192 defsubr (&Sw32_define_rgb_color);
9193 defsubr (&Sw32_default_color_map);
9194 defsubr (&Sw32_display_monitor_attributes_list);
9195 defsubr (&Sw32_send_sys_command);
9196 defsubr (&Sw32_shell_execute);
9197 defsubr (&Sw32_register_hot_key);
9198 defsubr (&Sw32_unregister_hot_key);
9199 defsubr (&Sw32_registered_hot_keys);
9200 defsubr (&Sw32_reconstruct_hot_key);
9201 defsubr (&Sw32_toggle_lock_key);
9202 defsubr (&Sw32_window_exists_p);
9203 defsubr (&Sw32_frame_rect);
9204 defsubr (&Sw32_frame_menu_bar_size);
9205 defsubr (&Sw32_battery_status);
9206 defsubr (&Sw32__menu_bar_in_use);
9208 #ifdef WINDOWSNT
9209 defsubr (&Sfile_system_info);
9210 defsubr (&Sdefault_printer_name);
9211 #endif
9213 defsubr (&Sset_message_beep);
9214 defsubr (&Sx_show_tip);
9215 defsubr (&Sx_hide_tip);
9216 tip_timer = Qnil;
9217 staticpro (&tip_timer);
9218 tip_frame = Qnil;
9219 staticpro (&tip_frame);
9221 last_show_tip_args = Qnil;
9222 staticpro (&last_show_tip_args);
9224 defsubr (&Sx_file_dialog);
9225 #ifdef WINDOWSNT
9226 defsubr (&Ssystem_move_file_to_trash);
9227 #endif
9232 /* Crashing and reporting backtrace. */
9234 #ifndef CYGWIN
9235 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
9236 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
9237 #endif
9238 static DWORD except_code;
9239 static PVOID except_addr;
9241 #ifndef CYGWIN
9242 /* This handler records the exception code and the address where it
9243 was triggered so that this info could be included in the backtrace.
9244 Without that, the backtrace in some cases has no information
9245 whatsoever about the offending code, and looks as if the top-level
9246 exception handler in the MinGW startup code di the one that
9247 crashed. */
9248 static LONG CALLBACK
9249 my_exception_handler (EXCEPTION_POINTERS * exception_data)
9251 except_code = exception_data->ExceptionRecord->ExceptionCode;
9252 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
9254 if (prev_exception_handler)
9255 return prev_exception_handler (exception_data);
9256 return EXCEPTION_EXECUTE_HANDLER;
9258 #endif
9260 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
9261 PULONG);
9263 #define BACKTRACE_LIMIT_MAX 62
9266 w32_backtrace (void **buffer, int limit)
9268 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
9269 HMODULE hm_kernel32 = NULL;
9271 if (!s_pfn_CaptureStackBackTrace)
9273 hm_kernel32 = LoadLibrary ("Kernel32.dll");
9274 s_pfn_CaptureStackBackTrace =
9275 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
9276 "RtlCaptureStackBackTrace");
9278 if (s_pfn_CaptureStackBackTrace)
9279 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
9280 buffer, NULL);
9281 return 0;
9284 void
9285 emacs_abort (void)
9287 int button;
9288 button = MessageBox (NULL,
9289 "A fatal error has occurred!\n\n"
9290 "Would you like to attach a debugger?\n\n"
9291 "Select:\n"
9292 "YES -- to debug Emacs, or\n"
9293 "NO -- to abort Emacs and produce a backtrace\n"
9294 " (emacs_backtrace.txt in current directory)."
9295 #if __GNUC__
9296 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
9297 "\"continue\" inside GDB before clicking YES.)"
9298 #endif
9299 , "Emacs Abort Dialog",
9300 MB_ICONEXCLAMATION | MB_TASKMODAL
9301 | MB_SETFOREGROUND | MB_YESNO);
9302 switch (button)
9304 case IDYES:
9305 DebugBreak ();
9306 exit (2); /* tell the compiler we will never return */
9307 case IDNO:
9308 default:
9310 void *stack[BACKTRACE_LIMIT_MAX + 1];
9311 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
9313 if (i)
9315 int errfile_fd = -1;
9316 int j;
9317 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
9318 /* The type below should really be 'void *', but
9319 INT_BUFSIZE_BOUND cannot handle that without
9320 triggering compiler warnings (under certain
9321 pedantic warning switches), it wants an
9322 integer type. */
9323 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
9324 #ifdef CYGWIN
9325 int stderr_fd = 2;
9326 #else
9327 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
9328 int stderr_fd = -1;
9330 if (errout && errout != INVALID_HANDLE_VALUE)
9331 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
9332 #endif
9334 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
9335 but not on Windows 7. addr2line doesn't mind a missing
9336 "0x", but will be confused by an extra one. */
9337 if (except_addr)
9338 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
9339 except_code, except_addr);
9340 if (stderr_fd >= 0)
9342 if (except_addr)
9343 write (stderr_fd, buf, strlen (buf));
9344 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
9346 #ifdef CYGWIN
9347 #define _open open
9348 #endif
9349 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
9350 if (errfile_fd >= 0)
9352 lseek (errfile_fd, 0L, SEEK_END);
9353 if (except_addr)
9354 write (errfile_fd, buf, strlen (buf));
9355 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
9358 for (j = 0; j < i; j++)
9360 /* stack[] gives the return addresses, whereas we want
9361 the address of the call, so decrease each address
9362 by approximate size of 1 CALL instruction. */
9363 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
9364 if (stderr_fd >= 0)
9365 write (stderr_fd, buf, strlen (buf));
9366 if (errfile_fd >= 0)
9367 write (errfile_fd, buf, strlen (buf));
9369 if (i == BACKTRACE_LIMIT_MAX)
9371 if (stderr_fd >= 0)
9372 write (stderr_fd, "...\r\n", 5);
9373 if (errfile_fd >= 0)
9374 write (errfile_fd, "...\r\n", 5);
9376 if (errfile_fd >= 0)
9377 close (errfile_fd);
9379 abort ();
9380 break;
9387 /* Initialization. */
9390 globals_of_w32fns is used to initialize those global variables that
9391 must always be initialized on startup even when the global variable
9392 initialized is non zero (see the function main in emacs.c).
9393 globals_of_w32fns is called from syms_of_w32fns when the global
9394 variable initialized is 0 and directly from main when initialized
9395 is non zero.
9397 void
9398 globals_of_w32fns (void)
9400 HMODULE user32_lib = GetModuleHandle ("user32.dll");
9402 TrackMouseEvent not available in all versions of Windows, so must load
9403 it dynamically. Do it once, here, instead of every time it is used.
9405 track_mouse_event_fn = (TrackMouseEvent_Proc)
9406 GetProcAddress (user32_lib, "TrackMouseEvent");
9408 monitor_from_point_fn = (MonitorFromPoint_Proc)
9409 GetProcAddress (user32_lib, "MonitorFromPoint");
9410 get_monitor_info_fn = (GetMonitorInfo_Proc)
9411 GetProcAddress (user32_lib, "GetMonitorInfoA");
9412 monitor_from_window_fn = (MonitorFromWindow_Proc)
9413 GetProcAddress (user32_lib, "MonitorFromWindow");
9414 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
9415 GetProcAddress (user32_lib, "EnumDisplayMonitors");
9418 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
9419 get_composition_string_fn = (ImmGetCompositionString_Proc)
9420 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
9421 get_ime_context_fn = (ImmGetContext_Proc)
9422 GetProcAddress (imm32_lib, "ImmGetContext");
9423 release_ime_context_fn = (ImmReleaseContext_Proc)
9424 GetProcAddress (imm32_lib, "ImmReleaseContext");
9425 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
9426 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
9429 except_code = 0;
9430 except_addr = 0;
9431 #ifndef CYGWIN
9432 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
9433 #endif
9435 DEFVAR_INT ("w32-ansi-code-page",
9436 w32_ansi_code_page,
9437 doc: /* The ANSI code page used by the system. */);
9438 w32_ansi_code_page = GetACP ();
9440 if (os_subtype == OS_NT)
9441 w32_unicode_gui = 1;
9442 else
9443 w32_unicode_gui = 0;
9445 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
9446 InitCommonControls ();
9448 syms_of_w32uniscribe ();
9451 #ifdef NTGUI_UNICODE
9453 Lisp_Object
9454 ntgui_encode_system (Lisp_Object str)
9456 Lisp_Object encoded;
9457 to_unicode (str, &encoded);
9458 return encoded;
9461 #endif /* NTGUI_UNICODE */