* lisp/url/url-handlers.el: No need for subr-x at run-time.
[emacs.git] / src / w32fns.c
blob2b920f29c650daf6ce9f49f1e1939b4c6685f90d
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2018 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 (at
10 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 <https://www.gnu.org/licenses/>. */
20 /* Added by Kevin Gallo */
22 #include <config.h>
23 /* Override API version to get the latest functionality. */
24 #undef _WIN32_WINNT
25 #define _WIN32_WINNT 0x0600
27 #include <signal.h>
28 #include <stdio.h>
29 #include <limits.h>
30 #include <errno.h>
31 #include <math.h>
32 #include <fcntl.h>
33 #include <unistd.h>
35 #include <c-ctype.h>
37 #include "lisp.h"
38 #include "w32term.h"
39 #include "frame.h"
40 #include "window.h"
41 #include "buffer.h"
42 #include "keyboard.h"
43 #include "blockinput.h"
44 #include "coding.h"
46 #include "w32common.h"
47 #include "w32inevt.h"
49 #ifdef WINDOWSNT
50 #include <mbstring.h>
51 #endif /* WINDOWSNT */
53 #if CYGWIN
54 #include "cygw32.h"
55 #else
56 #include "w32.h"
57 #endif
59 #include <basetyps.h>
60 #include <unknwn.h>
61 #include <commctrl.h>
62 #include <commdlg.h>
63 #include <shellapi.h>
64 #include <shlwapi.h>
65 #include <ctype.h>
66 #include <winspool.h>
67 #include <objbase.h>
69 #include <dlgs.h>
70 #include <imm.h>
71 #include <windowsx.h>
73 #ifndef FOF_NO_CONNECTED_ELEMENTS
74 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
75 #endif
77 extern int w32_console_toggle_lock_key (int, Lisp_Object);
78 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
79 extern void w32_free_menu_strings (HWND);
80 extern const char *map_w32_filename (const char *, const char **);
82 #ifndef IDC_HAND
83 #define IDC_HAND MAKEINTRESOURCE(32649)
84 #endif
86 /* Prefix for system colors. */
87 #define SYSTEM_COLOR_PREFIX "System"
88 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
90 /* State variables for emulating a three button mouse. */
91 #define LMOUSE 1
92 #define MMOUSE 2
93 #define RMOUSE 4
95 static int button_state = 0;
96 static W32Msg saved_mouse_button_msg;
97 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
98 static W32Msg saved_mouse_move_msg;
99 static unsigned mouse_move_timer = 0;
101 /* Window that is tracking the mouse. */
102 static HWND track_mouse_window;
104 /* Multi-monitor API definitions that are not pulled from the headers
105 since we are compiling for NT 4. */
106 #ifndef MONITOR_DEFAULT_TO_NEAREST
107 #define MONITOR_DEFAULT_TO_NEAREST 2
108 #endif
109 #ifndef MONITORINFOF_PRIMARY
110 #define MONITORINFOF_PRIMARY 1
111 #endif
112 #ifndef SM_XVIRTUALSCREEN
113 #define SM_XVIRTUALSCREEN 76
114 #endif
115 #ifndef SM_YVIRTUALSCREEN
116 #define SM_YVIRTUALSCREEN 77
117 #endif
118 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
119 To avoid a compile error on one or the other, redefine with a new name. */
120 struct MONITOR_INFO
122 DWORD cbSize;
123 RECT rcMonitor;
124 RECT rcWork;
125 DWORD dwFlags;
128 #if _WIN32_WINDOWS >= 0x0410
129 #define C_CHILDREN_TITLEBAR CCHILDREN_TITLEBAR
130 typedef TITLEBARINFO TITLEBAR_INFO;
131 #else
132 #define C_CHILDREN_TITLEBAR 5
133 typedef struct
135 DWORD cbSize;
136 RECT rcTitleBar;
137 DWORD rgstate[C_CHILDREN_TITLEBAR+1];
138 } TITLEBAR_INFO, *PTITLEBAR_INFO;
139 #endif
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);
175 typedef BOOL (WINAPI * GetTitleBarInfo_Proc)
176 (IN HWND hwnd, OUT TITLEBAR_INFO* info);
178 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
179 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
180 ImmGetContext_Proc get_ime_context_fn = NULL;
181 ImmReleaseContext_Proc release_ime_context_fn = NULL;
182 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
183 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
184 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
185 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
186 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
187 GetTitleBarInfo_Proc get_title_bar_info_fn = NULL;
189 extern AppendMenuW_Proc unicode_append_menu;
191 /* Flag to selectively ignore WM_IME_CHAR messages. */
192 static int ignore_ime_char = 0;
194 /* W95 mousewheel handler */
195 unsigned int msh_mousewheel = 0;
197 /* Timers */
198 #define MOUSE_BUTTON_ID 1
199 #define MOUSE_MOVE_ID 2
200 #define MENU_FREE_ID 3
201 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
202 is received. */
203 #define MENU_FREE_DELAY 1000
204 static unsigned menu_free_timer = 0;
206 #ifdef GLYPH_DEBUG
207 static ptrdiff_t image_cache_refcount;
208 static int dpyinfo_refcount;
209 #endif
211 static HWND w32_visible_system_caret_hwnd;
213 static int w32_unicode_gui;
215 /* From w32menu.c */
216 int menubar_in_use = 0;
218 /* From w32uniscribe.c */
219 extern void syms_of_w32uniscribe (void);
220 extern int uniscribe_available;
222 #ifdef WINDOWSNT
223 /* From w32inevt.c */
224 extern int faked_key;
225 #endif /* WINDOWSNT */
227 /* This gives us the page size and the size of the allocation unit on NT. */
228 SYSTEM_INFO sysinfo_cache;
230 /* This gives us version, build, and platform identification. */
231 OSVERSIONINFO osinfo_cache;
233 DWORD_PTR syspage_mask = 0;
235 /* The major and minor versions of NT. */
236 int w32_major_version;
237 int w32_minor_version;
238 int w32_build_number;
240 /* Distinguish between Windows NT and Windows 95. */
241 int os_subtype;
243 #ifdef HAVE_NTGUI
244 HINSTANCE hinst = NULL;
245 #endif
247 static unsigned int sound_type = 0xFFFFFFFF;
248 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
250 /* Special virtual key code for indicating "any" key. */
251 #define VK_ANY 0xFF
253 #ifndef WM_WTSSESSION_CHANGE
254 /* 32-bit MinGW does not define these constants. */
255 # define WM_WTSSESSION_CHANGE 0x02B1
256 # define WTS_SESSION_LOCK 0x7
257 #endif
259 #ifndef WS_EX_NOACTIVATE
260 #define WS_EX_NOACTIVATE 0x08000000L
261 #endif
263 /* Keyboard hook state data. */
264 static struct
266 int hook_count; /* counter, if several windows are created */
267 HHOOK hook; /* hook handle */
268 HWND console; /* console window handle */
270 int lwindown; /* Left Windows key currently pressed (and hooked) */
271 int rwindown; /* Right Windows key currently pressed (and hooked) */
272 int winsdown; /* Number of handled keys currently pressed */
273 int send_win_up; /* Pass through the keyup for this Windows key press? */
274 int suppress_lone; /* Suppress simulated Windows keydown-keyup for this press? */
275 int winseen; /* Windows keys seen during this press? */
277 char alt_hooked[256]; /* hook Alt+[this key]? */
278 char lwin_hooked[256]; /* hook left Win+[this key]? */
279 char rwin_hooked[256]; /* hook right Win+[this key]? */
280 } kbdhook;
281 typedef HWND (WINAPI *GetConsoleWindow_Proc) (void);
283 typedef BOOL (WINAPI *IsDebuggerPresent_Proc) (void);
285 /* stdin, from w32console.c */
286 extern HANDLE keyboard_handle;
288 /* Let the user specify a display with a frame.
289 nil stands for the selected frame--or, if that is not a w32 frame,
290 the first display on the list. */
292 struct w32_display_info *
293 check_x_display_info (Lisp_Object object)
295 if (NILP (object))
297 struct frame *sf = XFRAME (selected_frame);
299 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
300 return FRAME_DISPLAY_INFO (sf);
301 else
302 return &one_w32_display_info;
304 else if (TERMINALP (object))
306 struct terminal *t = decode_live_terminal (object);
308 if (t->type != output_w32)
309 error ("Terminal %d is not a W32 display", t->id);
311 return t->display_info.w32;
313 else if (STRINGP (object))
314 return x_display_info_for_name (object);
315 else
317 struct frame *f;
319 CHECK_LIVE_FRAME (object);
320 f = XFRAME (object);
321 if (! FRAME_W32_P (f))
322 error ("Non-W32 frame used");
323 return FRAME_DISPLAY_INFO (f);
327 /* Return the Emacs frame-object corresponding to an w32 window.
328 It could be the frame's main window or an icon window. */
330 struct frame *
331 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
333 Lisp_Object tail, frame;
334 struct frame *f;
336 FOR_EACH_FRAME (tail, frame)
338 f = XFRAME (frame);
339 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
340 continue;
342 if (FRAME_W32_WINDOW (f) == wdesc)
343 return f;
345 return 0;
349 static Lisp_Object unwind_create_frame (Lisp_Object);
350 static void unwind_create_tip_frame (Lisp_Object);
351 static void my_create_window (struct frame *);
352 static void my_create_tip_window (struct frame *);
354 /* TODO: Native Input Method support; see x_create_im. */
355 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
356 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
357 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
358 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
359 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
360 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
361 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
362 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
363 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
364 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
367 /* Store the screen positions of frame F into XPTR and YPTR.
368 These are the positions of the containing window manager window,
369 not Emacs's own window. */
371 void
372 x_real_positions (struct frame *f, int *xptr, int *yptr)
374 RECT rect;
376 /* Get the bounds of the WM window. */
377 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
379 if (FRAME_PARENT_FRAME (f))
381 /* For a child window we have to get its coordinates wrt its
382 parent. */
383 HWND parent_hwnd = FRAME_W32_WINDOW (FRAME_PARENT_FRAME (f));
385 if (parent_hwnd)
386 MapWindowPoints (HWND_DESKTOP, parent_hwnd, (LPPOINT) &rect, 2);
389 *xptr = rect.left;
390 *yptr = rect.top;
393 /* Returns the window rectangle appropriate for the given fullscreen mode.
394 The normal rect parameter was the window's rectangle prior to entering
395 fullscreen mode. If multiple monitor support is available, the nearest
396 monitor to the window is chosen. */
398 void
399 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
401 struct MONITOR_INFO mi = { sizeof(mi) };
402 if (monitor_from_window_fn && get_monitor_info_fn)
404 HMONITOR monitor =
405 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
406 get_monitor_info_fn (monitor, &mi);
408 else
410 mi.rcMonitor.left = 0;
411 mi.rcMonitor.top = 0;
412 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
413 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
414 mi.rcWork.left = 0;
415 mi.rcWork.top = 0;
416 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
417 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
420 switch (fsmode)
422 case FULLSCREEN_BOTH:
423 rect->left = mi.rcMonitor.left;
424 rect->top = mi.rcMonitor.top;
425 rect->right = mi.rcMonitor.right;
426 rect->bottom = mi.rcMonitor.bottom;
427 break;
428 case FULLSCREEN_WIDTH:
429 rect->left = mi.rcWork.left;
430 rect->top = normal.top;
431 rect->right = mi.rcWork.right;
432 rect->bottom = normal.bottom;
433 break;
434 case FULLSCREEN_HEIGHT:
435 rect->left = normal.left;
436 rect->top = mi.rcWork.top;
437 rect->right = normal.right;
438 rect->bottom = mi.rcWork.bottom;
439 break;
440 default:
441 *rect = normal;
442 break;
448 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
449 Sw32_define_rgb_color, 4, 4, 0,
450 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
451 This adds or updates a named color to `w32-color-map', making it
452 available for use. The original entry's RGB ref is returned, or nil
453 if the entry is new. */)
454 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
456 Lisp_Object rgb;
457 Lisp_Object oldrgb = Qnil;
458 Lisp_Object entry;
460 CHECK_NUMBER (red);
461 CHECK_NUMBER (green);
462 CHECK_NUMBER (blue);
463 CHECK_STRING (name);
465 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
467 block_input ();
469 /* replace existing entry in w32-color-map or add new entry. */
470 entry = Fassoc (name, Vw32_color_map, Qnil);
471 if (NILP (entry))
473 entry = Fcons (name, rgb);
474 Vw32_color_map = Fcons (entry, Vw32_color_map);
476 else
478 oldrgb = Fcdr (entry);
479 Fsetcdr (entry, rgb);
482 unblock_input ();
484 return (oldrgb);
487 /* The default colors for the w32 color map */
488 typedef struct colormap_t
490 const char *name;
491 COLORREF colorref;
492 } colormap_t;
494 colormap_t w32_color_map[] =
496 {"snow" , PALETTERGB (255,250,250)},
497 {"ghost white" , PALETTERGB (248,248,255)},
498 {"GhostWhite" , PALETTERGB (248,248,255)},
499 {"white smoke" , PALETTERGB (245,245,245)},
500 {"WhiteSmoke" , PALETTERGB (245,245,245)},
501 {"gainsboro" , PALETTERGB (220,220,220)},
502 {"floral white" , PALETTERGB (255,250,240)},
503 {"FloralWhite" , PALETTERGB (255,250,240)},
504 {"old lace" , PALETTERGB (253,245,230)},
505 {"OldLace" , PALETTERGB (253,245,230)},
506 {"linen" , PALETTERGB (250,240,230)},
507 {"antique white" , PALETTERGB (250,235,215)},
508 {"AntiqueWhite" , PALETTERGB (250,235,215)},
509 {"papaya whip" , PALETTERGB (255,239,213)},
510 {"PapayaWhip" , PALETTERGB (255,239,213)},
511 {"blanched almond" , PALETTERGB (255,235,205)},
512 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
513 {"bisque" , PALETTERGB (255,228,196)},
514 {"peach puff" , PALETTERGB (255,218,185)},
515 {"PeachPuff" , PALETTERGB (255,218,185)},
516 {"navajo white" , PALETTERGB (255,222,173)},
517 {"NavajoWhite" , PALETTERGB (255,222,173)},
518 {"moccasin" , PALETTERGB (255,228,181)},
519 {"cornsilk" , PALETTERGB (255,248,220)},
520 {"ivory" , PALETTERGB (255,255,240)},
521 {"lemon chiffon" , PALETTERGB (255,250,205)},
522 {"LemonChiffon" , PALETTERGB (255,250,205)},
523 {"seashell" , PALETTERGB (255,245,238)},
524 {"honeydew" , PALETTERGB (240,255,240)},
525 {"mint cream" , PALETTERGB (245,255,250)},
526 {"MintCream" , PALETTERGB (245,255,250)},
527 {"azure" , PALETTERGB (240,255,255)},
528 {"alice blue" , PALETTERGB (240,248,255)},
529 {"AliceBlue" , PALETTERGB (240,248,255)},
530 {"lavender" , PALETTERGB (230,230,250)},
531 {"lavender blush" , PALETTERGB (255,240,245)},
532 {"LavenderBlush" , PALETTERGB (255,240,245)},
533 {"misty rose" , PALETTERGB (255,228,225)},
534 {"MistyRose" , PALETTERGB (255,228,225)},
535 {"white" , PALETTERGB (255,255,255)},
536 {"black" , PALETTERGB ( 0, 0, 0)},
537 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
538 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
539 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
540 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
541 {"dim gray" , PALETTERGB (105,105,105)},
542 {"DimGray" , PALETTERGB (105,105,105)},
543 {"dim grey" , PALETTERGB (105,105,105)},
544 {"DimGrey" , PALETTERGB (105,105,105)},
545 {"slate gray" , PALETTERGB (112,128,144)},
546 {"SlateGray" , PALETTERGB (112,128,144)},
547 {"slate grey" , PALETTERGB (112,128,144)},
548 {"SlateGrey" , PALETTERGB (112,128,144)},
549 {"light slate gray" , PALETTERGB (119,136,153)},
550 {"LightSlateGray" , PALETTERGB (119,136,153)},
551 {"light slate grey" , PALETTERGB (119,136,153)},
552 {"LightSlateGrey" , PALETTERGB (119,136,153)},
553 {"gray" , PALETTERGB (190,190,190)},
554 {"grey" , PALETTERGB (190,190,190)},
555 {"light grey" , PALETTERGB (211,211,211)},
556 {"LightGrey" , PALETTERGB (211,211,211)},
557 {"light gray" , PALETTERGB (211,211,211)},
558 {"LightGray" , PALETTERGB (211,211,211)},
559 {"midnight blue" , PALETTERGB ( 25, 25,112)},
560 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
561 {"navy" , PALETTERGB ( 0, 0,128)},
562 {"navy blue" , PALETTERGB ( 0, 0,128)},
563 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
564 {"cornflower blue" , PALETTERGB (100,149,237)},
565 {"CornflowerBlue" , PALETTERGB (100,149,237)},
566 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
567 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
568 {"slate blue" , PALETTERGB (106, 90,205)},
569 {"SlateBlue" , PALETTERGB (106, 90,205)},
570 {"medium slate blue" , PALETTERGB (123,104,238)},
571 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
572 {"light slate blue" , PALETTERGB (132,112,255)},
573 {"LightSlateBlue" , PALETTERGB (132,112,255)},
574 {"medium blue" , PALETTERGB ( 0, 0,205)},
575 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
576 {"royal blue" , PALETTERGB ( 65,105,225)},
577 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
578 {"blue" , PALETTERGB ( 0, 0,255)},
579 {"dodger blue" , PALETTERGB ( 30,144,255)},
580 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
581 {"deep sky blue" , PALETTERGB ( 0,191,255)},
582 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
583 {"sky blue" , PALETTERGB (135,206,235)},
584 {"SkyBlue" , PALETTERGB (135,206,235)},
585 {"light sky blue" , PALETTERGB (135,206,250)},
586 {"LightSkyBlue" , PALETTERGB (135,206,250)},
587 {"steel blue" , PALETTERGB ( 70,130,180)},
588 {"SteelBlue" , PALETTERGB ( 70,130,180)},
589 {"light steel blue" , PALETTERGB (176,196,222)},
590 {"LightSteelBlue" , PALETTERGB (176,196,222)},
591 {"light blue" , PALETTERGB (173,216,230)},
592 {"LightBlue" , PALETTERGB (173,216,230)},
593 {"powder blue" , PALETTERGB (176,224,230)},
594 {"PowderBlue" , PALETTERGB (176,224,230)},
595 {"pale turquoise" , PALETTERGB (175,238,238)},
596 {"PaleTurquoise" , PALETTERGB (175,238,238)},
597 {"dark turquoise" , PALETTERGB ( 0,206,209)},
598 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
599 {"medium turquoise" , PALETTERGB ( 72,209,204)},
600 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
601 {"turquoise" , PALETTERGB ( 64,224,208)},
602 {"cyan" , PALETTERGB ( 0,255,255)},
603 {"light cyan" , PALETTERGB (224,255,255)},
604 {"LightCyan" , PALETTERGB (224,255,255)},
605 {"cadet blue" , PALETTERGB ( 95,158,160)},
606 {"CadetBlue" , PALETTERGB ( 95,158,160)},
607 {"medium aquamarine" , PALETTERGB (102,205,170)},
608 {"MediumAquamarine" , PALETTERGB (102,205,170)},
609 {"aquamarine" , PALETTERGB (127,255,212)},
610 {"dark green" , PALETTERGB ( 0,100, 0)},
611 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
612 {"dark olive green" , PALETTERGB ( 85,107, 47)},
613 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
614 {"dark sea green" , PALETTERGB (143,188,143)},
615 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
616 {"sea green" , PALETTERGB ( 46,139, 87)},
617 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
618 {"medium sea green" , PALETTERGB ( 60,179,113)},
619 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
620 {"light sea green" , PALETTERGB ( 32,178,170)},
621 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
622 {"pale green" , PALETTERGB (152,251,152)},
623 {"PaleGreen" , PALETTERGB (152,251,152)},
624 {"spring green" , PALETTERGB ( 0,255,127)},
625 {"SpringGreen" , PALETTERGB ( 0,255,127)},
626 {"lawn green" , PALETTERGB (124,252, 0)},
627 {"LawnGreen" , PALETTERGB (124,252, 0)},
628 {"green" , PALETTERGB ( 0,255, 0)},
629 {"chartreuse" , PALETTERGB (127,255, 0)},
630 {"medium spring green" , PALETTERGB ( 0,250,154)},
631 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
632 {"green yellow" , PALETTERGB (173,255, 47)},
633 {"GreenYellow" , PALETTERGB (173,255, 47)},
634 {"lime green" , PALETTERGB ( 50,205, 50)},
635 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
636 {"yellow green" , PALETTERGB (154,205, 50)},
637 {"YellowGreen" , PALETTERGB (154,205, 50)},
638 {"forest green" , PALETTERGB ( 34,139, 34)},
639 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
640 {"olive drab" , PALETTERGB (107,142, 35)},
641 {"OliveDrab" , PALETTERGB (107,142, 35)},
642 {"dark khaki" , PALETTERGB (189,183,107)},
643 {"DarkKhaki" , PALETTERGB (189,183,107)},
644 {"khaki" , PALETTERGB (240,230,140)},
645 {"pale goldenrod" , PALETTERGB (238,232,170)},
646 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
647 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
648 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
649 {"light yellow" , PALETTERGB (255,255,224)},
650 {"LightYellow" , PALETTERGB (255,255,224)},
651 {"yellow" , PALETTERGB (255,255, 0)},
652 {"gold" , PALETTERGB (255,215, 0)},
653 {"light goldenrod" , PALETTERGB (238,221,130)},
654 {"LightGoldenrod" , PALETTERGB (238,221,130)},
655 {"goldenrod" , PALETTERGB (218,165, 32)},
656 {"dark goldenrod" , PALETTERGB (184,134, 11)},
657 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
658 {"rosy brown" , PALETTERGB (188,143,143)},
659 {"RosyBrown" , PALETTERGB (188,143,143)},
660 {"indian red" , PALETTERGB (205, 92, 92)},
661 {"IndianRed" , PALETTERGB (205, 92, 92)},
662 {"saddle brown" , PALETTERGB (139, 69, 19)},
663 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
664 {"sienna" , PALETTERGB (160, 82, 45)},
665 {"peru" , PALETTERGB (205,133, 63)},
666 {"burlywood" , PALETTERGB (222,184,135)},
667 {"beige" , PALETTERGB (245,245,220)},
668 {"wheat" , PALETTERGB (245,222,179)},
669 {"sandy brown" , PALETTERGB (244,164, 96)},
670 {"SandyBrown" , PALETTERGB (244,164, 96)},
671 {"tan" , PALETTERGB (210,180,140)},
672 {"chocolate" , PALETTERGB (210,105, 30)},
673 {"firebrick" , PALETTERGB (178,34, 34)},
674 {"brown" , PALETTERGB (165,42, 42)},
675 {"dark salmon" , PALETTERGB (233,150,122)},
676 {"DarkSalmon" , PALETTERGB (233,150,122)},
677 {"salmon" , PALETTERGB (250,128,114)},
678 {"light salmon" , PALETTERGB (255,160,122)},
679 {"LightSalmon" , PALETTERGB (255,160,122)},
680 {"orange" , PALETTERGB (255,165, 0)},
681 {"dark orange" , PALETTERGB (255,140, 0)},
682 {"DarkOrange" , PALETTERGB (255,140, 0)},
683 {"coral" , PALETTERGB (255,127, 80)},
684 {"light coral" , PALETTERGB (240,128,128)},
685 {"LightCoral" , PALETTERGB (240,128,128)},
686 {"tomato" , PALETTERGB (255, 99, 71)},
687 {"orange red" , PALETTERGB (255, 69, 0)},
688 {"OrangeRed" , PALETTERGB (255, 69, 0)},
689 {"red" , PALETTERGB (255, 0, 0)},
690 {"hot pink" , PALETTERGB (255,105,180)},
691 {"HotPink" , PALETTERGB (255,105,180)},
692 {"deep pink" , PALETTERGB (255, 20,147)},
693 {"DeepPink" , PALETTERGB (255, 20,147)},
694 {"pink" , PALETTERGB (255,192,203)},
695 {"light pink" , PALETTERGB (255,182,193)},
696 {"LightPink" , PALETTERGB (255,182,193)},
697 {"pale violet red" , PALETTERGB (219,112,147)},
698 {"PaleVioletRed" , PALETTERGB (219,112,147)},
699 {"maroon" , PALETTERGB (176, 48, 96)},
700 {"medium violet red" , PALETTERGB (199, 21,133)},
701 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
702 {"violet red" , PALETTERGB (208, 32,144)},
703 {"VioletRed" , PALETTERGB (208, 32,144)},
704 {"magenta" , PALETTERGB (255, 0,255)},
705 {"violet" , PALETTERGB (238,130,238)},
706 {"plum" , PALETTERGB (221,160,221)},
707 {"orchid" , PALETTERGB (218,112,214)},
708 {"medium orchid" , PALETTERGB (186, 85,211)},
709 {"MediumOrchid" , PALETTERGB (186, 85,211)},
710 {"dark orchid" , PALETTERGB (153, 50,204)},
711 {"DarkOrchid" , PALETTERGB (153, 50,204)},
712 {"dark violet" , PALETTERGB (148, 0,211)},
713 {"DarkViolet" , PALETTERGB (148, 0,211)},
714 {"blue violet" , PALETTERGB (138, 43,226)},
715 {"BlueViolet" , PALETTERGB (138, 43,226)},
716 {"purple" , PALETTERGB (160, 32,240)},
717 {"medium purple" , PALETTERGB (147,112,219)},
718 {"MediumPurple" , PALETTERGB (147,112,219)},
719 {"thistle" , PALETTERGB (216,191,216)},
720 {"gray0" , PALETTERGB ( 0, 0, 0)},
721 {"grey0" , PALETTERGB ( 0, 0, 0)},
722 {"dark grey" , PALETTERGB (169,169,169)},
723 {"DarkGrey" , PALETTERGB (169,169,169)},
724 {"dark gray" , PALETTERGB (169,169,169)},
725 {"DarkGray" , PALETTERGB (169,169,169)},
726 {"dark blue" , PALETTERGB ( 0, 0,139)},
727 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
728 {"dark cyan" , PALETTERGB ( 0,139,139)},
729 {"DarkCyan" , PALETTERGB ( 0,139,139)},
730 {"dark magenta" , PALETTERGB (139, 0,139)},
731 {"DarkMagenta" , PALETTERGB (139, 0,139)},
732 {"dark red" , PALETTERGB (139, 0, 0)},
733 {"DarkRed" , PALETTERGB (139, 0, 0)},
734 {"light green" , PALETTERGB (144,238,144)},
735 {"LightGreen" , PALETTERGB (144,238,144)},
738 static Lisp_Object
739 w32_default_color_map (void)
741 int i;
742 colormap_t *pc = w32_color_map;
743 Lisp_Object cmap;
745 block_input ();
747 cmap = Qnil;
749 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
750 cmap = Fcons (Fcons (build_string (pc->name),
751 make_number (pc->colorref)),
752 cmap);
754 unblock_input ();
756 return (cmap);
759 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
760 0, 0, 0, doc: /* Return the default color map. */)
761 (void)
763 return w32_default_color_map ();
766 static Lisp_Object
767 w32_color_map_lookup (const char *colorname)
769 Lisp_Object tail, ret = Qnil;
771 block_input ();
773 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
775 register Lisp_Object elt, tem;
777 elt = XCAR (tail);
778 if (!CONSP (elt)) continue;
780 tem = XCAR (elt);
782 if (lstrcmpi (SSDATA (tem), colorname) == 0)
784 ret = Fcdr (elt);
785 break;
788 maybe_quit ();
791 unblock_input ();
793 return ret;
797 static void
798 add_system_logical_colors_to_map (Lisp_Object *system_colors)
800 HKEY colors_key;
802 /* Other registry operations are done with input blocked. */
803 block_input ();
805 /* Look for "Control Panel/Colors" under User and Machine registry
806 settings. */
807 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
808 KEY_READ, &colors_key) == ERROR_SUCCESS
809 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
810 KEY_READ, &colors_key) == ERROR_SUCCESS)
812 /* List all keys. */
813 char color_buffer[64];
814 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
815 int index = 0;
816 DWORD name_size, color_size;
817 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
819 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
820 color_size = sizeof (color_buffer);
822 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
824 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
825 NULL, NULL, (LPBYTE)color_buffer, &color_size)
826 == ERROR_SUCCESS)
828 unsigned r, g, b;
829 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
830 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
831 make_number (RGB (r, g, b))),
832 *system_colors);
834 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
835 color_size = sizeof (color_buffer);
836 index++;
838 RegCloseKey (colors_key);
841 unblock_input ();
845 static Lisp_Object
846 x_to_w32_color (const char * colorname)
848 register Lisp_Object ret = Qnil;
850 block_input ();
852 if (colorname[0] == '#')
854 /* Could be an old-style RGB Device specification. */
855 int size = strlen (colorname + 1);
856 char *color = alloca (size + 1);
858 strcpy (color, colorname + 1);
859 if (size == 3 || size == 6 || size == 9 || size == 12)
861 UINT colorval;
862 int i, pos;
863 pos = 0;
864 size /= 3;
865 colorval = 0;
867 for (i = 0; i < 3; i++)
869 char *end;
870 char t;
871 unsigned long value;
873 /* The check for 'x' in the following conditional takes into
874 account the fact that strtol allows a "0x" in front of
875 our numbers, and we don't. */
876 if (!isxdigit (color[0]) || color[1] == 'x')
877 break;
878 t = color[size];
879 color[size] = '\0';
880 value = strtoul (color, &end, 16);
881 color[size] = t;
882 if (errno == ERANGE || end - color != size)
883 break;
884 switch (size)
886 case 1:
887 value = value * 0x10;
888 break;
889 case 2:
890 break;
891 case 3:
892 value /= 0x10;
893 break;
894 case 4:
895 value /= 0x100;
896 break;
898 colorval |= (value << pos);
899 pos += 0x8;
900 if (i == 2)
902 unblock_input ();
903 XSETINT (ret, colorval);
904 return ret;
906 color = end;
910 else if (strnicmp (colorname, "rgb:", 4) == 0)
912 const char *color;
913 UINT colorval;
914 int i, pos;
915 pos = 0;
917 colorval = 0;
918 color = colorname + 4;
919 for (i = 0; i < 3; i++)
921 char *end;
922 unsigned long value;
924 /* The check for 'x' in the following conditional takes into
925 account the fact that strtol allows a "0x" in front of
926 our numbers, and we don't. */
927 if (!isxdigit (color[0]) || color[1] == 'x')
928 break;
929 value = strtoul (color, &end, 16);
930 if (errno == ERANGE)
931 break;
932 switch (end - color)
934 case 1:
935 value = value * 0x10 + value;
936 break;
937 case 2:
938 break;
939 case 3:
940 value /= 0x10;
941 break;
942 case 4:
943 value /= 0x100;
944 break;
945 default:
946 value = ULONG_MAX;
948 if (value == ULONG_MAX)
949 break;
950 colorval |= (value << pos);
951 pos += 0x8;
952 if (i == 2)
954 if (*end != '\0')
955 break;
956 unblock_input ();
957 XSETINT (ret, colorval);
958 return ret;
960 if (*end != '/')
961 break;
962 color = end + 1;
965 else if (strnicmp (colorname, "rgbi:", 5) == 0)
967 /* This is an RGB Intensity specification. */
968 const char *color;
969 UINT colorval;
970 int i, pos;
971 pos = 0;
973 colorval = 0;
974 color = colorname + 5;
975 for (i = 0; i < 3; i++)
977 char *end;
978 double value;
979 UINT val;
981 value = strtod (color, &end);
982 if (errno == ERANGE)
983 break;
984 if (value < 0.0 || value > 1.0)
985 break;
986 val = (UINT)(0x100 * value);
987 /* We used 0x100 instead of 0xFF to give a continuous
988 range between 0.0 and 1.0 inclusive. The next statement
989 fixes the 1.0 case. */
990 if (val == 0x100)
991 val = 0xFF;
992 colorval |= (val << pos);
993 pos += 0x8;
994 if (i == 2)
996 if (*end != '\0')
997 break;
998 unblock_input ();
999 XSETINT (ret, colorval);
1000 return ret;
1002 if (*end != '/')
1003 break;
1004 color = end + 1;
1007 /* I am not going to attempt to handle any of the CIE color schemes
1008 or TekHVC, since I don't know the algorithms for conversion to
1009 RGB. */
1011 /* If we fail to lookup the color name in w32_color_map, then check the
1012 colorname to see if it can be crudely approximated: If the X color
1013 ends in a number (e.g., "darkseagreen2"), strip the number and
1014 return the result of looking up the base color name. */
1015 ret = w32_color_map_lookup (colorname);
1016 if (NILP (ret))
1018 int len = strlen (colorname);
1020 if (isdigit (colorname[len - 1]))
1022 char *ptr, *approx = alloca (len + 1);
1024 strcpy (approx, colorname);
1025 ptr = &approx[len - 1];
1026 while (ptr > approx && isdigit (*ptr))
1027 *ptr-- = '\0';
1029 ret = w32_color_map_lookup (approx);
1033 unblock_input ();
1034 return ret;
1037 void
1038 w32_regenerate_palette (struct frame *f)
1040 struct w32_palette_entry * list;
1041 LOGPALETTE * log_palette;
1042 HPALETTE new_palette;
1043 int i;
1045 /* don't bother trying to create palette if not supported */
1046 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1047 return;
1049 log_palette = (LOGPALETTE *)
1050 alloca (sizeof (LOGPALETTE) +
1051 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1052 log_palette->palVersion = 0x300;
1053 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1055 list = FRAME_DISPLAY_INFO (f)->color_list;
1056 for (i = 0;
1057 i < FRAME_DISPLAY_INFO (f)->num_colors;
1058 i++, list = list->next)
1059 log_palette->palPalEntry[i] = list->entry;
1061 new_palette = CreatePalette (log_palette);
1063 enter_crit ();
1065 if (FRAME_DISPLAY_INFO (f)->palette)
1066 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1067 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1069 /* Realize display palette and garbage all frames. */
1070 release_frame_dc (f, get_frame_dc (f));
1072 leave_crit ();
1075 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1076 #define SET_W32_COLOR(pe, color) \
1077 do \
1079 pe.peRed = GetRValue (color); \
1080 pe.peGreen = GetGValue (color); \
1081 pe.peBlue = GetBValue (color); \
1082 pe.peFlags = 0; \
1083 } while (0)
1085 #if 0
1086 /* Keep these around in case we ever want to track color usage. */
1087 void
1088 w32_map_color (struct frame *f, COLORREF color)
1090 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1092 if (NILP (Vw32_enable_palette))
1093 return;
1095 /* check if color is already mapped */
1096 while (list)
1098 if (W32_COLOR (list->entry) == color)
1100 ++list->refcount;
1101 return;
1103 list = list->next;
1106 /* not already mapped, so add to list and recreate Windows palette */
1107 list = xmalloc (sizeof (struct w32_palette_entry));
1108 SET_W32_COLOR (list->entry, color);
1109 list->refcount = 1;
1110 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1111 FRAME_DISPLAY_INFO (f)->color_list = list;
1112 FRAME_DISPLAY_INFO (f)->num_colors++;
1114 /* set flag that palette must be regenerated */
1115 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1118 void
1119 w32_unmap_color (struct frame *f, COLORREF color)
1121 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1122 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1124 if (NILP (Vw32_enable_palette))
1125 return;
1127 /* check if color is already mapped */
1128 while (list)
1130 if (W32_COLOR (list->entry) == color)
1132 if (--list->refcount == 0)
1134 *prev = list->next;
1135 xfree (list);
1136 FRAME_DISPLAY_INFO (f)->num_colors--;
1137 break;
1139 else
1140 return;
1142 prev = &list->next;
1143 list = list->next;
1146 /* set flag that palette must be regenerated */
1147 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1149 #endif
1152 /* Gamma-correct COLOR on frame F. */
1154 void
1155 gamma_correct (struct frame *f, COLORREF *color)
1157 if (f->gamma)
1159 *color = PALETTERGB (
1160 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1161 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1162 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1167 /* Decide if color named COLOR is valid for the display associated with
1168 the selected frame; if so, return the rgb values in COLOR_DEF.
1169 If ALLOC is nonzero, allocate a new colormap cell. */
1172 w32_defined_color (struct frame *f, const char *color, XColor *color_def,
1173 bool alloc_p)
1175 register Lisp_Object tem;
1176 COLORREF w32_color_ref;
1178 tem = x_to_w32_color (color);
1180 if (!NILP (tem))
1182 if (f)
1184 /* Apply gamma correction. */
1185 w32_color_ref = XUINT (tem);
1186 gamma_correct (f, &w32_color_ref);
1187 XSETINT (tem, w32_color_ref);
1190 /* Map this color to the palette if it is enabled. */
1191 if (!NILP (Vw32_enable_palette))
1193 struct w32_palette_entry * entry =
1194 one_w32_display_info.color_list;
1195 struct w32_palette_entry ** prev =
1196 &one_w32_display_info.color_list;
1198 /* check if color is already mapped */
1199 while (entry)
1201 if (W32_COLOR (entry->entry) == XUINT (tem))
1202 break;
1203 prev = &entry->next;
1204 entry = entry->next;
1207 if (entry == NULL && alloc_p)
1209 /* not already mapped, so add to list */
1210 entry = xmalloc (sizeof (struct w32_palette_entry));
1211 SET_W32_COLOR (entry->entry, XUINT (tem));
1212 entry->next = NULL;
1213 *prev = entry;
1214 one_w32_display_info.num_colors++;
1216 /* set flag that palette must be regenerated */
1217 one_w32_display_info.regen_palette = TRUE;
1220 /* Ensure COLORREF value is snapped to nearest color in (default)
1221 palette by simulating the PALETTERGB macro. This works whether
1222 or not the display device has a palette. */
1223 w32_color_ref = XUINT (tem) | 0x2000000;
1225 color_def->pixel = w32_color_ref;
1226 color_def->red = GetRValue (w32_color_ref) * 256;
1227 color_def->green = GetGValue (w32_color_ref) * 256;
1228 color_def->blue = GetBValue (w32_color_ref) * 256;
1230 return 1;
1232 else
1234 return 0;
1238 /* Given a string ARG naming a color, compute a pixel value from it
1239 suitable for screen F.
1240 If F is not a color screen, return DEF (default) regardless of what
1241 ARG says. */
1243 static int
1244 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1246 XColor cdef;
1248 CHECK_STRING (arg);
1250 if (strcmp (SSDATA (arg), "black") == 0)
1251 return BLACK_PIX_DEFAULT (f);
1252 else if (strcmp (SSDATA (arg), "white") == 0)
1253 return WHITE_PIX_DEFAULT (f);
1255 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1256 return def;
1258 /* w32_defined_color is responsible for coping with failures
1259 by looking for a near-miss. */
1260 if (w32_defined_color (f, SSDATA (arg), &cdef, true))
1261 return cdef.pixel;
1263 /* defined_color failed; return an ultimate default. */
1264 return def;
1269 /* Functions called only from `x_set_frame_param'
1270 to set individual parameters.
1272 If FRAME_W32_WINDOW (f) is 0,
1273 the frame is being created and its window does not exist yet.
1274 In that case, just record the parameter's new value
1275 in the standard place; do not attempt to change the window. */
1277 void
1278 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1280 struct w32_output *x = f->output_data.w32;
1281 PIX_TYPE fg, old_fg;
1283 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1284 old_fg = FRAME_FOREGROUND_PIXEL (f);
1285 FRAME_FOREGROUND_PIXEL (f) = fg;
1287 if (FRAME_W32_WINDOW (f) != 0)
1289 if (x->cursor_pixel == old_fg)
1291 x->cursor_pixel = fg;
1292 x->cursor_gc->background = fg;
1295 update_face_from_frame_parameter (f, Qforeground_color, arg);
1296 if (FRAME_VISIBLE_P (f))
1297 redraw_frame (f);
1301 void
1302 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1304 FRAME_BACKGROUND_PIXEL (f)
1305 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1307 if (FRAME_W32_WINDOW (f) != 0)
1309 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1310 FRAME_BACKGROUND_PIXEL (f));
1312 update_face_from_frame_parameter (f, Qbackground_color, arg);
1314 if (FRAME_VISIBLE_P (f))
1315 redraw_frame (f);
1319 void
1320 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1322 #if 0
1323 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1324 int count;
1325 #endif
1326 int mask_color;
1328 if (!EQ (Qnil, arg))
1329 f->output_data.w32->mouse_pixel
1330 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1331 mask_color = FRAME_BACKGROUND_PIXEL (f);
1333 /* Don't let pointers be invisible. */
1334 if (mask_color == f->output_data.w32->mouse_pixel
1335 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1336 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1338 #if 0 /* TODO : Mouse cursor customization. */
1339 block_input ();
1341 /* It's not okay to crash if the user selects a screwy cursor. */
1342 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1344 if (!EQ (Qnil, Vx_pointer_shape))
1346 CHECK_NUMBER (Vx_pointer_shape);
1347 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1349 else
1350 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1351 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1353 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1355 CHECK_NUMBER (Vx_nontext_pointer_shape);
1356 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1357 XINT (Vx_nontext_pointer_shape));
1359 else
1360 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1361 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1363 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1365 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1366 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1367 XINT (Vx_hourglass_pointer_shape));
1369 else
1370 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1371 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1373 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1374 if (!EQ (Qnil, Vx_mode_pointer_shape))
1376 CHECK_NUMBER (Vx_mode_pointer_shape);
1377 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1378 XINT (Vx_mode_pointer_shape));
1380 else
1381 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1382 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1384 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1386 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1387 hand_cursor
1388 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1389 XINT (Vx_sensitive_text_pointer_shape));
1391 else
1392 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1394 if (!NILP (Vx_window_horizontal_drag_shape))
1396 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1397 horizontal_drag_cursor
1398 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1399 XINT (Vx_window_horizontal_drag_shape));
1401 else
1402 horizontal_drag_cursor
1403 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1405 if (!NILP (Vx_window_vertical_drag_shape))
1407 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1408 vertical_drag_cursor
1409 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1410 XINT (Vx_window_vertical_drag_shape));
1412 else
1413 vertical_drag_cursor
1414 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1416 /* Check and report errors with the above calls. */
1417 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1418 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1421 XColor fore_color, back_color;
1423 fore_color.pixel = f->output_data.w32->mouse_pixel;
1424 back_color.pixel = mask_color;
1425 XQueryColor (FRAME_W32_DISPLAY (f),
1426 DefaultColormap (FRAME_W32_DISPLAY (f),
1427 DefaultScreen (FRAME_W32_DISPLAY (f))),
1428 &fore_color);
1429 XQueryColor (FRAME_W32_DISPLAY (f),
1430 DefaultColormap (FRAME_W32_DISPLAY (f),
1431 DefaultScreen (FRAME_W32_DISPLAY (f))),
1432 &back_color);
1433 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1434 &fore_color, &back_color);
1435 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1436 &fore_color, &back_color);
1437 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1438 &fore_color, &back_color);
1439 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1440 &fore_color, &back_color);
1441 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1442 &fore_color, &back_color);
1445 if (FRAME_W32_WINDOW (f) != 0)
1446 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1448 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1449 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1450 f->output_data.w32->text_cursor = cursor;
1452 if (nontext_cursor != f->output_data.w32->nontext_cursor
1453 && f->output_data.w32->nontext_cursor != 0)
1454 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1455 f->output_data.w32->nontext_cursor = nontext_cursor;
1457 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1458 && f->output_data.w32->hourglass_cursor != 0)
1459 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1460 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1462 if (mode_cursor != f->output_data.w32->modeline_cursor
1463 && f->output_data.w32->modeline_cursor != 0)
1464 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1465 f->output_data.w32->modeline_cursor = mode_cursor;
1467 if (hand_cursor != f->output_data.w32->hand_cursor
1468 && f->output_data.w32->hand_cursor != 0)
1469 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1470 f->output_data.w32->hand_cursor = hand_cursor;
1472 XFlush (FRAME_W32_DISPLAY (f));
1473 unblock_input ();
1475 update_face_from_frame_parameter (f, Qmouse_color, arg);
1476 #endif /* TODO */
1479 void
1480 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1482 unsigned long fore_pixel, pixel;
1484 if (!NILP (Vx_cursor_fore_pixel))
1485 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1486 WHITE_PIX_DEFAULT (f));
1487 else
1488 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1490 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1492 /* Make sure that the cursor color differs from the background color. */
1493 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1495 pixel = f->output_data.w32->mouse_pixel;
1496 if (pixel == fore_pixel)
1497 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1500 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1501 f->output_data.w32->cursor_pixel = pixel;
1503 if (FRAME_W32_WINDOW (f) != 0)
1505 block_input ();
1506 /* Update frame's cursor_gc. */
1507 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1508 f->output_data.w32->cursor_gc->background = pixel;
1510 unblock_input ();
1512 if (FRAME_VISIBLE_P (f))
1514 x_update_cursor (f, 0);
1515 x_update_cursor (f, 1);
1519 update_face_from_frame_parameter (f, Qcursor_color, arg);
1522 /* Set the border-color of frame F to pixel value PIX.
1523 Note that this does not fully take effect if done before
1524 F has a window. */
1526 static void
1527 x_set_border_pixel (struct frame *f, int pix)
1530 f->output_data.w32->border_pixel = pix;
1532 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1534 if (FRAME_VISIBLE_P (f))
1535 redraw_frame (f);
1539 /* Set the border-color of frame F to value described by ARG.
1540 ARG can be a string naming a color.
1541 The border-color is used for the border that is drawn by the server.
1542 Note that this does not fully take effect if done before
1543 F has a window; it must be redone when the window is created. */
1545 void
1546 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1548 int pix;
1550 CHECK_STRING (arg);
1551 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1552 x_set_border_pixel (f, pix);
1553 update_face_from_frame_parameter (f, Qborder_color, arg);
1557 void
1558 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1560 set_frame_cursor_types (f, arg);
1563 void
1564 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1566 bool result;
1568 if (NILP (arg) && NILP (oldval))
1569 return;
1571 if (STRINGP (arg) && STRINGP (oldval)
1572 && EQ (Fstring_equal (oldval, arg), Qt))
1573 return;
1575 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1576 return;
1578 block_input ();
1580 result = x_bitmap_icon (f, arg);
1581 if (result)
1583 unblock_input ();
1584 error ("No icon window available");
1587 unblock_input ();
1590 void
1591 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1593 if (STRINGP (arg))
1595 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1596 return;
1598 else if (!NILP (arg) || NILP (oldval))
1599 return;
1601 fset_icon_name (f, arg);
1603 #if 0
1604 if (f->output_data.w32->icon_bitmap != 0)
1605 return;
1607 block_input ();
1609 result = x_text_icon (f,
1610 SSDATA ((!NILP (f->icon_name)
1611 ? f->icon_name
1612 : !NILP (f->title)
1613 ? f->title
1614 : f->name)));
1616 if (result)
1618 unblock_input ();
1619 error ("No icon window available");
1622 /* If the window was unmapped (and its icon was mapped),
1623 the new icon is not mapped, so map the window in its stead. */
1624 if (FRAME_VISIBLE_P (f))
1626 #ifdef USE_X_TOOLKIT
1627 XtPopup (f->output_data.w32->widget, XtGrabNone);
1628 #endif
1629 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1632 XFlush (FRAME_W32_DISPLAY (f));
1633 unblock_input ();
1634 #endif
1638 * x_clear_under_internal_border:
1640 * Clear area of frame F's internal border. If the internal border face
1641 * of F has been specified (is not null), fill the area with that face.
1643 void
1644 x_clear_under_internal_border (struct frame *f)
1646 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1648 /* Clear border if it's larger than before. */
1649 if (border != 0)
1651 HDC hdc = get_frame_dc (f);
1652 int width = FRAME_PIXEL_WIDTH (f);
1653 int height = FRAME_PIXEL_HEIGHT (f);
1654 struct face *face = FACE_FROM_ID_OR_NULL (f, INTERNAL_BORDER_FACE_ID);
1656 block_input ();
1657 if (face)
1659 /* Fill border with internal border face. */
1660 unsigned long color = face->background;
1662 w32_fill_area (f, hdc, color, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1663 w32_fill_area (f, hdc, color, 0, 0, border, height);
1664 w32_fill_area (f, hdc, color, width - border, 0, border, height);
1665 w32_fill_area (f, hdc, color, 0, height - border, width, border);
1667 else
1669 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1670 w32_clear_area (f, hdc, 0, 0, border, height);
1671 w32_clear_area (f, hdc, width - border, 0, border, height);
1672 w32_clear_area (f, hdc, 0, height - border, width, border);
1674 release_frame_dc (f, hdc);
1675 unblock_input ();
1681 * x_set_internal_border_width:
1683 * Set width of frame F's internal border to ARG pixels. ARG < 0 is
1684 * treated like ARG = 0.
1686 void
1687 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1689 int border;
1691 CHECK_TYPE_RANGED_INTEGER (int, arg);
1692 border = max (XINT (arg), 0);
1694 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1696 f->internal_border_width = border;
1698 if (FRAME_X_WINDOW (f) != 0)
1700 adjust_frame_size (f, -1, -1, 3, false, Qinternal_border_width);
1702 if (FRAME_VISIBLE_P (f))
1703 x_clear_under_internal_border (f);
1710 * x_set_menu_bar_lines:
1712 * Set number of lines of frame F's menu bar to VALUE. An integer
1713 * greater zero specifies 1 line and turns the menu bar on if it was off
1714 * before. Any other value specifies 0 lines and turns the menu bar off
1715 * if it was on before.
1717 void
1718 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1720 /* Right now, menu bars don't work properly in minibuf-only frames;
1721 most of the commands try to apply themselves to the minibuffer
1722 frame itself, and get an error because you can't switch buffers in
1723 or split the minibuffer window. Child frames don't like menu bars
1724 either. */
1725 if (!FRAME_MINIBUF_ONLY_P (f) && !FRAME_PARENT_FRAME (f))
1727 boolean old = FRAME_EXTERNAL_MENU_BAR (f);
1728 boolean new = (INTEGERP (value) && XINT (value) > 0) ? true : false;
1730 FRAME_MENU_BAR_LINES (f) = 0;
1731 FRAME_MENU_BAR_HEIGHT (f) = 0;
1733 if (old != new)
1735 FRAME_EXTERNAL_MENU_BAR (f) = new;
1737 if (!old)
1738 /* Make menu bar when there was none. Emacs 25 waited until
1739 the next redisplay for this to take effect. */
1740 set_frame_menubar (f, false, true);
1741 else
1743 /* Remove menu bar. */
1744 free_frame_menubar (f);
1746 /* Adjust the frame size so that the client (text) dimensions
1747 remain the same. Note that we resize twice: The first time
1748 upon a request from the window manager who wants to keep
1749 the height of the outer rectangle (including decorations)
1750 unchanged, and a second time because we want to keep the
1751 height of the inner rectangle (without the decorations
1752 unchanged). */
1753 adjust_frame_size (f, -1, -1, 2, false, Qmenu_bar_lines);
1756 if (FRAME_W32_WINDOW (f))
1757 x_clear_under_internal_border (f);
1759 /* Don't store anything but 1 or 0 in the parameter. */
1760 store_frame_param (f, Qmenu_bar_lines, make_number (new ? 1 : 0));
1766 /* Set the number of lines used for the tool bar of frame F to VALUE.
1767 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1768 the old number of tool bar lines (and is unused). This function may
1769 change the height of all windows on frame F to match the new tool bar
1770 height. By design, the frame's height doesn't change (but maybe it
1771 should if we don't get enough space otherwise). */
1773 void
1774 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1776 int nlines;
1778 /* Treat tool bars like menu bars. */
1779 if (FRAME_MINIBUF_ONLY_P (f))
1780 return;
1782 /* Use VALUE only if an integer >= 0. */
1783 if (INTEGERP (value) && XINT (value) >= 0)
1784 nlines = XFASTINT (value);
1785 else
1786 nlines = 0;
1788 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1792 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1793 void
1794 x_change_tool_bar_height (struct frame *f, int height)
1796 int unit = FRAME_LINE_HEIGHT (f);
1797 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1798 int lines = (height + unit - 1) / unit;
1799 Lisp_Object fullscreen;
1801 /* Make sure we redisplay all windows in this frame. */
1802 windows_or_buffers_changed = 23;
1804 /* Recalculate tool bar and frame text sizes. */
1805 FRAME_TOOL_BAR_HEIGHT (f) = height;
1806 FRAME_TOOL_BAR_LINES (f) = lines;
1807 /* Store `tool-bar-lines' and `height' frame parameters. */
1808 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1809 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1811 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1813 clear_frame (f);
1814 clear_current_matrices (f);
1817 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1818 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1820 /* Recalculate toolbar height. */
1821 f->n_tool_bar_rows = 0;
1822 if (old_height == 0
1823 && (!f->after_make_frame
1824 || NILP (frame_inhibit_implied_resize)
1825 || (CONSP (frame_inhibit_implied_resize)
1826 && NILP (Fmemq (Qtool_bar_lines, frame_inhibit_implied_resize)))))
1827 f->tool_bar_redisplayed = f->tool_bar_resized = false;
1829 adjust_frame_size (f, -1, -1,
1830 ((!f->tool_bar_resized
1831 && (NILP (fullscreen =
1832 get_frame_param (f, Qfullscreen))
1833 || EQ (fullscreen, Qfullwidth))) ? 1
1834 : (old_height == 0 || height == 0) ? 2
1835 : 4),
1836 false, Qtool_bar_lines);
1838 f->tool_bar_resized = f->tool_bar_redisplayed;
1840 /* adjust_frame_size might not have done anything, garbage frame
1841 here. */
1842 adjust_frame_glyphs (f);
1843 SET_FRAME_GARBAGED (f);
1844 if (FRAME_W32_WINDOW (f))
1845 x_clear_under_internal_border (f);
1848 static void
1849 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1851 if (FRAME_W32_WINDOW (f))
1853 block_input ();
1854 #ifdef __CYGWIN__
1855 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1856 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1857 #else
1858 /* The frame's title many times shows the name of the file
1859 visited in the selected window's buffer, so it makes sense to
1860 support non-ASCII characters outside of the current system
1861 codepage in the title. */
1862 if (w32_unicode_filenames)
1864 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1865 wchar_t *title_w;
1866 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1867 -1, NULL, 0);
1869 if (tlen > 0)
1871 /* Windows truncates the title text beyond what fits on
1872 a single line, so we can limit the length to some
1873 reasonably large value, and use alloca. */
1874 if (tlen > 10000)
1875 tlen = 10000;
1876 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1877 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1878 title_w, tlen);
1879 title_w[tlen] = L'\0';
1880 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1882 else /* Conversion to UTF-16 failed, so we punt. */
1883 SetWindowTextA (FRAME_W32_WINDOW (f),
1884 SSDATA (ENCODE_SYSTEM (name)));
1886 else
1887 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1888 #endif
1889 unblock_input ();
1893 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1894 w32_id_name.
1896 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1897 name; if NAME is a string, set F's name to NAME and set
1898 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1900 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1901 suggesting a new name, which lisp code should override; if
1902 F->explicit_name is set, ignore the new name; otherwise, set it. */
1904 static void
1905 x_set_name (struct frame *f, Lisp_Object name, bool explicit)
1907 /* Make sure that requests from lisp code override requests from
1908 Emacs redisplay code. */
1909 if (explicit)
1911 /* If we're switching from explicit to implicit, we had better
1912 update the mode lines and thereby update the title. */
1913 if (f->explicit_name && NILP (name))
1914 update_mode_lines = 25;
1916 f->explicit_name = ! NILP (name);
1918 else if (f->explicit_name)
1919 return;
1921 /* If NAME is nil, set the name to the w32_id_name. */
1922 if (NILP (name))
1924 /* Check for no change needed in this very common case
1925 before we do any consing. */
1926 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1927 SSDATA (f->name)))
1928 return;
1929 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1931 else
1932 CHECK_STRING (name);
1934 /* Don't change the name if it's already NAME. */
1935 if (! NILP (Fstring_equal (name, f->name)))
1936 return;
1938 fset_name (f, name);
1940 /* For setting the frame title, the title parameter should override
1941 the name parameter. */
1942 if (! NILP (f->title))
1943 name = f->title;
1945 w32_set_title_bar_text (f, name);
1948 /* This function should be called when the user's lisp code has
1949 specified a name for the frame; the name will override any set by the
1950 redisplay code. */
1951 void
1952 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1954 x_set_name (f, arg, true);
1957 /* This function should be called by Emacs redisplay code to set the
1958 name; names set this way will never override names set by the user's
1959 lisp code. */
1960 void
1961 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1963 x_set_name (f, arg, false);
1966 /* Change the title of frame F to NAME.
1967 If NAME is nil, use the frame name as the title. */
1969 void
1970 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1972 /* Don't change the title if it's already NAME. */
1973 if (EQ (name, f->title))
1974 return;
1976 update_mode_lines = 26;
1978 fset_title (f, name);
1980 if (NILP (name))
1981 name = f->name;
1983 w32_set_title_bar_text (f, name);
1986 void
1987 x_set_scroll_bar_default_width (struct frame *f)
1989 int unit = FRAME_COLUMN_WIDTH (f);
1991 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1992 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1993 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1997 void
1998 x_set_scroll_bar_default_height (struct frame *f)
2000 int unit = FRAME_LINE_HEIGHT (f);
2002 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
2003 FRAME_CONFIG_SCROLL_BAR_LINES (f)
2004 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
2008 * x_set_undecorated:
2010 * Set frame F's `undecorated' parameter. If non-nil, F's window-system
2011 * window is drawn without decorations, title, minimize/maximize boxes
2012 * and external borders. This usually means that the window cannot be
2013 * dragged, resized, iconified, maximized or deleted with the mouse. If
2014 * nil, draw the frame with all the elements listed above unless these
2015 * have been suspended via window manager settings.
2017 * Some window managers may not honor this parameter.
2019 static void
2020 x_set_undecorated (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
2022 HWND hwnd = FRAME_W32_WINDOW (f);
2023 DWORD dwStyle = GetWindowLong (hwnd, GWL_STYLE);
2024 Lisp_Object border_width = Fcdr (Fassq (Qborder_width, f->param_alist));
2026 block_input ();
2027 if (!NILP (new_value) && !FRAME_UNDECORATED (f))
2029 dwStyle = ((dwStyle & ~WS_THICKFRAME & ~WS_CAPTION)
2030 | ((NUMBERP (border_width) && (XINT (border_width) > 0))
2031 ? WS_BORDER : false));
2032 SetWindowLong (hwnd, GWL_STYLE, dwStyle);
2033 SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
2034 SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
2035 | SWP_FRAMECHANGED);
2036 FRAME_UNDECORATED (f) = true;
2038 else if (NILP (new_value) && FRAME_UNDECORATED (f))
2040 SetWindowLong (hwnd, GWL_STYLE, dwStyle | WS_THICKFRAME | WS_CAPTION
2041 | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU);
2042 SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
2043 SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
2044 | SWP_FRAMECHANGED);
2045 FRAME_UNDECORATED (f) = false;
2047 unblock_input ();
2051 * x_set_parent_frame:
2053 * Set frame F's `parent-frame' parameter. If non-nil, make F a child
2054 * frame of the frame specified by that parameter. Technically, this
2055 * makes F's window-system window a child window of the parent frame's
2056 * window-system window. If nil, make F's window-system window a
2057 * top-level window--a child of its display's root window.
2059 * A child frame is clipped at the native edges of its parent frame.
2060 * Its `left' and `top' parameters specify positions relative to the
2061 * top-left corner of its parent frame's native rectangle. Usually,
2062 * moving a parent frame moves all its child frames too, keeping their
2063 * position relative to the parent unaltered. When a parent frame is
2064 * iconified or made invisible, its child frames are made invisible.
2065 * When a parent frame is deleted, its child frames are deleted too.
2067 * A visible child frame always appears on top of its parent frame thus
2068 * obscuring parts of it. When a frame has more than one child frame,
2069 * their stacking order is specified just as that of non-child frames
2070 * relative to their display.
2072 * Whether a child frame has a menu or tool bar may be window-system or
2073 * window manager dependent. It's advisable to disable both via the
2074 * frame parameter settings.
2076 * Some window managers may not honor this parameter.
2078 static void
2079 x_set_parent_frame (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
2081 struct frame *p = NULL;
2083 if (!NILP (new_value)
2084 && (!FRAMEP (new_value)
2085 || !FRAME_LIVE_P (p = XFRAME (new_value))
2086 || !FRAME_W32_P (p)))
2088 store_frame_param (f, Qparent_frame, old_value);
2089 error ("Invalid specification of `parent-frame'");
2092 if (p != FRAME_PARENT_FRAME (f))
2094 HWND hwnd = FRAME_W32_WINDOW (f);
2095 HWND hwnd_parent = p ? FRAME_W32_WINDOW (p) : NULL;
2096 HWND hwnd_value;
2098 block_input ();
2099 hwnd_value = SetParent (hwnd, hwnd_parent);
2100 unblock_input ();
2102 if (hwnd_value)
2103 fset_parent_frame (f, new_value);
2104 else
2106 store_frame_param (f, Qparent_frame, old_value);
2107 error ("Reparenting frame failed");
2113 * x_set_skip_taskbar:
2115 * Set frame F's `skip-taskbar' parameter. If non-nil, this should
2116 * remove F's icon from the taskbar associated with the display of F's
2117 * window-system window and inhibit switching to F's window via
2118 * <Alt>-<TAB>. On Windows iconifying F will "roll in" its window at
2119 * the bottom of the desktop. If nil, lift these restrictions.
2121 * Some window managers may not honor this parameter.
2123 static void
2124 x_set_skip_taskbar (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
2126 if (!EQ (new_value, old_value))
2128 HWND hwnd = FRAME_W32_WINDOW (f);
2129 DWORD exStyle = GetWindowLong (hwnd, GWL_EXSTYLE);
2131 block_input ();
2132 /* Temporarily hide the window while changing its WS_EX_NOACTIVATE
2133 setting. */
2134 ShowWindow (hwnd, SW_HIDE);
2135 if (!NILP (new_value))
2136 SetWindowLong (hwnd, GWL_EXSTYLE, exStyle | WS_EX_NOACTIVATE);
2137 else
2138 SetWindowLong (hwnd, GWL_EXSTYLE, exStyle & ~WS_EX_NOACTIVATE);
2139 ShowWindow (hwnd, SW_SHOWNOACTIVATE);
2140 unblock_input ();
2142 FRAME_SKIP_TASKBAR (f) = !NILP (new_value);
2147 * x_set_no_focus_on_map:
2149 * Set frame F's `no-focus-on-map' parameter which, if non-nil, means
2150 * that F's window-system window does not want to receive input focus
2151 * when it is mapped. (A frame's window is mapped when the frame is
2152 * displayed for the first time and when the frame changes its state
2153 * from `iconified' or `invisible' to `visible'.)
2155 * Some window managers may not honor this parameter.
2157 static void
2158 x_set_no_focus_on_map (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
2160 if (!EQ (new_value, old_value))
2161 FRAME_NO_FOCUS_ON_MAP (f) = !NILP (new_value);
2165 * x_set_no_accept_focus:
2167 * Set frame F's `no-accept-focus' parameter which, if non-nil, hints
2168 * that F's window-system window does not want to receive input focus
2169 * via mouse clicks or by moving the mouse into it.
2171 * If non-nil, this may have the unwanted side-effect that a user cannot
2172 * scroll a non-selected frame with the mouse.
2174 * Some window managers may not honor this parameter.
2176 static void
2177 x_set_no_accept_focus (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
2179 if (!EQ (new_value, old_value))
2180 FRAME_NO_ACCEPT_FOCUS (f) = !NILP (new_value);
2184 * x_set_z_group:
2186 * Set frame F's `z-group' parameter. If `above', F's window-system
2187 * window is displayed above all windows that do not have the `above'
2188 * property set. If nil, F's window is shown below all windows that
2189 * have the `above' property set and above all windows that have the
2190 * `below' property set. If `below', F's window is displayed below all
2191 * windows that do not have the `below' property set.
2193 * Some window managers may not honor this parameter. The value `below'
2194 * is not supported on Windows.
2196 static void
2197 x_set_z_group (struct frame *f, Lisp_Object new_value, Lisp_Object old_value)
2199 HWND hwnd = FRAME_W32_WINDOW (f);
2201 if (NILP (new_value))
2203 block_input ();
2204 SetWindowPos (hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2205 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE
2206 | SWP_NOOWNERZORDER);
2207 unblock_input ();
2208 FRAME_Z_GROUP (f) = z_group_none;
2210 else if (EQ (new_value, Qabove))
2212 block_input ();
2213 SetWindowPos (hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2214 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE
2215 | SWP_NOOWNERZORDER);
2216 unblock_input ();
2217 FRAME_Z_GROUP (f) = z_group_above;
2219 else if (EQ (new_value, Qabove_suspended))
2221 block_input ();
2222 SetWindowPos (hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2223 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE
2224 | SWP_NOOWNERZORDER);
2225 unblock_input ();
2226 FRAME_Z_GROUP (f) = z_group_above_suspended;
2228 else if (EQ (new_value, Qbelow))
2229 error ("Value `below' for z-group is not supported on Windows");
2230 else
2231 error ("Invalid z-group specification");
2234 /* Subroutines for creating a frame. */
2236 Cursor w32_load_cursor (LPCTSTR);
2238 Cursor
2239 w32_load_cursor (LPCTSTR name)
2241 /* Try first to load cursor from application resource. */
2242 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
2243 name, IMAGE_CURSOR, 0, 0,
2244 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2245 if (!cursor)
2247 /* Then try to load a shared predefined cursor. */
2248 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
2249 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
2251 return cursor;
2254 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
2256 #define INIT_WINDOW_CLASS(WC) \
2257 (WC).style = CS_HREDRAW | CS_VREDRAW; \
2258 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
2259 (WC).cbClsExtra = 0; \
2260 (WC).cbWndExtra = WND_EXTRA_BYTES; \
2261 (WC).hInstance = hinst; \
2262 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
2263 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
2264 (WC).hbrBackground = NULL; \
2265 (WC).lpszMenuName = NULL; \
2267 static BOOL
2268 w32_init_class (HINSTANCE hinst)
2270 if (w32_unicode_gui)
2272 WNDCLASSW uwc;
2273 INIT_WINDOW_CLASS(uwc);
2274 uwc.lpszClassName = L"Emacs";
2276 return RegisterClassW (&uwc);
2278 else
2280 WNDCLASS wc;
2281 INIT_WINDOW_CLASS(wc);
2282 wc.lpszClassName = EMACS_CLASS;
2284 return RegisterClassA (&wc);
2288 static HWND
2289 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
2291 return CreateWindow ("SCROLLBAR", "",
2292 /* Clip siblings so we don't draw over child
2293 frames. Apparently this is not always
2294 sufficient so we also try to make bar windows
2295 bottommost. */
2296 SBS_VERT | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS,
2297 /* Position and size of scroll bar. */
2298 bar->left, bar->top, bar->width, bar->height,
2299 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2302 static HWND
2303 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
2305 return CreateWindow ("SCROLLBAR", "",
2306 /* Clip siblings so we don't draw over child
2307 frames. Apparently this is not always
2308 sufficient so we also try to make bar windows
2309 bottommost. */
2310 SBS_HORZ | WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS,
2311 /* Position and size of scroll bar. */
2312 bar->left, bar->top, bar->width, bar->height,
2313 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2316 static void
2317 w32_createwindow (struct frame *f, int *coords)
2319 HWND hwnd = NULL, parent_hwnd = NULL;
2320 RECT rect;
2321 int top, left;
2322 Lisp_Object border_width = Fcdr (Fassq (Qborder_width, f->param_alist));
2324 if (FRAME_PARENT_FRAME (f) && FRAME_W32_P (FRAME_PARENT_FRAME (f)))
2326 parent_hwnd = FRAME_W32_WINDOW (FRAME_PARENT_FRAME (f));
2327 f->output_data.w32->dwStyle = WS_CHILD | WS_CLIPSIBLINGS;
2329 if (FRAME_UNDECORATED (f))
2331 /* If we want a thin border, specify it here. */
2332 if (NUMBERP (border_width) && (XINT (border_width) > 0))
2333 f->output_data.w32->dwStyle |= WS_BORDER;
2335 else
2336 /* To decorate a child frame, list all needed elements. */
2337 f->output_data.w32->dwStyle |= (WS_THICKFRAME | WS_CAPTION
2338 | WS_MAXIMIZEBOX | WS_MINIMIZEBOX
2339 | WS_SYSMENU);
2341 else if (FRAME_UNDECORATED (f))
2343 /* All attempts to start with ~WS_OVERLAPPEDWINDOW or overlapped
2344 with all other style elements negated failed here. */
2345 f->output_data.w32->dwStyle = WS_POPUP;
2347 /* If we want a thin border, specify it here. */
2348 if (NUMBERP (border_width) && (XINT (border_width) > 0))
2349 f->output_data.w32->dwStyle |= WS_BORDER;
2351 else
2352 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
2354 /* Always clip children. */
2355 f->output_data.w32->dwStyle |= WS_CLIPCHILDREN;
2357 rect.left = rect.top = 0;
2358 rect.right = FRAME_PIXEL_WIDTH (f);
2359 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2361 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2362 FRAME_EXTERNAL_MENU_BAR (f) && !parent_hwnd);
2364 /* Do first time app init */
2365 w32_init_class (hinst);
2367 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2369 left = f->left_pos;
2370 top = f->top_pos;
2372 else
2374 left = coords[0];
2375 top = coords[1];
2378 FRAME_W32_WINDOW (f) = hwnd
2379 = CreateWindow (EMACS_CLASS, f->namebuf, f->output_data.w32->dwStyle,
2380 left, top, rect.right - rect.left, rect.bottom - rect.top,
2381 parent_hwnd, NULL, hinst, NULL);
2383 if (hwnd)
2385 if (FRAME_SKIP_TASKBAR (f))
2386 SetWindowLong (hwnd, GWL_EXSTYLE,
2387 GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_NOACTIVATE);
2389 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2390 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2391 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2392 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2393 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2394 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2396 /* Enable drag-n-drop. */
2397 DragAcceptFiles (hwnd, TRUE);
2399 /* Do this to discard the default setting specified by our parent. */
2400 ShowWindow (hwnd, SW_HIDE);
2402 /* Update frame positions. */
2403 GetWindowRect (hwnd, &rect);
2405 if (parent_hwnd)
2406 /* For a child window we have to get its coordinates wrt its
2407 parent. */
2408 MapWindowPoints (HWND_DESKTOP, parent_hwnd, (LPPOINT) &rect, 2);
2410 f->left_pos = rect.left;
2411 f->top_pos = rect.top;
2415 static void
2416 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2418 wmsg->msg.hwnd = hwnd;
2419 wmsg->msg.message = msg;
2420 wmsg->msg.wParam = wParam;
2421 wmsg->msg.lParam = lParam;
2422 wmsg->msg.time = GetMessageTime ();
2424 post_msg (wmsg);
2427 #ifdef WINDOWSNT
2428 /* The Windows keyboard hook callback. */
2429 static LRESULT CALLBACK
2430 funhook (int code, WPARAM w, LPARAM l)
2432 INPUT inputs[2];
2433 HWND focus = GetFocus ();
2434 int console = 0;
2435 KBDLLHOOKSTRUCT const *hs = (KBDLLHOOKSTRUCT*)l;
2437 if (code < 0 || (hs->flags & LLKHF_INJECTED))
2438 return CallNextHookEx (0, code, w, l);
2440 /* The keyboard hook sees keyboard input on all processes (except
2441 elevated ones, when Emacs itself is not elevated). As such,
2442 care must be taken to only filter out keyboard input when Emacs
2443 itself is on the foreground.
2445 GetFocus returns a non-NULL window if another application is active,
2446 and always for a console Emacs process. For a console Emacs, determine
2447 focus by checking if the current foreground window is the process's
2448 console window. */
2449 if (focus == NULL && kbdhook.console != NULL)
2451 if (GetForegroundWindow () == kbdhook.console)
2453 focus = kbdhook.console;
2454 console = 1;
2458 /* First, check hooks for the left and right Windows keys. */
2459 if (hs->vkCode == VK_LWIN || hs->vkCode == VK_RWIN)
2461 if (focus != NULL && (w == WM_KEYDOWN || w == WM_SYSKEYDOWN))
2463 /* The key is being pressed in an Emacs window. */
2464 if (hs->vkCode == VK_LWIN && !kbdhook.lwindown)
2466 kbdhook.lwindown = 1;
2467 kbdhook.winseen = 1;
2468 kbdhook.winsdown++;
2470 else if (hs->vkCode == VK_RWIN && !kbdhook.rwindown)
2472 kbdhook.rwindown = 1;
2473 kbdhook.winseen = 1;
2474 kbdhook.winsdown++;
2476 /* Returning 1 here drops the keypress without further processing.
2477 If the keypress was allowed to go through, the normal Windows
2478 hotkeys would take over. */
2479 return 1;
2481 else if (kbdhook.winsdown > 0 && (w == WM_KEYUP || w == WM_SYSKEYUP))
2483 /* A key that has been captured earlier is being released now. */
2484 if (hs->vkCode == VK_LWIN && kbdhook.lwindown)
2486 kbdhook.lwindown = 0;
2487 kbdhook.winsdown--;
2489 else if (hs->vkCode == VK_RWIN && kbdhook.rwindown)
2491 kbdhook.rwindown = 0;
2492 kbdhook.winsdown--;
2494 if (kbdhook.winsdown == 0 && kbdhook.winseen)
2496 if (!kbdhook.suppress_lone)
2498 /* The Windows key was pressed, then released,
2499 without any other key pressed simultaneously.
2500 Normally, this opens the Start menu, but the user
2501 can prevent this by setting the
2502 w32-pass-[lr]window-to-system variable to
2503 NIL. */
2504 if ((hs->vkCode == VK_LWIN && !NILP (Vw32_pass_lwindow_to_system)) ||
2505 (hs->vkCode == VK_RWIN && !NILP (Vw32_pass_rwindow_to_system)))
2507 /* Not prevented - Simulate the keypress to the system. */
2508 memset (inputs, 0, sizeof (inputs));
2509 inputs[0].type = INPUT_KEYBOARD;
2510 inputs[0].ki.wVk = hs->vkCode;
2511 inputs[0].ki.wScan = hs->vkCode;
2512 inputs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
2513 inputs[0].ki.time = 0;
2514 inputs[1].type = INPUT_KEYBOARD;
2515 inputs[1].ki.wVk = hs->vkCode;
2516 inputs[1].ki.wScan = hs->vkCode;
2517 inputs[1].ki.dwFlags
2518 = KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP;
2519 inputs[1].ki.time = 0;
2520 SendInput (2, inputs, sizeof (INPUT));
2522 else if (focus != NULL)
2524 /* When not passed to system, must simulate privately to Emacs. */
2525 PostMessage (focus, WM_SYSKEYDOWN, hs->vkCode, 0);
2526 PostMessage (focus, WM_SYSKEYUP, hs->vkCode, 0);
2530 if (kbdhook.winsdown == 0)
2532 /* No Windows keys pressed anymore - clear the state flags. */
2533 kbdhook.suppress_lone = 0;
2534 kbdhook.winseen = 0;
2536 if (!kbdhook.send_win_up)
2538 /* Swallow this release message, as not to confuse
2539 applications who did not get to see the original
2540 WM_KEYDOWN message either. */
2541 return 1;
2543 kbdhook.send_win_up = 0;
2546 else if (kbdhook.winsdown > 0)
2548 /* Some other key was pressed while a captured Win key is down.
2549 This is either an Emacs registered hotkey combination, or a
2550 system hotkey. */
2551 if ((kbdhook.lwindown && kbdhook.lwin_hooked[hs->vkCode]) ||
2552 (kbdhook.rwindown && kbdhook.rwin_hooked[hs->vkCode]))
2554 /* Hooked Win-x combination, do not pass the keypress to Windows. */
2555 kbdhook.suppress_lone = 1;
2557 else if (!kbdhook.suppress_lone)
2559 /* Unhooked S-x combination; simulate the combination now
2560 (will be seen by the system). */
2561 memset (inputs, 0, sizeof (inputs));
2562 inputs[0].type = INPUT_KEYBOARD;
2563 inputs[0].ki.wVk = kbdhook.lwindown ? VK_LWIN : VK_RWIN;
2564 inputs[0].ki.wScan = kbdhook.lwindown ? VK_LWIN : VK_RWIN;
2565 inputs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
2566 inputs[0].ki.time = 0;
2567 inputs[1].type = INPUT_KEYBOARD;
2568 inputs[1].ki.wVk = hs->vkCode;
2569 inputs[1].ki.wScan = hs->scanCode;
2570 inputs[1].ki.dwFlags =
2571 (hs->flags & LLKHF_EXTENDED) ? KEYEVENTF_EXTENDEDKEY : 0;
2572 inputs[1].ki.time = 0;
2573 SendInput (2, inputs, sizeof (INPUT));
2574 /* Stop processing of this Win sequence here; the
2575 corresponding keyup messages will come through the normal
2576 channel when the keys are released. */
2577 kbdhook.suppress_lone = 1;
2578 kbdhook.send_win_up = 1;
2579 /* Swallow the original keypress (as we want the Win key
2580 down message simulated above to precede this real message). */
2581 return 1;
2585 /* Next, handle the registered Alt-* combinations. */
2586 if ((w == WM_SYSKEYDOWN || w == WM_KEYDOWN)
2587 && kbdhook.alt_hooked[hs->vkCode]
2588 && focus != NULL
2589 && (GetAsyncKeyState (VK_MENU) & 0x8000))
2591 /* Prevent the system from getting this Alt-* key - suppress the
2592 message and post as a normal keypress to Emacs. */
2593 if (console)
2595 INPUT_RECORD rec;
2596 DWORD n;
2597 rec.EventType = KEY_EVENT;
2598 rec.Event.KeyEvent.bKeyDown = TRUE;
2599 rec.Event.KeyEvent.wVirtualKeyCode = hs->vkCode;
2600 rec.Event.KeyEvent.wVirtualScanCode = hs->scanCode;
2601 rec.Event.KeyEvent.uChar.UnicodeChar = 0;
2602 rec.Event.KeyEvent.dwControlKeyState =
2603 ((GetAsyncKeyState (VK_LMENU) & 0x8000) ? LEFT_ALT_PRESSED : 0)
2604 | ((GetAsyncKeyState (VK_RMENU) & 0x8000) ? RIGHT_ALT_PRESSED : 0)
2605 | ((GetAsyncKeyState (VK_LCONTROL) & 0x8000) ? LEFT_CTRL_PRESSED : 0)
2606 | ((GetAsyncKeyState (VK_RCONTROL) & 0x8000) ? RIGHT_CTRL_PRESSED : 0)
2607 | ((GetAsyncKeyState (VK_SHIFT) & 0x8000) ? SHIFT_PRESSED : 0)
2608 | ((hs->flags & LLKHF_EXTENDED) ? ENHANCED_KEY : 0);
2609 if (w32_console_unicode_input)
2610 WriteConsoleInputW (keyboard_handle, &rec, 1, &n);
2611 else
2612 WriteConsoleInputA (keyboard_handle, &rec, 1, &n);
2614 else
2615 PostMessage (focus, w, hs->vkCode, 1 | (1<<29));
2616 return 1;
2619 /* The normal case - pass the message through. */
2620 return CallNextHookEx (0, code, w, l);
2623 /* Set up the hook; can be called several times, with matching
2624 remove_w32_kbdhook calls. */
2625 void
2626 setup_w32_kbdhook (void)
2628 kbdhook.hook_count++;
2630 /* This hook gets in the way of debugging, since when Emacs stops,
2631 its input thread stops, and there's nothing to process keyboard
2632 events, whereas this hook is global, and is invoked in the
2633 context of the thread that installed it. So we don't install the
2634 hook if the process is being debugged. */
2635 if (w32_kbdhook_active)
2637 IsDebuggerPresent_Proc is_debugger_present = (IsDebuggerPresent_Proc)
2638 GetProcAddress (GetModuleHandle ("kernel32.dll"), "IsDebuggerPresent");
2639 if (is_debugger_present && is_debugger_present ())
2640 return;
2643 /* Hooking is only available on NT architecture systems, as
2644 indicated by the w32_kbdhook_active variable. */
2645 if (kbdhook.hook_count == 1 && w32_kbdhook_active)
2647 /* Get the handle of the Emacs console window. As the
2648 GetConsoleWindow function is only available on Win2000+, a
2649 hackish workaround described in Microsoft KB article 124103
2650 (https://support.microsoft.com/en-us/kb/124103) is used for
2651 NT 4 systems. */
2652 GetConsoleWindow_Proc get_console = (GetConsoleWindow_Proc)
2653 GetProcAddress (GetModuleHandle ("kernel32.dll"), "GetConsoleWindow");
2655 if (get_console != NULL)
2656 kbdhook.console = get_console ();
2657 else
2659 GUID guid;
2660 wchar_t *oldTitle = malloc (1024 * sizeof(wchar_t));
2661 wchar_t newTitle[64];
2662 int i;
2664 CoCreateGuid (&guid);
2665 StringFromGUID2 (&guid, newTitle, 64);
2666 if (newTitle != NULL)
2668 GetConsoleTitleW (oldTitle, 1024);
2669 SetConsoleTitleW (newTitle);
2670 for (i = 0; i < 25; i++)
2672 Sleep (40);
2673 kbdhook.console = FindWindowW (NULL, newTitle);
2674 if (kbdhook.console != NULL)
2675 break;
2677 SetConsoleTitleW (oldTitle);
2679 free (oldTitle);
2682 /* Set the hook. */
2683 kbdhook.hook = SetWindowsHookEx (WH_KEYBOARD_LL, funhook,
2684 GetModuleHandle (NULL), 0);
2688 /* Remove the hook. */
2689 void
2690 remove_w32_kbdhook (void)
2692 kbdhook.hook_count--;
2693 if (kbdhook.hook_count == 0 && w32_kbdhook_active)
2695 UnhookWindowsHookEx (kbdhook.hook);
2696 kbdhook.hook = NULL;
2699 #endif /* WINDOWSNT */
2701 /* Mark a specific key combination as hooked, preventing it to be
2702 handled by the system. */
2703 static void
2704 hook_w32_key (int hook, int modifier, int vkey)
2706 char *tbl = NULL;
2708 switch (modifier)
2710 case VK_MENU:
2711 tbl = kbdhook.alt_hooked;
2712 break;
2713 case VK_LWIN:
2714 tbl = kbdhook.lwin_hooked;
2715 break;
2716 case VK_RWIN:
2717 tbl = kbdhook.rwin_hooked;
2718 break;
2721 if (tbl != NULL && vkey >= 0 && vkey <= 255)
2723 /* VK_ANY hooks all keys for this modifier */
2724 if (vkey == VK_ANY)
2725 memset (tbl, (char)hook, 256);
2726 else
2727 tbl[vkey] = (char)hook;
2728 /* Alt-<modifier>s should go through */
2729 kbdhook.alt_hooked[VK_MENU] = 0;
2730 kbdhook.alt_hooked[VK_LMENU] = 0;
2731 kbdhook.alt_hooked[VK_RMENU] = 0;
2732 kbdhook.alt_hooked[VK_CONTROL] = 0;
2733 kbdhook.alt_hooked[VK_LCONTROL] = 0;
2734 kbdhook.alt_hooked[VK_RCONTROL] = 0;
2735 kbdhook.alt_hooked[VK_SHIFT] = 0;
2736 kbdhook.alt_hooked[VK_LSHIFT] = 0;
2737 kbdhook.alt_hooked[VK_RSHIFT] = 0;
2741 #ifdef WINDOWSNT
2742 /* Check the current Win key pressed state. */
2744 check_w32_winkey_state (int vkey)
2746 /* The hook code handles grabbing of the Windows keys and Alt-* key
2747 combinations reserved by the system. Handling Alt is a bit
2748 easier, as Windows intends Alt-* shortcuts for application use in
2749 Windows; hotkeys such as Alt-tab and Alt-escape are special
2750 cases. Win-* hotkeys, on the other hand, are primarily meant for
2751 system use.
2753 As a result, when we want Emacs to be able to grab the Win-*
2754 keys, we must swallow all Win key presses in a low-level keyboard
2755 hook. Unfortunately, this means that the Emacs window procedure
2756 (and console input handler) never see the keypresses either.
2757 Thus, to check the modifier states properly, Emacs code must use
2758 the check_w32_winkey_state function that uses the flags directly
2759 updated by the hook callback. */
2760 switch (vkey)
2762 case VK_LWIN:
2763 return kbdhook.lwindown;
2764 case VK_RWIN:
2765 return kbdhook.rwindown;
2767 return 0;
2769 #endif /* WINDOWSNT */
2771 /* Reset the keyboard hook state. Locking the workstation with Win-L
2772 leaves the Win key(s) "down" from the hook's point of view - the
2773 keyup event is never seen. Thus, this function must be called when
2774 the system is locked. */
2775 static void
2776 reset_w32_kbdhook_state (void)
2778 kbdhook.lwindown = 0;
2779 kbdhook.rwindown = 0;
2780 kbdhook.winsdown = 0;
2781 kbdhook.send_win_up = 0;
2782 kbdhook.suppress_lone = 0;
2783 kbdhook.winseen = 0;
2786 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2787 between left and right keys as advertised. We test for this
2788 support dynamically, and set a flag when the support is absent. If
2789 absent, we keep track of the left and right control and alt keys
2790 ourselves. This is particularly necessary on keyboards that rely
2791 upon the AltGr key, which is represented as having the left control
2792 and right alt keys pressed. For these keyboards, we need to know
2793 when the left alt key has been pressed in addition to the AltGr key
2794 so that we can properly support M-AltGr-key sequences (such as M-@
2795 on Swedish keyboards). */
2797 #define EMACS_LCONTROL 0
2798 #define EMACS_RCONTROL 1
2799 #define EMACS_LMENU 2
2800 #define EMACS_RMENU 3
2802 static int modifiers[4];
2803 static int modifiers_recorded;
2804 static int modifier_key_support_tested;
2806 static void
2807 test_modifier_support (unsigned int wparam)
2809 unsigned int l, r;
2811 if (wparam != VK_CONTROL && wparam != VK_MENU)
2812 return;
2813 if (wparam == VK_CONTROL)
2815 l = VK_LCONTROL;
2816 r = VK_RCONTROL;
2818 else
2820 l = VK_LMENU;
2821 r = VK_RMENU;
2823 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2824 modifiers_recorded = 1;
2825 else
2826 modifiers_recorded = 0;
2827 modifier_key_support_tested = 1;
2830 static void
2831 record_keydown (unsigned int wparam, unsigned int lparam)
2833 int i;
2835 if (!modifier_key_support_tested)
2836 test_modifier_support (wparam);
2838 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2839 return;
2841 if (wparam == VK_CONTROL)
2842 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2843 else
2844 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2846 modifiers[i] = 1;
2849 static void
2850 record_keyup (unsigned int wparam, unsigned int lparam)
2852 int i;
2854 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2855 return;
2857 if (wparam == VK_CONTROL)
2858 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2859 else
2860 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2862 modifiers[i] = 0;
2865 /* Emacs can lose focus while a modifier key has been pressed. When
2866 it regains focus, be conservative and clear all modifiers since
2867 we cannot reconstruct the left and right modifier state. */
2868 static void
2869 reset_modifiers (void)
2871 SHORT ctrl, alt;
2873 if (GetFocus () == NULL)
2874 /* Emacs doesn't have keyboard focus. Do nothing. */
2875 return;
2877 ctrl = GetAsyncKeyState (VK_CONTROL);
2878 alt = GetAsyncKeyState (VK_MENU);
2880 if (!(ctrl & 0x08000))
2881 /* Clear any recorded control modifier state. */
2882 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2884 if (!(alt & 0x08000))
2885 /* Clear any recorded alt modifier state. */
2886 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2888 /* Update the state of all modifier keys, because modifiers used in
2889 hot-key combinations can get stuck on if Emacs loses focus as a
2890 result of a hot-key being pressed. */
2892 BYTE keystate[256];
2894 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2896 memset (keystate, 0, sizeof (keystate));
2897 GetKeyboardState (keystate);
2898 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2899 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2900 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2901 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2902 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2903 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2904 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2905 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2906 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2907 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2908 SetKeyboardState (keystate);
2912 /* Synchronize modifier state with what is reported with the current
2913 keystroke. Even if we cannot distinguish between left and right
2914 modifier keys, we know that, if no modifiers are set, then neither
2915 the left or right modifier should be set. */
2916 static void
2917 sync_modifiers (void)
2919 if (!modifiers_recorded)
2920 return;
2922 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2923 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2925 if (!(GetKeyState (VK_MENU) & 0x8000))
2926 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2929 static int
2930 modifier_set (int vkey)
2932 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2933 toggle keys is not an omission! If you want to add it, you will
2934 have to make changes in the default sub-case of the WM_KEYDOWN
2935 switch, because if the NUMLOCK modifier is set, the code there
2936 will directly convert any key that looks like an ASCII letter,
2937 and also downcase those that look like upper-case ASCII. */
2938 if (vkey == VK_CAPITAL)
2940 if (NILP (Vw32_enable_caps_lock))
2941 return 0;
2942 else
2943 return (GetKeyState (vkey) & 0x1);
2945 if (vkey == VK_SCROLL)
2947 if (NILP (Vw32_scroll_lock_modifier)
2948 /* w32-scroll-lock-modifier can be any non-nil value that is
2949 not one of the modifiers, in which case it shall be ignored. */
2950 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2951 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2952 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2953 || EQ (Vw32_scroll_lock_modifier, Qalt)
2954 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2955 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2956 return 0;
2957 else
2958 return (GetKeyState (vkey) & 0x1);
2960 #ifdef WINDOWSNT
2961 if (w32_kbdhook_active && (vkey == VK_LWIN || vkey == VK_RWIN))
2962 return check_w32_winkey_state (vkey);
2963 #endif
2965 if (!modifiers_recorded)
2966 return (GetKeyState (vkey) & 0x8000);
2968 switch (vkey)
2970 case VK_LCONTROL:
2971 return modifiers[EMACS_LCONTROL];
2972 case VK_RCONTROL:
2973 return modifiers[EMACS_RCONTROL];
2974 case VK_LMENU:
2975 return modifiers[EMACS_LMENU];
2976 case VK_RMENU:
2977 return modifiers[EMACS_RMENU];
2979 return (GetKeyState (vkey) & 0x8000);
2982 /* Convert between the modifier bits W32 uses and the modifier bits
2983 Emacs uses. */
2984 unsigned int w32_key_to_modifier (int);
2986 unsigned int
2987 w32_key_to_modifier (int key)
2989 Lisp_Object key_mapping;
2991 switch (key)
2993 case VK_LWIN:
2994 key_mapping = Vw32_lwindow_modifier;
2995 break;
2996 case VK_RWIN:
2997 key_mapping = Vw32_rwindow_modifier;
2998 break;
2999 case VK_APPS:
3000 key_mapping = Vw32_apps_modifier;
3001 break;
3002 case VK_SCROLL:
3003 key_mapping = Vw32_scroll_lock_modifier;
3004 break;
3005 default:
3006 key_mapping = Qnil;
3009 /* NB. This code runs in the input thread, asynchronously to the lisp
3010 thread, so we must be careful to ensure access to lisp data is
3011 thread-safe. The following code is safe because the modifier
3012 variable values are updated atomically from lisp and symbols are
3013 not relocated by GC. Also, we don't have to worry about seeing GC
3014 markbits here. */
3015 if (EQ (key_mapping, Qhyper))
3016 return hyper_modifier;
3017 if (EQ (key_mapping, Qsuper))
3018 return super_modifier;
3019 if (EQ (key_mapping, Qmeta))
3020 return meta_modifier;
3021 if (EQ (key_mapping, Qalt))
3022 return alt_modifier;
3023 if (EQ (key_mapping, Qctrl))
3024 return ctrl_modifier;
3025 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
3026 return ctrl_modifier;
3027 if (EQ (key_mapping, Qshift))
3028 return shift_modifier;
3030 /* Don't generate any modifier if not explicitly requested. */
3031 return 0;
3034 static unsigned int
3035 w32_get_modifiers (void)
3037 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
3038 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
3039 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
3040 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
3041 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
3042 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
3043 (modifier_set (VK_MENU) ?
3044 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
3047 /* We map the VK_* modifiers into console modifier constants
3048 so that we can use the same routines to handle both console
3049 and window input. */
3051 static int
3052 construct_console_modifiers (void)
3054 int mods;
3056 mods = 0;
3057 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
3058 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
3059 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
3060 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
3061 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
3062 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
3063 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
3064 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
3065 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
3066 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
3067 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
3069 return mods;
3072 static int
3073 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
3075 int mods;
3077 /* Convert to emacs modifiers. */
3078 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
3080 return mods;
3083 unsigned int map_keypad_keys (unsigned int, unsigned int);
3085 unsigned int
3086 map_keypad_keys (unsigned int virt_key, unsigned int extended)
3088 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
3089 return virt_key;
3091 if (virt_key == VK_RETURN)
3092 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
3094 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
3095 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
3097 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
3098 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
3100 if (virt_key == VK_CLEAR)
3101 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
3103 return virt_key;
3106 /* List of special key combinations which w32 would normally capture,
3107 but Emacs should grab instead. Not directly visible to lisp, to
3108 simplify synchronization. Each item is an integer encoding a virtual
3109 key code and modifier combination to capture.
3110 Note: This code is not used if keyboard hooks are active
3111 (Windows 2000 and later). */
3112 static Lisp_Object w32_grabbed_keys;
3114 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
3115 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
3116 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
3117 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
3119 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
3120 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
3121 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
3123 /* Register hot-keys for reserved key combinations when Emacs has
3124 keyboard focus, since this is the only way Emacs can receive key
3125 combinations like Alt-Tab which are used by the system. */
3127 static void
3128 register_hot_keys (HWND hwnd)
3130 Lisp_Object keylist;
3132 /* Use CONSP, since we are called asynchronously. */
3133 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
3135 Lisp_Object key = XCAR (keylist);
3137 /* Deleted entries get set to nil. */
3138 if (!INTEGERP (key))
3139 continue;
3141 RegisterHotKey (hwnd, HOTKEY_ID (key),
3142 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
3146 static void
3147 unregister_hot_keys (HWND hwnd)
3149 Lisp_Object keylist;
3151 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
3153 Lisp_Object key = XCAR (keylist);
3155 if (!INTEGERP (key))
3156 continue;
3158 UnregisterHotKey (hwnd, HOTKEY_ID (key));
3162 #if EMACSDEBUG
3163 const char*
3164 w32_name_of_message (UINT msg)
3166 unsigned i;
3167 static char buf[64];
3168 static const struct {
3169 UINT msg;
3170 const char* name;
3171 } msgnames[] = {
3172 #define M(msg) { msg, # msg }
3173 M (WM_PAINT),
3174 M (WM_TIMER),
3175 M (WM_USER),
3176 M (WM_MOUSEMOVE),
3177 M (WM_LBUTTONUP),
3178 M (WM_KEYDOWN),
3179 M (WM_EMACS_KILL),
3180 M (WM_EMACS_CREATEWINDOW),
3181 M (WM_EMACS_DONE),
3182 M (WM_EMACS_CREATEVSCROLLBAR),
3183 M (WM_EMACS_CREATEHSCROLLBAR),
3184 M (WM_EMACS_SHOWWINDOW),
3185 M (WM_EMACS_SETWINDOWPOS),
3186 M (WM_EMACS_DESTROYWINDOW),
3187 M (WM_EMACS_TRACKPOPUPMENU),
3188 M (WM_EMACS_SETFOCUS),
3189 M (WM_EMACS_SETFOREGROUND),
3190 M (WM_EMACS_SETLOCALE),
3191 M (WM_EMACS_SETKEYBOARDLAYOUT),
3192 M (WM_EMACS_REGISTER_HOT_KEY),
3193 M (WM_EMACS_UNREGISTER_HOT_KEY),
3194 M (WM_EMACS_TOGGLE_LOCK_KEY),
3195 M (WM_EMACS_TRACK_CARET),
3196 M (WM_EMACS_DESTROY_CARET),
3197 M (WM_EMACS_SHOW_CARET),
3198 M (WM_EMACS_HIDE_CARET),
3199 M (WM_EMACS_SETCURSOR),
3200 M (WM_EMACS_SHOWCURSOR),
3201 M (WM_EMACS_PAINT),
3202 M (WM_CHAR),
3203 #undef M
3204 { 0, 0 }
3207 for (i = 0; msgnames[i].name; ++i)
3208 if (msgnames[i].msg == msg)
3209 return msgnames[i].name;
3211 sprintf (buf, "message 0x%04x", (unsigned)msg);
3212 return buf;
3214 #endif /* EMACSDEBUG */
3216 /* Here's an overview of how Emacs input works in GUI sessions on
3217 MS-Windows. (For description of non-GUI input, see the commentary
3218 before w32_console_read_socket in w32inevt.c.)
3220 System messages are read and processed by w32_msg_pump below. This
3221 function runs in a separate thread. It handles a small number of
3222 custom WM_EMACS_* messages (posted by the main thread, look for
3223 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
3224 is the main window procedure for the entire Emacs application.
3226 w32_wnd_proc also runs in the same separate input thread. It
3227 handles some messages, mostly those that need GDI calls, by itself.
3228 For the others, it calls my_post_msg, which inserts the messages
3229 into the input queue serviced by w32_read_socket.
3231 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
3232 called synchronously from keyboard.c when it is known or suspected
3233 that some input is available. w32_read_socket either handles
3234 messages immediately, or converts them into Emacs input events and
3235 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
3236 them and process them when read_char and its callers require
3237 input.
3239 Under Cygwin with the W32 toolkit, the use of /dev/windows with
3240 select(2) takes the place of w32_read_socket.
3244 /* Main message dispatch loop. */
3246 static void
3247 w32_msg_pump (deferred_msg * msg_buf)
3249 MSG msg;
3250 WPARAM result;
3251 HWND focus_window;
3253 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
3255 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
3258 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
3259 /* w32_name_of_message (msg.message), msg.time)); */
3261 if (msg.hwnd == NULL)
3263 switch (msg.message)
3265 case WM_NULL:
3266 /* Produced by complete_deferred_msg; just ignore. */
3267 break;
3268 case WM_EMACS_CREATEWINDOW:
3269 /* Initialize COM for this window. Even though we don't use it,
3270 some third party shell extensions can cause it to be used in
3271 system dialogs, which causes a crash if it is not initialized.
3272 This is a known bug in Windows, which was fixed long ago, but
3273 the patch for XP is not publicly available until XP SP3,
3274 and older versions will never be patched. */
3275 CoInitialize (NULL);
3276 w32_createwindow ((struct frame *) msg.wParam,
3277 (int *) msg.lParam);
3278 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3279 emacs_abort ();
3280 break;
3281 case WM_EMACS_SETLOCALE:
3282 SetThreadLocale (msg.wParam);
3283 /* Reply is not expected. */
3284 break;
3285 case WM_EMACS_SETKEYBOARDLAYOUT:
3286 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
3287 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3288 result, 0))
3289 emacs_abort ();
3290 break;
3291 case WM_EMACS_REGISTER_HOT_KEY:
3292 focus_window = GetFocus ();
3293 if (focus_window != NULL)
3294 RegisterHotKey (focus_window,
3295 RAW_HOTKEY_ID (msg.wParam),
3296 RAW_HOTKEY_MODIFIERS (msg.wParam),
3297 RAW_HOTKEY_VK_CODE (msg.wParam));
3298 /* Reply is not expected. */
3299 break;
3300 case WM_EMACS_UNREGISTER_HOT_KEY:
3301 focus_window = GetFocus ();
3302 if (focus_window != NULL)
3303 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
3304 /* Mark item as erased. NB: this code must be
3305 thread-safe. The next line is okay because the cons
3306 cell is never made into garbage and is not relocated by
3307 GC. */
3308 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
3309 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3310 emacs_abort ();
3311 break;
3312 case WM_EMACS_TOGGLE_LOCK_KEY:
3314 int vk_code = (int) msg.wParam;
3315 int cur_state = (GetKeyState (vk_code) & 1);
3316 int new_state = msg.lParam;
3318 if (new_state == -1
3319 || ((new_state & 1) != cur_state))
3321 one_w32_display_info.faked_key = vk_code;
3323 keybd_event ((BYTE) vk_code,
3324 (BYTE) MapVirtualKey (vk_code, 0),
3325 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3326 keybd_event ((BYTE) vk_code,
3327 (BYTE) MapVirtualKey (vk_code, 0),
3328 KEYEVENTF_EXTENDEDKEY | 0, 0);
3329 keybd_event ((BYTE) vk_code,
3330 (BYTE) MapVirtualKey (vk_code, 0),
3331 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3332 cur_state = !cur_state;
3334 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3335 cur_state, 0))
3336 emacs_abort ();
3338 break;
3339 #ifdef MSG_DEBUG
3340 /* Broadcast messages make it here, so you need to be looking
3341 for something in particular for this to be useful. */
3342 default:
3343 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3344 #endif
3347 else
3349 if (w32_unicode_gui)
3350 DispatchMessageW (&msg);
3351 else
3352 DispatchMessageA (&msg);
3355 /* Exit nested loop when our deferred message has completed. */
3356 if (msg_buf->completed)
3357 break;
3361 deferred_msg * deferred_msg_head;
3363 static deferred_msg *
3364 find_deferred_msg (HWND hwnd, UINT msg)
3366 deferred_msg * item;
3368 /* Don't actually need synchronization for read access, since
3369 modification of single pointer is always atomic. */
3370 /* enter_crit (); */
3372 for (item = deferred_msg_head; item != NULL; item = item->next)
3373 if (item->w32msg.msg.hwnd == hwnd
3374 && item->w32msg.msg.message == msg)
3375 break;
3377 /* leave_crit (); */
3379 return item;
3382 static LRESULT
3383 send_deferred_msg (deferred_msg * msg_buf,
3384 HWND hwnd,
3385 UINT msg,
3386 WPARAM wParam,
3387 LPARAM lParam)
3389 /* Only input thread can send deferred messages. */
3390 if (GetCurrentThreadId () != dwWindowsThreadId)
3391 emacs_abort ();
3393 /* It is an error to send a message that is already deferred. */
3394 if (find_deferred_msg (hwnd, msg) != NULL)
3395 emacs_abort ();
3397 /* Enforced synchronization is not needed because this is the only
3398 function that alters deferred_msg_head, and the following critical
3399 section is guaranteed to only be serially reentered (since only the
3400 input thread can call us). */
3402 /* enter_crit (); */
3404 msg_buf->completed = 0;
3405 msg_buf->next = deferred_msg_head;
3406 deferred_msg_head = msg_buf;
3407 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3409 /* leave_crit (); */
3411 /* Start a new nested message loop to process other messages until
3412 this one is completed. */
3413 w32_msg_pump (msg_buf);
3415 deferred_msg_head = msg_buf->next;
3417 return msg_buf->result;
3420 void
3421 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3423 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3425 if (msg_buf == NULL)
3426 /* Message may have been canceled, so don't abort. */
3427 return;
3429 msg_buf->result = result;
3430 msg_buf->completed = 1;
3432 /* Ensure input thread is woken so it notices the completion. */
3433 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3436 static void
3437 cancel_all_deferred_msgs (void)
3439 deferred_msg * item;
3441 /* Don't actually need synchronization for read access, since
3442 modification of single pointer is always atomic. */
3443 /* enter_crit (); */
3445 for (item = deferred_msg_head; item != NULL; item = item->next)
3447 item->result = 0;
3448 item->completed = 1;
3451 /* leave_crit (); */
3453 /* Ensure input thread is woken so it notices the completion. */
3454 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3457 DWORD WINAPI w32_msg_worker (void *);
3459 DWORD WINAPI
3460 w32_msg_worker (void *arg)
3462 MSG msg;
3463 deferred_msg dummy_buf;
3465 /* Ensure our message queue is created */
3467 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3469 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3470 emacs_abort ();
3472 memset (&dummy_buf, 0, sizeof (dummy_buf));
3473 dummy_buf.w32msg.msg.hwnd = NULL;
3474 dummy_buf.w32msg.msg.message = WM_NULL;
3476 /* This is the initial message loop which should only exit when the
3477 application quits. */
3478 w32_msg_pump (&dummy_buf);
3480 return 0;
3483 static void
3484 signal_user_input (void)
3486 /* Interrupt any lisp that wants to be interrupted by input. */
3487 if (!NILP (Vthrow_on_input))
3489 Vquit_flag = Vthrow_on_input;
3490 /* Calling maybe_quit from this thread is a bad idea, since this
3491 unwinds the stack of the Lisp thread, and the Windows runtime
3492 rightfully barfs. */
3497 static void
3498 post_character_message (HWND hwnd, UINT msg,
3499 WPARAM wParam, LPARAM lParam,
3500 DWORD modifiers)
3502 W32Msg wmsg;
3504 wmsg.dwModifiers = modifiers;
3506 /* Detect quit_char and set quit-flag directly. Note that we
3507 still need to post a message to ensure the main thread will be
3508 woken up if blocked in sys_select, but we do NOT want to post
3509 the quit_char message itself (because it will usually be as if
3510 the user had typed quit_char twice). Instead, we post a dummy
3511 message that has no particular effect. */
3513 int c = wParam;
3514 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
3515 c = make_ctrl_char (c) & 0377;
3516 if (c == quit_char
3517 || (wmsg.dwModifiers == 0
3518 && w32_quit_key && wParam == w32_quit_key))
3520 Vquit_flag = Qt;
3522 /* The choice of message is somewhat arbitrary, as long as
3523 the main thread handler just ignores it. */
3524 msg = WM_NULL;
3526 /* Interrupt any blocking system calls. */
3527 signal_quit ();
3529 /* As a safety precaution, forcibly complete any deferred
3530 messages. This is a kludge, but I don't see any particularly
3531 clean way to handle the situation where a deferred message is
3532 "dropped" in the lisp thread, and will thus never be
3533 completed, eg. by the user trying to activate the menubar
3534 when the lisp thread is busy, and then typing C-g when the
3535 menubar doesn't open promptly (with the result that the
3536 menubar never responds at all because the deferred
3537 WM_INITMENU message is never completed). Another problem
3538 situation is when the lisp thread calls SendMessage (to send
3539 a window manager command) when a message has been deferred;
3540 the lisp thread gets blocked indefinitely waiting for the
3541 deferred message to be completed, which itself is waiting for
3542 the lisp thread to respond.
3544 Note that we don't want to block the input thread waiting for
3545 a response from the lisp thread (although that would at least
3546 solve the deadlock problem above), because we want to be able
3547 to receive C-g to interrupt the lisp thread. */
3548 cancel_all_deferred_msgs ();
3550 else
3551 signal_user_input ();
3554 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3557 static int
3558 get_wm_chars (HWND aWnd, int *buf, int buflen, int ignore_ctrl, int ctrl,
3559 int *ctrl_cnt, int *is_dead, int vk, int exp)
3561 MSG msg;
3562 /* If doubled is at the end, ignore it. */
3563 int i = buflen, doubled = 0, code_unit;
3565 if (ctrl_cnt)
3566 *ctrl_cnt = 0;
3567 if (is_dead)
3568 *is_dead = -1;
3569 eassert (w32_unicode_gui);
3570 while (buflen
3571 /* Should be called only when w32_unicode_gui: */
3572 && PeekMessageW (&msg, aWnd, WM_KEYFIRST, WM_KEYLAST,
3573 PM_NOREMOVE | PM_NOYIELD)
3574 && (msg.message == WM_CHAR || msg.message == WM_SYSCHAR
3575 || msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR
3576 || msg.message == WM_UNICHAR))
3578 /* We extract character payload, but in this call we handle only the
3579 characters which come BEFORE the next keyup/keydown message. */
3580 int dead;
3582 GetMessageW (&msg, aWnd, msg.message, msg.message);
3583 dead = (msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR);
3584 if (is_dead)
3585 *is_dead = (dead ? msg.wParam : -1);
3586 if (dead)
3587 continue;
3588 code_unit = msg.wParam;
3589 if (doubled)
3591 /* Had surrogate. */
3592 if (msg.message == WM_UNICHAR
3593 || code_unit < 0xDC00 || code_unit > 0xDFFF)
3594 { /* Mismatched first surrogate.
3595 Pass both code units as if they were two characters. */
3596 *buf++ = doubled;
3597 if (!--buflen)
3598 return i; /* Drop the 2nd char if at the end of the buffer. */
3600 else /* see https://en.wikipedia.org/wiki/UTF-16 */
3601 code_unit = (doubled << 10) + code_unit - 0x35FDC00;
3602 doubled = 0;
3604 else if (code_unit >= 0xD800 && code_unit <= 0xDBFF)
3606 /* Handle mismatched 2nd surrogate the same as a normal character. */
3607 doubled = code_unit;
3608 continue;
3611 /* The only "fake" characters delivered by ToUnicode() or
3612 TranslateMessage() are:
3613 0x01 .. 0x1a for Ctrl-letter, Enter, Tab, Ctrl-Break, Esc, Backspace
3614 0x00 and 0x1b .. 0x1f for Control- []\@^_
3615 0x7f for Control-BackSpace
3616 0x20 for Control-Space */
3617 if (ignore_ctrl
3618 && (code_unit < 0x20 || code_unit == 0x7f
3619 || (code_unit == 0x20 && ctrl)))
3621 /* Non-character payload in a WM_CHAR
3622 (Ctrl-something pressed, see above). Ignore, and report. */
3623 if (ctrl_cnt)
3624 (*ctrl_cnt)++;
3625 continue;
3627 /* Traditionally, Emacs would ignore the character payload of VK_NUMPAD*
3628 keys, and would treat them later via `function-key-map'. In addition
3629 to usual 102-key NUMPAD keys, this map also treats `kp-'-variants of
3630 space, tab, enter, separator, equal. TAB and EQUAL, apparently,
3631 cannot be generated on Win-GUI branch. ENTER is already handled
3632 by the code above. According to `lispy_function_keys', kp_space is
3633 generated by not-extended VK_CLEAR. (kp-tab != VK_OEM_NEC_EQUAL!).
3635 We do similarly for backward-compatibility, but ignore only the
3636 characters restorable later by `function-key-map'. */
3637 if (code_unit < 0x7f
3638 && ((vk >= VK_NUMPAD0 && vk <= VK_DIVIDE)
3639 || (exp && ((vk >= VK_PRIOR && vk <= VK_DOWN) ||
3640 vk == VK_INSERT || vk == VK_DELETE || vk == VK_CLEAR)))
3641 && strchr ("0123456789/*-+.,", code_unit))
3642 continue;
3643 *buf++ = code_unit;
3644 buflen--;
3646 return i - buflen;
3649 #ifdef DBG_WM_CHARS
3650 # define FPRINTF_WM_CHARS(ARG) fprintf ARG
3651 #else
3652 # define FPRINTF_WM_CHARS(ARG) (void)0
3653 #endif
3655 /* This is a heuristic only. This is supposed to track the state of the
3656 finite automaton in the language environment of Windows.
3658 However, separate windows (if with the same different language
3659 environments!) should have different values. Moreover, switching to a
3660 non-Emacs window with the same language environment, and using (dead)keys
3661 there would change the value stored in the kernel, but not this value. */
3662 /* A layout may emit deadkey=0. It looks like this would reset the state
3663 of the kernel's finite automaton (equivalent to emiting 0-length string,
3664 which is otherwise impossible in the dead-key map of a layout).
3665 Be ready to treat the case when this delivers WM_(SYS)DEADCHAR. */
3666 static int after_deadkey = -1;
3668 static int
3669 deliver_wm_chars (int do_translate, HWND hwnd, UINT msg, UINT wParam,
3670 UINT lParam, int legacy_alt_meta)
3672 /* An "old style" keyboard description may assign up to 125 UTF-16 code
3673 points to a keypress.
3674 (However, the "old style" TranslateMessage() would deliver at most 16 of
3675 them.) Be on a safe side, and prepare to treat many more. */
3676 int ctrl_cnt, buf[1024], count, is_dead, after_dead = (after_deadkey > 0);
3678 /* Since the keypress processing logic of Windows has a lot of state, it
3679 is important to call TranslateMessage() for every keyup/keydown, AND
3680 do it exactly once. (The actual change of state is done by
3681 ToUnicode[Ex](), which is called by TranslateMessage(). So one can
3682 call ToUnicode[Ex]() instead.)
3684 The "usual" message pump calls TranslateMessage() for EVERY event.
3685 Emacs calls TranslateMessage() very selectively (is it needed for doing
3686 some tricky stuff with Win95??? With newer Windows, selectiveness is,
3687 most probably, not needed -- and harms a lot).
3689 So, with the usual message pump, the following call to TranslateMessage()
3690 is not needed (and is going to be VERY harmful). With Emacs' message
3691 pump, the call is needed. */
3692 if (do_translate)
3694 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3696 windows_msg.time = GetMessageTime ();
3697 TranslateMessage (&windows_msg);
3699 count = get_wm_chars (hwnd, buf, sizeof (buf)/sizeof (*buf), 1,
3700 /* The message may have been synthesized by
3701 who knows what; be conservative. */
3702 modifier_set (VK_LCONTROL)
3703 || modifier_set (VK_RCONTROL)
3704 || modifier_set (VK_CONTROL),
3705 &ctrl_cnt, &is_dead, wParam,
3706 (lParam & 0x1000000L) != 0);
3707 if (count)
3709 W32Msg wmsg;
3710 DWORD console_modifiers = construct_console_modifiers ();
3711 int *b = buf, strip_ExtraMods = 1, hairy = 0;
3712 const char *type_CtrlAlt = NULL;
3714 /* XXXX In fact, there may be another case when we need to do the same:
3715 What happens if the string defined in the LIGATURES has length
3716 0? Probably, we will get count==0, but the state of the finite
3717 automaton would reset to 0??? */
3718 after_deadkey = -1;
3720 /* wParam is checked when converting CapsLock to Shift; this is a clone
3721 of w32_get_key_modifiers (). */
3722 wmsg.dwModifiers = w32_kbd_mods_to_emacs (console_modifiers, wParam);
3724 /* What follows is just heuristics; the correct treatement requires
3725 non-destructive ToUnicode():
3726 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Can_an_application_on_Windows_accept_keyboard_events?_Part_IV:_application-specific_modifiers
3728 What one needs to find is:
3729 * which of the present modifiers AFFECT the resulting char(s)
3730 (so should be stripped, since their EFFECT is "already
3731 taken into account" in the string in buf), and
3732 * which modifiers are not affecting buf, so should be reported to
3733 the application for further treatment.
3735 Example: assume that we know:
3736 (A) lCtrl+rCtrl+rAlt modifiers with VK_A key produce a Latin "f"
3737 ("may be logical" in JCUKEN-flavored Russian keyboard flavors);
3738 (B) removing any of lCtrl, rCtrl, rAlt changes the produced char;
3739 (C) Win-modifier is not affecting the produced character
3740 (this is the common case: happens with all "standard" layouts).
3742 Suppose the user presses Win+lCtrl+rCtrl+rAlt modifiers with VK_A.
3743 What is the intent of the user? We need to guess the intent to decide
3744 which event to deliver to the application.
3746 This looks like a reasonable logic: since Win- modifier doesn't affect
3747 the output string, the user was pressing Win for SOME OTHER purpose.
3748 So the user wanted to generate Win-SOMETHING event. Now, what is
3749 something? If one takes the mantra that "character payload is more
3750 important than the combination of keypresses which resulted in this
3751 payload", then one should ignore lCtrl+rCtrl+rAlt, ignore VK_A, and
3752 assume that the user wanted to generate Win-f.
3754 Unfortunately, without non-destructive ToUnicode(), checking (B),(C)
3755 is out of question. So we use heuristics (hopefully, covering
3756 99.9999% of cases). */
3758 /* Another thing to watch for is a possibility to use AltGr-* and
3759 Ctrl-Alt-* with different semantic.
3761 Background: the layout defining the KLLF_ALTGR bit are treated
3762 specially by the kernel: when VK_RMENU (=rightAlt, =AltGr) is pressed
3763 (released), a press (release) of VK_LCONTROL is emulated (unless Ctrl
3764 is already down). As a result, any press/release of AltGr is seen
3765 by applications as a press/release of lCtrl AND rAlt. This is
3766 applicable, in particular, to ToUnicode[Ex](). (Keyrepeat is covered
3767 the same way!)
3769 NOTE: it IS possible to see bare rAlt even with KLLF_ALTGR; but this
3770 requires a good finger coordination: doing (physically)
3771 Down-lCtrl Down-rAlt Up-lCtrl Down-a
3772 (doing quick enough, so that key repeat of rAlt [which would
3773 generate new "fake" Down-lCtrl events] does not happens before 'a'
3774 is down) results in no "fake" events, so the application will see
3775 only rAlt down when 'a' is pressed. (However, fake Up-lCtrl WILL
3776 be generated when rAlt goes UP.)
3778 In fact, note also that KLLF_ALTGR does not prohibit construction of
3779 rCtrl-rAlt (just press them in this order!).
3781 Moreover: "traditional" layouts do not define distinct modifier-masks
3782 for VK_LMENU and VK_RMENU (same for VK_L/RCONTROL). Instead, they
3783 rely on the KLLF_ALTGR bit to make the behavior of VK_LMENU and
3784 VK_RMENU distinct. As a corollary, for such layouts, the produced
3785 character is the same for AltGr-* (=rAlt-*) and Ctrl-Alt-* (in any
3786 combination of handedness). For description of masks, see
3788 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Keyboard_input_on_Windows,_Part_I:_what_is_the_kernel_doing?
3790 By default, Emacs was using these coincidences via the following
3791 heuristics: it was treating:
3792 (*) keypresses with lCtrl-rAlt modifiers as if they are carrying
3793 ONLY the character payload (no matter what the actual keyboard
3794 was defining: if lCtrl-lAlt-b was delivering U+05df=beta, then
3795 Emacs saw [beta]; if lCtrl-lAlt-b was undefined in the layout,
3796 the keypress was completely ignored), and
3797 (*) keypresses with the other combinations of handedness of Ctrl-Alt
3798 modifiers (e.g., lCtrl-lAlt) as if they NEVER carry a character
3799 payload (so they were reported "raw": if lCtrl-lAlt-b was
3800 delivering beta, then Emacs saw event [C-A-b], and not [beta]).
3801 This worked good for "traditional" layouts: users could type both
3802 AltGr-x and Ctrl-Alt-x, and one was a character, another a bindable
3803 event.
3805 However, for layouts which deliver different characters for AltGr-x
3806 and lCtrl-lAlt-x, this scheme makes the latter character unaccessible
3807 in Emacs. While it is easy to access functionality of [C-M-x] in
3808 Emacs by other means (for example, by the `controlify' prefix, or
3809 using lCtrl-rCtrl-x, or rCtrl-rAlt-x [in this order]), missing
3810 characters cannot be reconstructed without a tedious manual work. */
3812 /* These two cases are often going to be distinguishable, since at most
3813 one of these character is defined with KBDCTRL | KBDMENU modifier
3814 bitmap. (This heuristic breaks if both lCtrl-lAlt- AND lCtrl-rAlt-
3815 are translated to modifier bitmaps distinct from KBDCTRL | KBDMENU,
3816 or in the cases when lCtrl-lAlt-* and lCtrl-rAlt-* are generally
3817 different, but lCtrl-lAlt-x and lCtrl-rAlt-x happen to deliver the
3818 same character.)
3820 So we have 2 chunks of info:
3821 (A) is it lCtrl-rAlt-, or lCtrl-lAlt, or some other combination?
3822 (B) is the delivered character defined with KBDCTRL | KBDMENU bits?
3823 Basing on (A) and (B), we should decide whether to ignore the
3824 delivered character. (Before, Emacs was completely ignoring (B), and
3825 was treating the 3-state of (A) as a bit.) This means that we have 6
3826 bits of customization.
3828 Additionally, a presence of two Ctrl down may be AltGr-rCtrl-. */
3830 /* Strip all non-Shift modifiers if:
3831 - more than one UTF-16 code point delivered (can't call VkKeyScanW ())
3832 - or the character is a result of combining with a prefix key. */
3833 if (!after_dead && count == 1 && *b < 0x10000)
3835 if (console_modifiers & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
3836 && console_modifiers & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
3838 type_CtrlAlt = "bB"; /* generic bindable Ctrl-Alt- modifiers */
3839 if ((console_modifiers & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3840 == (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3841 /* double-Ctrl:
3842 e.g. AltGr-rCtrl on some layouts (in this order!) */
3843 type_CtrlAlt = "dD";
3844 else if ((console_modifiers
3845 & (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3846 == (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3847 type_CtrlAlt = "lL"; /* Ctrl-Alt- modifiers on the left */
3848 else if (!NILP (Vw32_recognize_altgr)
3849 && ((console_modifiers
3850 & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)))
3851 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
3852 type_CtrlAlt = "gG"; /* modifiers as in AltGr */
3854 else if (wmsg.dwModifiers & (alt_modifier | meta_modifier)
3855 || ((console_modifiers
3856 & (LEFT_WIN_PRESSED | RIGHT_WIN_PRESSED
3857 | APPS_PRESSED | SCROLLLOCK_ON))))
3859 /* Pure Alt (or combination of Alt, Win, APPS, scrolllock. */
3860 type_CtrlAlt = "aA";
3862 if (type_CtrlAlt)
3864 /* Out of bound bitmap: */
3865 SHORT r = VkKeyScanW (*b), bitmap = 0x1FF;
3867 FPRINTF_WM_CHARS((stderr, "VkKeyScanW %#06x %#04x\n", (int)r,
3868 wParam));
3869 if ((r & 0xFF) == wParam)
3870 bitmap = r>>8; /* *b is reachable via simple interface */
3871 else
3873 /* VkKeyScanW() (essentially) returns the FIRST key with
3874 the specified character; so here the pressed key is the
3875 SECONDARY key producing the character.
3877 Essentially, we have no information about the "role" of
3878 modifiers on this key: which contribute into the
3879 produced character (so "are consumed"), and which are
3880 "extra" (must attache to bindable events).
3882 The default above would consume ALL modifiers, so the
3883 character is reported "as is". However, on many layouts
3884 the ordering of the keys (in the layout table) is not
3885 thought out well, so the "secondary" keys are often those
3886 which the users would prefer to use with Alt-CHAR.
3887 (Moreover - with e.g. Czech-QWERTY - the ASCII
3888 punctuation is accessible from two equally [nu]preferable
3889 AltGr-keys.)
3891 SO: Heuristic: if the reported char is ASCII, AND Meta
3892 modifier is a candidate, behave as if Meta is present
3893 (fallback to the legacy branch; bug#23251).
3895 (This would break layouts
3896 - delivering ASCII characters
3897 - on SECONDARY keys
3898 - with not Shift/AltGr-like modifier combinations.
3899 All 3 conditions together must be pretty exotic
3900 cases - and a workaround exists: use "primary" keys!) */
3901 if (*b < 0x80
3902 && (wmsg.dwModifiers
3903 & (alt_modifier | meta_modifier
3904 | super_modifier | hyper_modifier)))
3905 return 0;
3907 if (*type_CtrlAlt == 'a') /* Simple Alt seen */
3909 if ((bitmap & ~1) == 0) /* 1: KBDSHIFT */
3911 /* In "traditional" layouts, Alt without Ctrl does not
3912 change the delivered character. This detects this
3913 situation; it is safe to report this as Alt-something
3914 -- as opposed to delivering the reported character
3915 without modifiers. */
3916 if (legacy_alt_meta
3917 && *b > 0x7f && ('A' <= wParam && wParam <= 'Z'))
3918 /* For backward-compatibility with older Emacsen, let
3919 this be processed by another branch below (which
3920 would convert it to Alt-Latin char via wParam). */
3921 return 0;
3923 else
3924 hairy = 1;
3926 /* Check whether the delivered character(s) is accessible via
3927 KBDCTRL | KBDALT ( | KBDSHIFT ) modifier mask (which is 7). */
3928 else if ((bitmap & ~1) != 6)
3930 /* The character is not accessible via plain Ctrl-Alt(-Shift)
3931 (which is, probably, same as AltGr) modifiers.
3932 Either it was after a prefix key, or is combined with
3933 modifier keys which we don't see, or there is an asymmetry
3934 between left-hand and right-hand modifiers, or other hairy
3935 stuff. */
3936 hairy = 1;
3938 /* The best solution is to delegate these tough (but rarely
3939 needed) choices to the user. Temporarily (???), it is
3940 implemented as C macros.
3942 Essentially, there are 3 things to do: return 0 (handle to the
3943 legacy processing code [ignoring the character payload]; keep
3944 some modifiers (so that they will be processed by the binding
3945 system [on top of the character payload]; strip modifiers [so
3946 that `self-insert' is going to be triggered with the character
3947 payload]).
3949 The default below should cover 99.9999% of cases:
3950 (a) strip Alt- in the hairy case only;
3951 (stripping = not ignoring)
3952 (l) for lAlt-lCtrl, ignore the char in simple cases only;
3953 (g) for what looks like AltGr, ignore the modifiers;
3954 (d) for what looks like lCtrl-rCtrl-Alt (probably
3955 AltGr-rCtrl), ignore the character in simple cases only;
3956 (b) for other cases of Ctrl-Alt, ignore the character in
3957 simple cases only.
3959 Essentially, in all hairy cases, and in looks-like-AltGr case,
3960 we keep the character, ignoring the modifiers. In all the
3961 other cases, we ignore the delivered character. */
3962 #define S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD "aldb"
3963 #define S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS ""
3964 if (strchr (S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD,
3965 type_CtrlAlt[hairy]))
3966 return 0;
3967 /* If in neither list, report all the modifiers we see COMBINED
3968 WITH the reported character. */
3969 if (strchr (S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS,
3970 type_CtrlAlt[hairy]))
3971 strip_ExtraMods = 0;
3974 if (strip_ExtraMods)
3975 wmsg.dwModifiers = wmsg.dwModifiers & shift_modifier;
3977 signal_user_input ();
3978 while (count--)
3980 FPRINTF_WM_CHARS((stderr, "unichar %#06x\n", *b));
3981 my_post_msg (&wmsg, hwnd, WM_UNICHAR, *b++, lParam);
3983 if (!ctrl_cnt) /* Process ALSO as ctrl */
3984 return 1;
3985 else
3986 FPRINTF_WM_CHARS((stderr, "extra ctrl char\n"));
3987 return -1;
3989 else if (is_dead >= 0)
3991 FPRINTF_WM_CHARS((stderr, "dead %#06x\n", is_dead));
3992 after_deadkey = is_dead;
3993 return 1;
3995 return 0;
3998 /* Main window procedure */
4000 static LRESULT CALLBACK
4001 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
4003 struct frame *f;
4004 struct w32_display_info *dpyinfo = &one_w32_display_info;
4005 W32Msg wmsg;
4006 int windows_translate;
4007 int key;
4009 /* Note that it is okay to call x_window_to_frame, even though we are
4010 not running in the main lisp thread, because frame deletion
4011 requires the lisp thread to synchronize with this thread. Thus, if
4012 a frame struct is returned, it can be used without concern that the
4013 lisp thread might make it disappear while we are using it.
4015 NB. Walking the frame list in this thread is safe (as long as
4016 writes of Lisp_Object slots are atomic, which they are on Windows).
4017 Although delete-frame can destructively modify the frame list while
4018 we are walking it, a garbage collection cannot occur until after
4019 delete-frame has synchronized with this thread.
4021 It is also safe to use functions that make GDI calls, such as
4022 w32_clear_rect, because these functions must obtain a DC handle
4023 from the frame struct using get_frame_dc which is thread-aware. */
4025 switch (msg)
4027 case WM_ERASEBKGND:
4028 f = x_window_to_frame (dpyinfo, hwnd);
4029 if (f)
4031 HDC hdc = get_frame_dc (f);
4032 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
4033 w32_clear_rect (f, hdc, &wmsg.rect);
4034 release_frame_dc (f, hdc);
4036 #if defined (W32_DEBUG_DISPLAY)
4037 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
4039 wmsg.rect.left, wmsg.rect.top,
4040 wmsg.rect.right, wmsg.rect.bottom));
4041 #endif /* W32_DEBUG_DISPLAY */
4043 return 1;
4044 case WM_PALETTECHANGED:
4045 /* ignore our own changes */
4046 if ((HWND)wParam != hwnd)
4048 f = x_window_to_frame (dpyinfo, hwnd);
4049 if (f)
4050 /* get_frame_dc will realize our palette and force all
4051 frames to be redrawn if needed. */
4052 release_frame_dc (f, get_frame_dc (f));
4054 return 0;
4055 case WM_PAINT:
4057 PAINTSTRUCT paintStruct;
4058 RECT update_rect;
4059 memset (&update_rect, 0, sizeof (update_rect));
4061 f = x_window_to_frame (dpyinfo, hwnd);
4062 if (f == 0)
4064 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
4065 return 0;
4068 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
4069 fails. Apparently this can happen under some
4070 circumstances. */
4071 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
4073 enter_crit ();
4074 BeginPaint (hwnd, &paintStruct);
4076 /* The rectangles returned by GetUpdateRect and BeginPaint
4077 do not always match. Play it safe by assuming both areas
4078 are invalid. */
4079 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
4081 #if defined (W32_DEBUG_DISPLAY)
4082 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
4084 wmsg.rect.left, wmsg.rect.top,
4085 wmsg.rect.right, wmsg.rect.bottom));
4086 DebPrint ((" [update region is %d,%d-%d,%d]\n",
4087 update_rect.left, update_rect.top,
4088 update_rect.right, update_rect.bottom));
4089 #endif
4090 EndPaint (hwnd, &paintStruct);
4091 leave_crit ();
4093 /* Change the message type to prevent Windows from
4094 combining WM_PAINT messages in the Lisp thread's queue,
4095 since Windows assumes that each message queue is
4096 dedicated to one frame and does not bother checking
4097 that hwnd matches before combining them. */
4098 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
4100 return 0;
4103 /* If GetUpdateRect returns 0 (meaning there is no update
4104 region), assume the whole window needs to be repainted. */
4105 GetClientRect (hwnd, &wmsg.rect);
4106 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4107 return 0;
4110 case WM_INPUTLANGCHANGE:
4111 /* Inform lisp thread of keyboard layout changes. */
4112 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4114 /* The state of the finite automaton is separate per every input
4115 language environment (so it does not change when one switches
4116 to a different window with the same environment). Moreover,
4117 the experiments show that the state is not remembered when
4118 one switches back to the pre-previous environment. */
4119 after_deadkey = -1;
4121 /* XXXX??? What follows is a COMPLETE misunderstanding of Windows! */
4123 /* Clear dead keys in the keyboard state; for simplicity only
4124 preserve modifier key states. */
4126 int i;
4127 BYTE keystate[256];
4129 GetKeyboardState (keystate);
4130 for (i = 0; i < 256; i++)
4131 if (1
4132 && i != VK_SHIFT
4133 && i != VK_LSHIFT
4134 && i != VK_RSHIFT
4135 && i != VK_CAPITAL
4136 && i != VK_NUMLOCK
4137 && i != VK_SCROLL
4138 && i != VK_CONTROL
4139 && i != VK_LCONTROL
4140 && i != VK_RCONTROL
4141 && i != VK_MENU
4142 && i != VK_LMENU
4143 && i != VK_RMENU
4144 && i != VK_LWIN
4145 && i != VK_RWIN)
4146 keystate[i] = 0;
4147 SetKeyboardState (keystate);
4149 goto dflt;
4151 case WM_HOTKEY:
4152 /* Synchronize hot keys with normal input. */
4153 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
4154 return (0);
4156 case WM_KEYUP:
4157 case WM_SYSKEYUP:
4158 record_keyup (wParam, lParam);
4159 goto dflt;
4161 case WM_KEYDOWN:
4162 case WM_SYSKEYDOWN:
4163 /* Ignore keystrokes we fake ourself; see below. */
4164 if (dpyinfo->faked_key == wParam)
4166 dpyinfo->faked_key = 0;
4167 /* Make sure TranslateMessage sees them though (as long as
4168 they don't produce WM_CHAR messages). This ensures that
4169 indicator lights are toggled promptly on Windows 9x, for
4170 example. */
4171 if (wParam < 256 && lispy_function_keys[wParam])
4173 windows_translate = 1;
4174 goto translate;
4176 return 0;
4179 /* Synchronize modifiers with current keystroke. */
4180 sync_modifiers ();
4181 record_keydown (wParam, lParam);
4182 if (w32_use_fallback_wm_chars_method)
4183 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4185 windows_translate = 0;
4187 switch (wParam)
4189 case VK_LWIN:
4190 if (!w32_kbdhook_active && NILP (Vw32_pass_lwindow_to_system))
4192 /* Prevent system from acting on keyup (which opens the
4193 Start menu if no other key was pressed) by simulating a
4194 press of Space which we will ignore. */
4195 if (GetAsyncKeyState (wParam) & 1)
4197 if (NUMBERP (Vw32_phantom_key_code))
4198 key = XUINT (Vw32_phantom_key_code) & 255;
4199 else
4200 key = VK_SPACE;
4201 dpyinfo->faked_key = key;
4202 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4205 if (!NILP (Vw32_lwindow_modifier))
4206 return 0;
4207 break;
4208 case VK_RWIN:
4209 if (!w32_kbdhook_active && NILP (Vw32_pass_rwindow_to_system))
4211 if (GetAsyncKeyState (wParam) & 1)
4213 if (NUMBERP (Vw32_phantom_key_code))
4214 key = XUINT (Vw32_phantom_key_code) & 255;
4215 else
4216 key = VK_SPACE;
4217 dpyinfo->faked_key = key;
4218 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
4221 if (!NILP (Vw32_rwindow_modifier))
4222 return 0;
4223 break;
4224 case VK_APPS:
4225 if (!NILP (Vw32_apps_modifier))
4226 return 0;
4227 break;
4228 case VK_MENU:
4229 if (NILP (Vw32_pass_alt_to_system))
4230 /* Prevent DefWindowProc from activating the menu bar if an
4231 Alt key is pressed and released by itself. */
4232 return 0;
4233 windows_translate = 1;
4234 break;
4235 case VK_CAPITAL:
4236 /* Decide whether to treat as modifier or function key. */
4237 if (NILP (Vw32_enable_caps_lock))
4238 goto disable_lock_key;
4239 windows_translate = 1;
4240 break;
4241 case VK_NUMLOCK:
4242 /* Decide whether to treat as modifier or function key. */
4243 if (NILP (Vw32_enable_num_lock))
4244 goto disable_lock_key;
4245 windows_translate = 1;
4246 break;
4247 case VK_SCROLL:
4248 /* Decide whether to treat as modifier or function key. */
4249 if (NILP (Vw32_scroll_lock_modifier))
4250 goto disable_lock_key;
4251 windows_translate = 1;
4252 break;
4253 disable_lock_key:
4254 /* Ensure the appropriate lock key state (and indicator light)
4255 remains in the same state. We do this by faking another
4256 press of the relevant key. Apparently, this really is the
4257 only way to toggle the state of the indicator lights. */
4258 dpyinfo->faked_key = wParam;
4259 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4260 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4261 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4262 KEYEVENTF_EXTENDEDKEY | 0, 0);
4263 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
4264 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
4265 /* Ensure indicator lights are updated promptly on Windows 9x
4266 (TranslateMessage apparently does this), after forwarding
4267 input event. */
4268 post_character_message (hwnd, msg, wParam, lParam,
4269 w32_get_key_modifiers (wParam, lParam));
4270 windows_translate = 1;
4271 break;
4272 case VK_CONTROL:
4273 case VK_SHIFT:
4274 case VK_PROCESSKEY: /* Generated by IME. */
4275 windows_translate = 1;
4276 break;
4277 case VK_CANCEL:
4278 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
4279 which is confusing for purposes of key binding; convert
4280 VK_CANCEL events into VK_PAUSE events. */
4281 wParam = VK_PAUSE;
4282 break;
4283 case VK_PAUSE:
4284 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
4285 for purposes of key binding; convert these back into
4286 VK_NUMLOCK events, at least when we want to see NumLock key
4287 presses. (Note that there is never any possibility that
4288 VK_PAUSE with Ctrl really is C-Pause as per above.) */
4289 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
4290 wParam = VK_NUMLOCK;
4291 break;
4292 default:
4293 if (w32_unicode_gui && !w32_use_fallback_wm_chars_method)
4295 /* If this event generates characters or deadkeys, do
4296 not interpret it as a "raw combination of modifiers
4297 and keysym". Hide deadkeys, and use the generated
4298 character(s) instead of the keysym. (Backward
4299 compatibility: exceptions for numpad keys generating
4300 0-9 . , / * - +, and for extra-Alt combined with a
4301 non-Latin char.)
4303 Try to not report modifiers which have effect on
4304 which character or deadkey is generated.
4306 Example (contrived): if rightAlt-? generates f (on a
4307 Cyrillic keyboard layout), and Ctrl, leftAlt do not
4308 affect the generated character, one wants to report
4309 Ctrl-leftAlt-f if the user presses
4310 Ctrl-leftAlt-rightAlt-?. */
4311 int res;
4312 #if 0
4313 /* Some of WM_CHAR may be fed to us directly, some are
4314 results of TranslateMessage(). Using 0 as the first
4315 argument (in a separate call) might help us
4316 distinguish these two cases.
4318 However, the keypress feeders would most probably
4319 expect the "standard" message pump, when
4320 TranslateMessage() is called on EVERY KeyDown/KeyUp
4321 event. So they may feed us Down-Ctrl Down-FAKE
4322 Char-o and expect us to recognize it as Ctrl-o.
4323 Using 0 as the first argument would interfere with
4324 this. */
4325 deliver_wm_chars (0, hwnd, msg, wParam, lParam, 1);
4326 #endif
4327 /* Processing the generated WM_CHAR messages *WHILE* we
4328 handle KEYDOWN/UP event is the best choice, since
4329 without any fuss, we know all 3 of: scancode, virtual
4330 keycode, and expansion. (Additionally, one knows
4331 boundaries of expansion of different keypresses.) */
4332 res = deliver_wm_chars (1, hwnd, msg, wParam, lParam, 1);
4333 windows_translate = -(res != 0);
4334 if (res > 0) /* Bound to character(s) or a deadkey */
4335 break;
4336 /* deliver_wm_chars may make some branches after this vestigal. */
4338 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4339 /* If not defined as a function key, change it to a WM_CHAR message. */
4340 if (wParam > 255 || !lispy_function_keys[wParam])
4342 DWORD modifiers = construct_console_modifiers ();
4344 if (!NILP (Vw32_recognize_altgr)
4345 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4347 /* Always let TranslateMessage handle AltGr key chords;
4348 for some reason, ToAscii doesn't always process AltGr
4349 chords correctly. */
4350 windows_translate = 1;
4352 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4354 /* Handle key chords including any modifiers other
4355 than shift directly, in order to preserve as much
4356 modifier information as possible. */
4357 if ('A' <= wParam && wParam <= 'Z')
4359 /* Don't translate modified alphabetic keystrokes,
4360 so the user doesn't need to constantly switch
4361 layout to type control or meta keystrokes when
4362 the normal layout translates alphabetic
4363 characters to non-ascii characters. */
4364 if (!modifier_set (VK_SHIFT))
4365 wParam += ('a' - 'A');
4366 msg = WM_CHAR;
4368 else
4370 /* Try to handle other keystrokes by determining the
4371 base character (ie. translating the base key plus
4372 shift modifier). */
4373 int add;
4374 KEY_EVENT_RECORD key;
4376 key.bKeyDown = TRUE;
4377 key.wRepeatCount = 1;
4378 key.wVirtualKeyCode = wParam;
4379 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4380 key.uChar.AsciiChar = 0;
4381 key.dwControlKeyState = modifiers;
4383 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
4384 /* 0 means an unrecognized keycode, negative means
4385 dead key. Ignore both. */
4386 while (--add >= 0)
4388 /* Forward asciified character sequence. */
4389 post_character_message
4390 (hwnd, WM_CHAR,
4391 (unsigned char) key.uChar.AsciiChar, lParam,
4392 w32_get_key_modifiers (wParam, lParam));
4393 w32_kbd_patch_key (&key, w32_keyboard_codepage);
4395 return 0;
4398 else
4400 /* Let TranslateMessage handle everything else. */
4401 windows_translate = 1;
4406 if (windows_translate == -1)
4407 break;
4408 translate:
4409 if (windows_translate)
4411 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4412 windows_msg.time = GetMessageTime ();
4413 TranslateMessage (&windows_msg);
4414 goto dflt;
4416 /* Fall through */
4417 FALLTHROUGH;
4419 case WM_SYSCHAR:
4420 case WM_CHAR:
4421 if (wParam > 255 )
4423 W32Msg wmsg;
4425 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4426 signal_user_input ();
4427 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
4430 else
4431 post_character_message (hwnd, msg, wParam, lParam,
4432 w32_get_key_modifiers (wParam, lParam));
4433 break;
4435 case WM_UNICHAR:
4436 /* WM_UNICHAR looks promising from the docs, but the exact
4437 circumstances in which TranslateMessage sends it is one of those
4438 Microsoft secret API things that EU and US courts are supposed
4439 to have put a stop to already. Spy++ shows it being sent to Notepad
4440 and other MS apps, but never to Emacs.
4442 Some third party IMEs send it in accordance with the official
4443 documentation though, so handle it here.
4445 UNICODE_NOCHAR is used to test for support for this message.
4446 TRUE indicates that the message is supported. */
4447 if (wParam == UNICODE_NOCHAR)
4448 return TRUE;
4451 W32Msg wmsg;
4452 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4453 signal_user_input ();
4454 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4456 break;
4458 case WM_IME_CHAR:
4459 /* If we can't get the IME result as Unicode, use default processing,
4460 which will at least allow characters decodable in the system locale
4461 get through. */
4462 if (!get_composition_string_fn)
4463 goto dflt;
4465 else if (!ignore_ime_char)
4467 wchar_t * buffer;
4468 int size, i;
4469 W32Msg wmsg;
4470 HIMC context = get_ime_context_fn (hwnd);
4471 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4472 /* Get buffer size. */
4473 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
4474 buffer = alloca (size);
4475 size = get_composition_string_fn (context, GCS_RESULTSTR,
4476 buffer, size);
4477 release_ime_context_fn (hwnd, context);
4479 signal_user_input ();
4480 for (i = 0; i < size / sizeof (wchar_t); i++)
4482 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
4483 lParam);
4485 /* Ignore the messages for the rest of the
4486 characters in the string that was output above. */
4487 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
4489 else
4490 ignore_ime_char--;
4492 break;
4494 case WM_IME_STARTCOMPOSITION:
4495 if (!set_ime_composition_window_fn)
4496 goto dflt;
4497 else
4499 COMPOSITIONFORM form;
4500 HIMC context;
4501 struct window *w;
4503 /* Implementation note: The code below does something that
4504 one shouldn't do: it accesses the window object from a
4505 separate thread, while the main (a.k.a. "Lisp") thread
4506 runs and can legitimately delete and even GC it. That is
4507 why we are extra careful not to futz with a window that
4508 is different from the one recorded when the system caret
4509 coordinates were last modified. That is also why we are
4510 careful not to move the IME window if the window
4511 described by W was deleted, as indicated by its buffer
4512 field being reset to nil. */
4513 f = x_window_to_frame (dpyinfo, hwnd);
4514 if (!(f && FRAME_LIVE_P (f)))
4515 goto dflt;
4516 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
4517 /* Punt if someone changed the frame's selected window
4518 behind our back. */
4519 if (w != w32_system_caret_window)
4520 goto dflt;
4522 form.dwStyle = CFS_RECT;
4523 form.ptCurrentPos.x = w32_system_caret_x;
4524 form.ptCurrentPos.y = w32_system_caret_y;
4526 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
4527 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
4528 + w32_system_caret_hdr_height);
4529 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
4530 - WINDOW_RIGHT_MARGIN_WIDTH (w)
4531 - WINDOW_RIGHT_FRINGE_WIDTH (w));
4532 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
4533 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
4534 - w32_system_caret_mode_height);
4536 /* Punt if the window was deleted behind our back. */
4537 if (!BUFFERP (w->contents))
4538 goto dflt;
4540 context = get_ime_context_fn (hwnd);
4542 if (!context)
4543 goto dflt;
4545 set_ime_composition_window_fn (context, &form);
4546 release_ime_context_fn (hwnd, context);
4548 /* We should "goto dflt" here to pass WM_IME_STARTCOMPOSITION to
4549 DefWindowProc, so that the composition window will actually
4550 be displayed. But doing so causes trouble with displaying
4551 dialog boxes, such as the file selection dialog or font
4552 selection dialog. So something else is needed to fix the
4553 former without breaking the latter. See bug#11732. */
4554 break;
4556 case WM_IME_ENDCOMPOSITION:
4557 ignore_ime_char = 0;
4558 goto dflt;
4560 /* Simulate middle mouse button events when left and right buttons
4561 are used together, but only if user has two button mouse. */
4562 case WM_LBUTTONDOWN:
4563 case WM_RBUTTONDOWN:
4564 if (w32_num_mouse_buttons > 2)
4565 goto handle_plain_button;
4568 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4569 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4571 if (button_state & this)
4572 return 0;
4574 if (button_state == 0)
4575 SetCapture (hwnd);
4577 button_state |= this;
4579 if (button_state & other)
4581 if (mouse_button_timer)
4583 KillTimer (hwnd, mouse_button_timer);
4584 mouse_button_timer = 0;
4586 /* Generate middle mouse event instead. */
4587 msg = WM_MBUTTONDOWN;
4588 button_state |= MMOUSE;
4590 else if (button_state & MMOUSE)
4592 /* Ignore button event if we've already generated a
4593 middle mouse down event. This happens if the
4594 user releases and press one of the two buttons
4595 after we've faked a middle mouse event. */
4596 return 0;
4598 else
4600 /* Flush out saved message. */
4601 post_msg (&saved_mouse_button_msg);
4603 wmsg.dwModifiers = w32_get_modifiers ();
4604 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4605 signal_user_input ();
4607 /* Clear message buffer. */
4608 saved_mouse_button_msg.msg.hwnd = 0;
4610 else
4612 /* Hold onto message for now. */
4613 mouse_button_timer =
4614 SetTimer (hwnd, MOUSE_BUTTON_ID,
4615 w32_mouse_button_tolerance, NULL);
4616 saved_mouse_button_msg.msg.hwnd = hwnd;
4617 saved_mouse_button_msg.msg.message = msg;
4618 saved_mouse_button_msg.msg.wParam = wParam;
4619 saved_mouse_button_msg.msg.lParam = lParam;
4620 saved_mouse_button_msg.msg.time = GetMessageTime ();
4621 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4624 return 0;
4626 case WM_LBUTTONUP:
4627 case WM_RBUTTONUP:
4628 if (w32_num_mouse_buttons > 2)
4629 goto handle_plain_button;
4632 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4633 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4635 if ((button_state & this) == 0)
4636 return 0;
4638 button_state &= ~this;
4640 if (button_state & MMOUSE)
4642 /* Only generate event when second button is released. */
4643 if ((button_state & other) == 0)
4645 msg = WM_MBUTTONUP;
4646 button_state &= ~MMOUSE;
4648 if (button_state) emacs_abort ();
4650 else
4651 return 0;
4653 else
4655 /* Flush out saved message if necessary. */
4656 if (saved_mouse_button_msg.msg.hwnd)
4658 post_msg (&saved_mouse_button_msg);
4661 wmsg.dwModifiers = w32_get_modifiers ();
4662 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4663 signal_user_input ();
4665 /* Always clear message buffer and cancel timer. */
4666 saved_mouse_button_msg.msg.hwnd = 0;
4667 KillTimer (hwnd, mouse_button_timer);
4668 mouse_button_timer = 0;
4670 if (button_state == 0)
4671 ReleaseCapture ();
4673 return 0;
4675 case WM_XBUTTONDOWN:
4676 case WM_XBUTTONUP:
4677 if (w32_pass_extra_mouse_buttons_to_system)
4678 goto dflt;
4679 /* else fall through and process them. */
4680 FALLTHROUGH;
4681 case WM_MBUTTONDOWN:
4682 case WM_MBUTTONUP:
4683 handle_plain_button:
4685 BOOL up;
4686 int button;
4688 /* Ignore middle and extra buttons as long as the menu is active. */
4689 f = x_window_to_frame (dpyinfo, hwnd);
4690 if (f && f->output_data.w32->menubar_active)
4691 return 0;
4693 if (parse_button (msg, HIWORD (wParam), &button, &up))
4695 if (up) ReleaseCapture ();
4696 else SetCapture (hwnd);
4697 button = (button == 0) ? LMOUSE :
4698 ((button == 1) ? MMOUSE : RMOUSE);
4699 if (up)
4700 button_state &= ~button;
4701 else
4702 button_state |= button;
4706 if (f && (msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN
4707 || msg == WM_MBUTTONDOWN ||msg == WM_XBUTTONDOWN)
4708 && !FRAME_NO_ACCEPT_FOCUS (f))
4709 /* When clicking into a child frame or when clicking into a
4710 parent frame with the child frame selected and
4711 `no-accept-focus' is not set, select the clicked frame. */
4713 struct frame *p = FRAME_PARENT_FRAME (XFRAME (selected_frame));
4715 if (FRAME_PARENT_FRAME (f) || f == p)
4717 SetFocus (hwnd);
4718 SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
4722 wmsg.dwModifiers = w32_get_modifiers ();
4723 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4724 signal_user_input ();
4726 /* Need to return true for XBUTTON messages, false for others,
4727 to indicate that we processed the message. */
4728 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4730 case WM_MOUSEMOVE:
4731 f = x_window_to_frame (dpyinfo, hwnd);
4732 if (f)
4734 /* Ignore mouse movements as long as the menu is active.
4735 These movements are processed by the window manager
4736 anyway, and it's wrong to handle them as if they happened
4737 on the underlying frame. */
4738 if (f->output_data.w32->menubar_active)
4739 return 0;
4741 /* If the mouse moved, and the mouse pointer is invisible,
4742 make it visible again. We do this here so as to be able
4743 to show the mouse pointer even when the main
4744 (a.k.a. "Lisp") thread is busy doing something. */
4745 static int last_x, last_y;
4746 int x = GET_X_LPARAM (lParam);
4747 int y = GET_Y_LPARAM (lParam);
4749 if (f->pointer_invisible
4750 && (x != last_x || y != last_y))
4751 f->pointer_invisible = false;
4753 last_x = x;
4754 last_y = y;
4757 /* If the mouse has just moved into the frame, start tracking
4758 it, so we will be notified when it leaves the frame. Mouse
4759 tracking only works under W98 and NT4 and later. On earlier
4760 versions, there is no way of telling when the mouse leaves the
4761 frame, so we just have to put up with help-echo and mouse
4762 highlighting remaining while the frame is not active. */
4763 if (track_mouse_event_fn && !track_mouse_window
4764 /* If the menu bar is active, turning on tracking of mouse
4765 movement events might send these events to the tooltip
4766 frame, if the user happens to move the mouse pointer over
4767 the tooltip. But since we don't process events for
4768 tooltip frames, this causes Windows to present a
4769 hourglass cursor, which is ugly and unexpected. So don't
4770 enable tracking mouse events in this case; they will be
4771 restarted when the menu pops down. (Confusingly, the
4772 menubar_active member of f->output_data.w32, tested
4773 above, is only set when a menu was popped up _not_ from
4774 the frame's menu bar, but via x-popup-menu.) */
4775 && !menubar_in_use)
4777 TRACKMOUSEEVENT tme;
4778 tme.cbSize = sizeof (tme);
4779 tme.dwFlags = TME_LEAVE;
4780 tme.hwndTrack = hwnd;
4781 tme.dwHoverTime = HOVER_DEFAULT;
4783 track_mouse_event_fn (&tme);
4784 track_mouse_window = hwnd;
4786 FALLTHROUGH;
4787 case WM_HSCROLL:
4788 case WM_VSCROLL:
4789 if (w32_mouse_move_interval <= 0
4790 || (msg == WM_MOUSEMOVE && button_state == 0))
4792 wmsg.dwModifiers = w32_get_modifiers ();
4793 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4794 return 0;
4797 /* Hang onto mouse move and scroll messages for a bit, to avoid
4798 sending such events to Emacs faster than it can process them.
4799 If we get more events before the timer from the first message
4800 expires, we just replace the first message. */
4802 if (saved_mouse_move_msg.msg.hwnd == 0)
4803 mouse_move_timer =
4804 SetTimer (hwnd, MOUSE_MOVE_ID,
4805 w32_mouse_move_interval, NULL);
4807 /* Hold onto message for now. */
4808 saved_mouse_move_msg.msg.hwnd = hwnd;
4809 saved_mouse_move_msg.msg.message = msg;
4810 saved_mouse_move_msg.msg.wParam = wParam;
4811 saved_mouse_move_msg.msg.lParam = lParam;
4812 saved_mouse_move_msg.msg.time = GetMessageTime ();
4813 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4815 return 0;
4817 case WM_MOUSEWHEEL:
4818 case WM_DROPFILES:
4819 wmsg.dwModifiers = w32_get_modifiers ();
4820 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4821 signal_user_input ();
4822 return 0;
4824 case WM_APPCOMMAND:
4825 if (w32_pass_multimedia_buttons_to_system)
4826 goto dflt;
4827 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
4828 FALLTHROUGH;
4830 /* FIXME!!! This is never reached so what's the purpose? If the
4831 non-zero return remark below is right we're doing it wrong all
4832 the time. */
4833 case WM_MOUSEHWHEEL:
4834 wmsg.dwModifiers = w32_get_modifiers ();
4835 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4836 signal_user_input ();
4837 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
4838 handled, to prevent the system trying to handle it by faking
4839 scroll bar events. */
4840 return 1;
4842 case WM_TIMER:
4843 /* Flush out saved messages if necessary. */
4844 if (wParam == mouse_button_timer)
4846 if (saved_mouse_button_msg.msg.hwnd)
4848 post_msg (&saved_mouse_button_msg);
4849 signal_user_input ();
4850 saved_mouse_button_msg.msg.hwnd = 0;
4852 KillTimer (hwnd, mouse_button_timer);
4853 mouse_button_timer = 0;
4855 else if (wParam == mouse_move_timer)
4857 if (saved_mouse_move_msg.msg.hwnd)
4859 post_msg (&saved_mouse_move_msg);
4860 saved_mouse_move_msg.msg.hwnd = 0;
4862 KillTimer (hwnd, mouse_move_timer);
4863 mouse_move_timer = 0;
4865 else if (wParam == menu_free_timer)
4867 KillTimer (hwnd, menu_free_timer);
4868 menu_free_timer = 0;
4869 f = x_window_to_frame (dpyinfo, hwnd);
4870 /* If a popup menu is active, don't wipe its strings. */
4871 if (menubar_in_use
4872 && current_popup_menu == NULL)
4874 /* Free memory used by owner-drawn and help-echo strings. */
4875 w32_free_menu_strings (hwnd);
4876 if (f)
4877 f->output_data.w32->menubar_active = 0;
4878 menubar_in_use = 0;
4881 return 0;
4883 case WM_NCACTIVATE:
4884 /* Windows doesn't send us focus messages when putting up and
4885 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4886 The only indication we get that something happened is receiving
4887 this message afterwards. So this is a good time to reset our
4888 keyboard modifiers' state. */
4889 reset_modifiers ();
4890 goto dflt;
4892 case WM_INITMENU:
4893 button_state = 0;
4894 ReleaseCapture ();
4895 /* We must ensure menu bar is fully constructed and up to date
4896 before allowing user interaction with it. To achieve this
4897 we send this message to the lisp thread and wait for a
4898 reply (whose value is not actually needed) to indicate that
4899 the menu bar is now ready for use, so we can now return.
4901 To remain responsive in the meantime, we enter a nested message
4902 loop that can process all other messages.
4904 However, we skip all this if the message results from calling
4905 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4906 thread a message because it is blocked on us at this point. We
4907 set menubar_active before calling TrackPopupMenu to indicate
4908 this (there is no possibility of confusion with real menubar
4909 being active). */
4911 f = x_window_to_frame (dpyinfo, hwnd);
4912 if (f
4913 && (f->output_data.w32->menubar_active
4914 /* We can receive this message even in the absence of a
4915 menubar (ie. when the system menu is activated) - in this
4916 case we do NOT want to forward the message, otherwise it
4917 will cause the menubar to suddenly appear when the user
4918 had requested it to be turned off! */
4919 || f->output_data.w32->menubar_widget == NULL))
4920 return 0;
4923 deferred_msg msg_buf;
4925 /* Detect if message has already been deferred; in this case
4926 we cannot return any sensible value to ignore this. */
4927 if (find_deferred_msg (hwnd, msg) != NULL)
4928 emacs_abort ();
4930 menubar_in_use = 1;
4932 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4935 case WM_EXITMENULOOP:
4936 f = x_window_to_frame (dpyinfo, hwnd);
4938 /* If a menu is still active, check again after a short delay,
4939 since Windows often (always?) sends the WM_EXITMENULOOP
4940 before the corresponding WM_COMMAND message.
4941 Don't do this if a popup menu is active, since it is only
4942 menubar menus that require cleaning up in this way.
4944 if (f && menubar_in_use && current_popup_menu == NULL)
4945 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4947 /* If hourglass cursor should be displayed, display it now. */
4948 if (f && f->output_data.w32->hourglass_p)
4949 SetCursor (f->output_data.w32->hourglass_cursor);
4951 goto dflt;
4953 case WM_MENUSELECT:
4954 /* Direct handling of help_echo in menus. Should be safe now
4955 that we generate the help_echo by placing a help event in the
4956 keyboard buffer. */
4958 HMENU menu = (HMENU) lParam;
4959 UINT menu_item = (UINT) LOWORD (wParam);
4960 UINT flags = (UINT) HIWORD (wParam);
4962 w32_menu_display_help (hwnd, menu, menu_item, flags);
4964 return 0;
4966 case WM_MEASUREITEM:
4967 f = x_window_to_frame (dpyinfo, hwnd);
4968 if (f)
4970 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4972 if (pMis->CtlType == ODT_MENU)
4974 /* Work out dimensions for popup menu titles. */
4975 char * title = (char *) pMis->itemData;
4976 HDC hdc = GetDC (hwnd);
4977 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4978 LOGFONT menu_logfont;
4979 HFONT old_font;
4980 SIZE size;
4982 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4983 menu_logfont.lfWeight = FW_BOLD;
4984 menu_font = CreateFontIndirect (&menu_logfont);
4985 old_font = SelectObject (hdc, menu_font);
4987 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4988 if (title)
4990 if (unicode_append_menu)
4991 GetTextExtentPoint32W (hdc, (WCHAR *) title,
4992 wcslen ((WCHAR *) title),
4993 &size);
4994 else
4995 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4997 pMis->itemWidth = size.cx;
4998 if (pMis->itemHeight < size.cy)
4999 pMis->itemHeight = size.cy;
5001 else
5002 pMis->itemWidth = 0;
5004 SelectObject (hdc, old_font);
5005 DeleteObject (menu_font);
5006 ReleaseDC (hwnd, hdc);
5007 return TRUE;
5010 return 0;
5012 case WM_DRAWITEM:
5013 f = x_window_to_frame (dpyinfo, hwnd);
5014 if (f)
5016 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
5018 if (pDis->CtlType == ODT_MENU)
5020 /* Draw popup menu title. */
5021 char * title = (char *) pDis->itemData;
5022 if (title)
5024 HDC hdc = pDis->hDC;
5025 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
5026 LOGFONT menu_logfont;
5027 HFONT old_font;
5029 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
5030 menu_logfont.lfWeight = FW_BOLD;
5031 menu_font = CreateFontIndirect (&menu_logfont);
5032 old_font = SelectObject (hdc, menu_font);
5034 /* Always draw title as if not selected. */
5035 if (unicode_append_menu)
5036 ExtTextOutW (hdc,
5037 pDis->rcItem.left
5038 + GetSystemMetrics (SM_CXMENUCHECK),
5039 pDis->rcItem.top,
5040 ETO_OPAQUE, &pDis->rcItem,
5041 (WCHAR *) title,
5042 wcslen ((WCHAR *) title), NULL);
5043 else
5044 ExtTextOut (hdc,
5045 pDis->rcItem.left
5046 + GetSystemMetrics (SM_CXMENUCHECK),
5047 pDis->rcItem.top,
5048 ETO_OPAQUE, &pDis->rcItem,
5049 title, strlen (title), NULL);
5051 SelectObject (hdc, old_font);
5052 DeleteObject (menu_font);
5054 return TRUE;
5057 return 0;
5059 case WM_MOUSEACTIVATE:
5060 /* WM_MOUSEACTIVATE is the only way on Windows to implement the
5061 `no-accept-focus' frame parameter. This means that one can't
5062 use the mouse to scroll a window on a non-selected frame. */
5064 /* Still not right - can't distinguish between clicks in the
5065 client area of the frame from clicks forwarded from the scroll
5066 bars - may have to hook WM_NCHITTEST to remember the mouse
5067 position and then check if it is in the client area
5068 ourselves. */
5070 /* Discard the mouse click that activates a frame, allowing the
5071 user to click anywhere without changing point (or worse!).
5072 Don't eat mouse clicks on scrollbars though!! */
5074 if ((f = x_window_to_frame (dpyinfo, hwnd))
5075 && FRAME_NO_ACCEPT_FOCUS (f)
5076 /* Ignore child frames, they don't accept focus anyway. */
5077 && !FRAME_PARENT_FRAME (f))
5079 Lisp_Object frame;
5081 XSETFRAME (frame, f);
5082 if (!EQ (selected_frame, frame))
5083 /* Don't discard the message, GTK doesn't either. */
5084 return MA_NOACTIVATE; /* ANDEAT; */
5086 goto dflt;
5088 case WM_MOUSELEAVE:
5089 /* No longer tracking mouse. */
5090 track_mouse_window = NULL;
5091 FALLTHROUGH;
5093 case WM_ACTIVATEAPP:
5094 case WM_ACTIVATE:
5095 case WM_WINDOWPOSCHANGED:
5096 case WM_SHOWWINDOW:
5097 /* Inform lisp thread that a frame might have just been obscured
5098 or exposed, so should recheck visibility of all frames. */
5099 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5100 goto dflt;
5102 case WM_SETFOCUS:
5103 dpyinfo->faked_key = 0;
5104 reset_modifiers ();
5105 if (!w32_kbdhook_active)
5106 register_hot_keys (hwnd);
5107 goto command;
5108 case WM_KILLFOCUS:
5109 if (!w32_kbdhook_active)
5110 unregister_hot_keys (hwnd);
5111 button_state = 0;
5112 ReleaseCapture ();
5113 /* Relinquish the system caret. */
5114 if (w32_system_caret_hwnd)
5116 w32_visible_system_caret_hwnd = NULL;
5117 w32_system_caret_hwnd = NULL;
5118 DestroyCaret ();
5120 goto command;
5121 case WM_COMMAND:
5122 menubar_in_use = 0;
5123 f = x_window_to_frame (dpyinfo, hwnd);
5124 if (f && HIWORD (wParam) == 0)
5126 if (menu_free_timer)
5128 KillTimer (hwnd, menu_free_timer);
5129 menu_free_timer = 0;
5132 FALLTHROUGH;
5133 case WM_MOVE:
5134 case WM_SIZE:
5135 command:
5136 wmsg.dwModifiers = w32_get_modifiers ();
5137 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5138 goto dflt;
5140 #ifdef WINDOWSNT
5141 case WM_CREATE:
5142 setup_w32_kbdhook ();
5143 goto dflt;
5144 #endif
5146 case WM_DESTROY:
5147 #ifdef WINDOWSNT
5148 remove_w32_kbdhook ();
5149 #endif
5150 CoUninitialize ();
5151 return 0;
5153 case WM_WTSSESSION_CHANGE:
5154 if (wParam == WTS_SESSION_LOCK)
5155 reset_w32_kbdhook_state ();
5156 goto dflt;
5158 case WM_CLOSE:
5159 wmsg.dwModifiers = w32_get_modifiers ();
5160 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5161 return 0;
5163 case WM_ENDSESSION:
5164 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5165 /* Allow time for Emacs to attempt an orderly shutdown. If we
5166 return, the process will be terminated immediately. FIXME:
5167 1000 seconds is too long to sleep if the shutdown attempt
5168 fails (see bug#25875). But if it fails, we want to find out
5169 about it, so let's leave 1000 for now. */
5170 sleep (1000);
5171 FALLTHROUGH;
5173 case WM_WINDOWPOSCHANGING:
5174 /* Don't restrict the sizing of any kind of frames. If the window
5175 manager doesn't, there's no reason to do it ourselves. */
5176 return 0;
5178 case WM_GETMINMAXINFO:
5179 /* Hack to allow resizing the Emacs frame above the screen size.
5180 Note that Windows 9x limits coordinates to 16-bits. */
5181 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
5182 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
5183 return 0;
5185 case WM_SETCURSOR:
5186 if (LOWORD (lParam) == HTCLIENT)
5188 f = x_window_to_frame (dpyinfo, hwnd);
5189 if (f)
5191 if (f->output_data.w32->hourglass_p
5192 && !menubar_in_use && !current_popup_menu)
5193 SetCursor (f->output_data.w32->hourglass_cursor);
5194 else if (f->pointer_invisible)
5195 SetCursor (NULL);
5196 else
5197 SetCursor (f->output_data.w32->current_cursor);
5200 return 0;
5202 goto dflt;
5204 case WM_EMACS_SETCURSOR:
5206 Cursor cursor = (Cursor) wParam;
5207 f = x_window_to_frame (dpyinfo, hwnd);
5208 if (f && cursor)
5210 f->output_data.w32->current_cursor = cursor;
5211 /* Don't change the cursor while menu-bar menu is in use. */
5212 if (!f->output_data.w32->menubar_active
5213 && !f->output_data.w32->hourglass_p)
5215 if (f->pointer_invisible)
5216 SetCursor (NULL);
5217 else
5218 SetCursor (cursor);
5221 return 0;
5224 case WM_EMACS_SHOWCURSOR:
5226 ShowCursor ((BOOL) wParam);
5228 return 0;
5231 case WM_EMACS_CREATEVSCROLLBAR:
5232 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
5233 (struct scroll_bar *) lParam);
5235 case WM_EMACS_CREATEHSCROLLBAR:
5236 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
5237 (struct scroll_bar *) lParam);
5239 case WM_EMACS_SHOWWINDOW:
5240 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
5242 case WM_EMACS_BRINGTOTOP:
5243 case WM_EMACS_SETFOREGROUND:
5245 HWND foreground_window;
5246 DWORD foreground_thread, retval;
5248 /* On NT 5.0, and apparently Windows 98, it is necessary to
5249 attach to the thread that currently has focus in order to
5250 pull the focus away from it. */
5251 foreground_window = GetForegroundWindow ();
5252 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
5253 if (!foreground_window
5254 || foreground_thread == GetCurrentThreadId ()
5255 || !AttachThreadInput (GetCurrentThreadId (),
5256 foreground_thread, TRUE))
5257 foreground_thread = 0;
5259 retval = SetForegroundWindow ((HWND) wParam);
5260 if (msg == WM_EMACS_BRINGTOTOP)
5261 retval = BringWindowToTop ((HWND) wParam);
5263 /* Detach from the previous foreground thread. */
5264 if (foreground_thread)
5265 AttachThreadInput (GetCurrentThreadId (),
5266 foreground_thread, FALSE);
5268 /* SetFocus to give/remove focus to/from a child window. */
5269 if (msg == WM_EMACS_SETFOREGROUND)
5270 SetFocus ((HWND) wParam);
5272 return retval;
5275 case WM_EMACS_SETWINDOWPOS:
5277 WINDOWPOS * pos = (WINDOWPOS *) wParam;
5278 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5279 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
5282 case WM_EMACS_DESTROYWINDOW:
5283 DragAcceptFiles ((HWND) wParam, FALSE);
5284 return DestroyWindow ((HWND) wParam);
5286 case WM_EMACS_HIDE_CARET:
5287 return HideCaret (hwnd);
5289 case WM_EMACS_SHOW_CARET:
5290 return ShowCaret (hwnd);
5292 case WM_EMACS_DESTROY_CARET:
5293 w32_system_caret_hwnd = NULL;
5294 w32_visible_system_caret_hwnd = NULL;
5295 return DestroyCaret ();
5297 case WM_EMACS_TRACK_CARET:
5298 /* If there is currently no system caret, create one. */
5299 if (w32_system_caret_hwnd == NULL)
5301 /* Use the default caret width, and avoid changing it
5302 unnecessarily, as it confuses screen reader software. */
5303 w32_system_caret_hwnd = hwnd;
5304 CreateCaret (hwnd, NULL, 0,
5305 w32_system_caret_height);
5308 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
5309 return 0;
5310 /* Ensure visible caret gets turned on when requested. */
5311 else if (w32_use_visible_system_caret
5312 && w32_visible_system_caret_hwnd != hwnd)
5314 w32_visible_system_caret_hwnd = hwnd;
5315 return ShowCaret (hwnd);
5317 /* Ensure visible caret gets turned off when requested. */
5318 else if (!w32_use_visible_system_caret
5319 && w32_visible_system_caret_hwnd)
5321 w32_visible_system_caret_hwnd = NULL;
5322 return HideCaret (hwnd);
5324 else
5325 return 1;
5327 case WM_EMACS_TRACKPOPUPMENU:
5329 UINT flags;
5330 POINT *pos;
5331 int retval;
5332 pos = (POINT *)lParam;
5333 flags = TPM_CENTERALIGN;
5334 if (button_state & LMOUSE)
5335 flags |= TPM_LEFTBUTTON;
5336 else if (button_state & RMOUSE)
5337 flags |= TPM_RIGHTBUTTON;
5339 /* Remember we did a SetCapture on the initial mouse down event,
5340 so for safety, we make sure the capture is canceled now. */
5341 ReleaseCapture ();
5342 button_state = 0;
5344 /* Use menubar_active to indicate that WM_INITMENU is from
5345 TrackPopupMenu below, and should be ignored. */
5346 f = x_window_to_frame (dpyinfo, hwnd);
5347 if (f)
5348 f->output_data.w32->menubar_active = 1;
5350 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
5351 0, hwnd, NULL))
5353 MSG amsg;
5354 /* Eat any mouse messages during popupmenu */
5355 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
5356 PM_REMOVE));
5357 /* Get the menu selection, if any */
5358 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
5360 retval = LOWORD (amsg.wParam);
5362 else
5364 retval = 0;
5367 else
5369 retval = -1;
5372 return retval;
5374 case WM_EMACS_FILENOTIFY:
5375 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5376 return 1;
5378 default:
5379 /* Check for messages registered at runtime. */
5380 if (msg == msh_mousewheel)
5382 wmsg.dwModifiers = w32_get_modifiers ();
5383 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5384 signal_user_input ();
5385 return 0;
5388 dflt:
5389 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
5392 /* The most common default return code for handled messages is 0. */
5393 return 0;
5396 static void
5397 my_create_window (struct frame * f)
5399 MSG msg;
5400 static int coords[2];
5401 Lisp_Object left, top;
5402 struct w32_display_info *dpyinfo = &one_w32_display_info;
5404 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
5405 anything that is not a number and is not Qunbound. */
5406 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
5407 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
5408 if (EQ (left, Qunbound))
5409 coords[0] = CW_USEDEFAULT;
5410 else
5411 coords[0] = XINT (left);
5412 if (EQ (top, Qunbound))
5413 coords[1] = CW_USEDEFAULT;
5414 else
5415 coords[1] = XINT (top);
5417 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
5418 (WPARAM)f, (LPARAM)coords))
5419 emacs_abort ();
5420 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5424 /* Create a tooltip window. Unlike my_create_window, we do not do this
5425 indirectly via the Window thread, as we do not need to process Window
5426 messages for the tooltip. Creating tooltips indirectly also creates
5427 deadlocks when tooltips are created for menu items. */
5428 static void
5429 my_create_tip_window (struct frame *f)
5431 RECT rect;
5433 rect.left = rect.top = 0;
5434 rect.right = FRAME_PIXEL_WIDTH (f);
5435 rect.bottom = FRAME_PIXEL_HEIGHT (f);
5437 AdjustWindowRect (&rect, f->output_data.w32->dwStyle, false);
5439 tip_window = FRAME_W32_WINDOW (f)
5440 = CreateWindow (EMACS_CLASS,
5441 f->namebuf,
5442 f->output_data.w32->dwStyle,
5443 f->left_pos,
5444 f->top_pos,
5445 rect.right - rect.left,
5446 rect.bottom - rect.top,
5447 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5448 NULL,
5449 hinst,
5450 NULL);
5452 if (tip_window)
5454 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
5455 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
5456 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
5457 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5459 /* Tip frames have no scrollbars. */
5460 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
5461 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
5463 /* Do this to discard the default setting specified by our parent. */
5464 ShowWindow (tip_window, SW_HIDE);
5469 /* Create and set up the w32 window for frame F. */
5471 static void
5472 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
5474 block_input ();
5476 /* Use the resource name as the top-level window name
5477 for looking up resources. Make a non-Lisp copy
5478 for the window manager, so GC relocation won't bother it.
5480 Elsewhere we specify the window name for the window manager. */
5481 f->namebuf = xlispstrdup (Vx_resource_name);
5483 my_create_window (f);
5485 validate_x_resource_name ();
5487 /* x_set_name normally ignores requests to set the name if the
5488 requested name is the same as the current name. This is the one
5489 place where that assumption isn't correct; f->name is set, but
5490 the server hasn't been told. */
5492 Lisp_Object name;
5493 int explicit = f->explicit_name;
5495 f->explicit_name = 0;
5496 name = f->name;
5497 fset_name (f, Qnil);
5498 x_set_name (f, name, explicit);
5501 unblock_input ();
5503 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f)
5504 && !FRAME_PARENT_FRAME (f))
5505 initialize_frame_menubar (f);
5507 if (FRAME_W32_WINDOW (f) == 0)
5508 error ("Unable to create window");
5511 /* Handle the icon stuff for this window. Perhaps later we might
5512 want an x_set_icon_position which can be called interactively as
5513 well. */
5515 static void
5516 x_icon (struct frame *f, Lisp_Object parms)
5518 Lisp_Object icon_x, icon_y;
5519 struct w32_display_info *dpyinfo = &one_w32_display_info;
5521 /* Set the position of the icon. Note that Windows 95 groups all
5522 icons in the tray. */
5523 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5524 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5525 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5527 CHECK_NUMBER (icon_x);
5528 CHECK_NUMBER (icon_y);
5530 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5531 error ("Both left and top icon corners of icon must be specified");
5533 block_input ();
5535 #if 0 /* TODO */
5536 /* Start up iconic or window? */
5537 x_wm_set_window_state
5538 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5539 ? IconicState
5540 : NormalState));
5542 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
5543 ? f->icon_name
5544 : f->name)));
5545 #endif
5547 unblock_input ();
5551 static void
5552 x_make_gc (struct frame *f)
5554 XGCValues gc_values;
5556 block_input ();
5558 /* Create the GC's of this frame.
5559 Note that many default values are used. */
5561 /* Normal video */
5562 gc_values.font = FRAME_FONT (f);
5564 /* Cursor has cursor-color background, background-color foreground. */
5565 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5566 gc_values.background = f->output_data.w32->cursor_pixel;
5567 f->output_data.w32->cursor_gc
5568 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5569 (GCFont | GCForeground | GCBackground),
5570 &gc_values);
5572 /* Reliefs. */
5573 f->output_data.w32->white_relief.gc = 0;
5574 f->output_data.w32->black_relief.gc = 0;
5576 unblock_input ();
5580 /* Handler for signals raised during x_create_frame and
5581 x_create_tip_frame. FRAME is the frame which is partially
5582 constructed. */
5584 static Lisp_Object
5585 unwind_create_frame (Lisp_Object frame)
5587 struct frame *f = XFRAME (frame);
5589 /* If frame is ``official'', nothing to do. */
5590 if (NILP (Fmemq (frame, Vframe_list)))
5592 #ifdef GLYPH_DEBUG
5593 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5595 /* If the frame's image cache refcount is still the same as our
5596 private shadow variable, it means we are unwinding a frame
5597 for which we didn't yet call init_frame_faces, where the
5598 refcount is incremented. Therefore, we increment it here, so
5599 that free_frame_faces, called in x_free_frame_resources
5600 below, will not mistakenly decrement the counter that was not
5601 incremented yet to account for this new frame. */
5602 if (FRAME_IMAGE_CACHE (f) != NULL
5603 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
5604 FRAME_IMAGE_CACHE (f)->refcount++;
5605 #endif
5607 x_free_frame_resources (f);
5608 free_glyphs (f);
5610 #ifdef GLYPH_DEBUG
5611 /* Check that reference counts are indeed correct. */
5612 eassert (dpyinfo->reference_count == dpyinfo_refcount);
5613 eassert ((dpyinfo->terminal->image_cache == NULL
5614 && image_cache_refcount == 0)
5615 || (dpyinfo->terminal->image_cache != NULL
5616 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
5617 #endif
5618 return Qt;
5621 return Qnil;
5624 static void
5625 do_unwind_create_frame (Lisp_Object frame)
5627 unwind_create_frame (frame);
5630 static void
5631 x_default_font_parameter (struct frame *f, Lisp_Object parms)
5633 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5634 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
5635 RES_TYPE_STRING);
5636 Lisp_Object font;
5637 if (EQ (font_param, Qunbound))
5638 font_param = Qnil;
5639 font = !NILP (font_param) ? font_param
5640 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
5642 if (!STRINGP (font))
5644 int i;
5645 static const char *names[]
5646 = { "Courier New-10",
5647 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
5648 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
5649 "Fixedsys",
5650 NULL };
5652 for (i = 0; names[i]; i++)
5654 font = font_open_by_name (f, build_unibyte_string (names[i]));
5655 if (! NILP (font))
5656 break;
5658 if (NILP (font))
5659 error ("No suitable font was found");
5661 else if (!NILP (font_param))
5663 /* Remember the explicit font parameter, so we can re-apply it after
5664 we've applied the `default' face settings. */
5665 x_set_frame_parameters (f, Fcons (Fcons (Qfont_parameter, font_param),
5666 Qnil));
5668 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
5671 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5672 1, 1, 0,
5673 doc: /* SKIP: real doc in xfns.c. */)
5674 (Lisp_Object parameters)
5676 struct frame *f;
5677 Lisp_Object frame, tem;
5678 Lisp_Object name;
5679 bool minibuffer_only = false;
5680 long window_prompting = 0;
5681 ptrdiff_t count = SPECPDL_INDEX ();
5682 Lisp_Object display;
5683 struct w32_display_info *dpyinfo = NULL;
5684 Lisp_Object parent, parent_frame;
5685 struct kboard *kb;
5686 int x_width = 0, x_height = 0;
5688 if (!FRAME_W32_P (SELECTED_FRAME ())
5689 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
5690 error ("Cannot create a GUI frame in a -nw session");
5692 /* Make copy of frame parameters because the original is in pure
5693 storage now. */
5694 parameters = Fcopy_alist (parameters);
5696 /* Use this general default value to start with
5697 until we know if this frame has a specified name. */
5698 Vx_resource_name = Vinvocation_name;
5700 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
5701 if (EQ (display, Qunbound))
5702 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
5703 if (EQ (display, Qunbound))
5704 display = Qnil;
5705 dpyinfo = check_x_display_info (display);
5706 kb = dpyinfo->terminal->kboard;
5708 if (!dpyinfo->terminal->name)
5709 error ("Terminal is not live, can't create new frames on it");
5711 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5712 if (!STRINGP (name)
5713 && ! EQ (name, Qunbound)
5714 && ! NILP (name))
5715 error ("Invalid frame name--not a string or nil");
5717 if (STRINGP (name))
5718 Vx_resource_name = name;
5720 /* See if parent window is specified. */
5721 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL,
5722 RES_TYPE_NUMBER);
5723 if (EQ (parent, Qunbound))
5724 parent = Qnil;
5725 else if (!NILP (parent))
5726 CHECK_NUMBER (parent);
5728 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5729 /* No need to protect DISPLAY because that's not used after passing
5730 it to make_frame_without_minibuffer. */
5731 frame = Qnil;
5732 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5733 RES_TYPE_SYMBOL);
5734 if (EQ (tem, Qnone) || NILP (tem))
5735 f = make_frame_without_minibuffer (Qnil, kb, display);
5736 else if (EQ (tem, Qonly))
5738 f = make_minibuffer_frame ();
5739 minibuffer_only = true;
5741 else if (WINDOWP (tem))
5742 f = make_frame_without_minibuffer (tem, kb, display);
5743 else
5744 f = make_frame (true);
5746 XSETFRAME (frame, f);
5748 parent_frame = x_get_arg (dpyinfo, parameters, Qparent_frame, NULL, NULL,
5749 RES_TYPE_SYMBOL);
5750 /* Apply `parent-frame' parameter only when no `parent-id' was
5751 specified. */
5752 if (!NILP (parent_frame)
5753 && (!NILP (parent)
5754 || !FRAMEP (parent_frame)
5755 || !FRAME_LIVE_P (XFRAME (parent_frame))
5756 || !FRAME_W32_P (XFRAME (parent_frame))))
5757 parent_frame = Qnil;
5759 fset_parent_frame (f, parent_frame);
5760 store_frame_param (f, Qparent_frame, parent_frame);
5762 tem = x_get_arg (dpyinfo, parameters, Qundecorated, NULL, NULL,
5763 RES_TYPE_BOOLEAN);
5764 FRAME_UNDECORATED (f) = !NILP (tem) && !EQ (tem, Qunbound);
5765 store_frame_param (f, Qundecorated, FRAME_UNDECORATED (f) ? Qt : Qnil);
5767 tem = x_get_arg (dpyinfo, parameters, Qskip_taskbar, NULL, NULL,
5768 RES_TYPE_BOOLEAN);
5769 FRAME_SKIP_TASKBAR (f) = !NILP (tem) && !EQ (tem, Qunbound);
5770 store_frame_param (f, Qskip_taskbar,
5771 (NILP (tem) || EQ (tem, Qunbound)) ? Qnil : Qt);
5773 /* By default, make scrollbars the system standard width and height. */
5774 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5775 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5777 f->terminal = dpyinfo->terminal;
5779 f->output_method = output_w32;
5780 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5781 FRAME_FONTSET (f) = -1;
5783 fset_icon_name
5784 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5785 RES_TYPE_STRING));
5786 if (! STRINGP (f->icon_name))
5787 fset_icon_name (f, Qnil);
5789 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5791 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5792 record_unwind_protect (do_unwind_create_frame, frame);
5794 #ifdef GLYPH_DEBUG
5795 image_cache_refcount =
5796 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5797 dpyinfo_refcount = dpyinfo->reference_count;
5798 #endif /* GLYPH_DEBUG */
5800 /* Specify the parent under which to make this window - this seems to
5801 have no effect on Windows because parent_desc is explicitly reset
5802 below. */
5803 if (!NILP (parent))
5805 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5806 pointer from integer of different size. */
5807 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5808 f->output_data.w32->explicit_parent = true;
5810 else
5812 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5813 f->output_data.w32->explicit_parent = false;
5816 /* Set the name; the functions to which we pass f expect the name to
5817 be set. */
5818 if (EQ (name, Qunbound) || NILP (name))
5820 fset_name (f, build_string (dpyinfo->w32_id_name));
5821 f->explicit_name = false;
5823 else
5825 fset_name (f, name);
5826 f->explicit_name = true;
5827 /* Use the frame's title when getting resources for this frame. */
5828 specbind (Qx_resource_name, name);
5831 if (uniscribe_available)
5832 register_font_driver (&uniscribe_font_driver, f);
5833 register_font_driver (&w32font_driver, f);
5835 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5836 "fontBackend", "FontBackend", RES_TYPE_STRING);
5838 /* Extract the window parameters from the supplied values
5839 that are needed to determine window geometry. */
5840 x_default_font_parameter (f, parameters);
5842 /* Default BorderWidth to 0 to match other platforms. */
5843 x_default_parameter (f, parameters, Qborder_width, make_number (0),
5844 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5846 /* We recognize either internalBorderWidth or internalBorder
5847 (which is what xterm calls it). */
5848 if (NILP (Fassq (Qinternal_border_width, parameters)))
5850 Lisp_Object value;
5852 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5853 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5854 if (! EQ (value, Qunbound))
5855 parameters = Fcons (Fcons (Qinternal_border_width, value),
5856 parameters);
5859 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5860 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5861 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5862 NULL, NULL, RES_TYPE_NUMBER);
5863 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5864 NULL, NULL, RES_TYPE_NUMBER);
5865 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5866 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5867 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5868 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5870 /* Also do the stuff which must be set before the window exists. */
5871 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5872 "foreground", "Foreground", RES_TYPE_STRING);
5873 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5874 "background", "Background", RES_TYPE_STRING);
5875 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5876 "pointerColor", "Foreground", RES_TYPE_STRING);
5877 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5878 "borderColor", "BorderColor", RES_TYPE_STRING);
5879 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5880 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5881 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5882 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5883 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5884 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5885 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5886 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5887 x_default_parameter (f, parameters, Qno_focus_on_map, Qnil,
5888 NULL, NULL, RES_TYPE_BOOLEAN);
5889 x_default_parameter (f, parameters, Qno_accept_focus, Qnil,
5890 NULL, NULL, RES_TYPE_BOOLEAN);
5891 x_default_parameter (f, parameters, Qno_special_glyphs, Qnil,
5892 NULL, NULL, RES_TYPE_BOOLEAN);
5894 /* Process alpha here (Bug#16619). On XP this fails with child
5895 frames. For `no-focus-on-map' frames delay processing of alpha
5896 until the frame becomes visible. */
5897 if (!FRAME_NO_FOCUS_ON_MAP (f))
5898 x_default_parameter (f, parameters, Qalpha, Qnil,
5899 "alpha", "Alpha", RES_TYPE_NUMBER);
5901 /* Init faces first since we need the frame's column width/line
5902 height in various occasions. */
5903 init_frame_faces (f);
5905 /* We have to call adjust_frame_size here since otherwise
5906 x_set_tool_bar_lines will already work with the character sizes
5907 installed by init_frame_faces while the frame's pixel size is still
5908 calculated from a character size of 1 and we subsequently hit the
5909 (height >= 0) assertion in window_box_height.
5911 The non-pixelwise code apparently worked around this because it
5912 had one frame line vs one toolbar line which left us with a zero
5913 root window height which was obviously wrong as well ...
5915 Also process `min-width' and `min-height' parameters right here
5916 because `frame-windows-min-size' needs them. */
5917 tem = x_get_arg (dpyinfo, parameters, Qmin_width, NULL, NULL,
5918 RES_TYPE_NUMBER);
5919 if (NUMBERP (tem))
5920 store_frame_param (f, Qmin_width, tem);
5921 tem = x_get_arg (dpyinfo, parameters, Qmin_height, NULL, NULL,
5922 RES_TYPE_NUMBER);
5923 if (NUMBERP (tem))
5924 store_frame_param (f, Qmin_height, tem);
5925 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5926 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5927 Qx_create_frame_1);
5929 /* The X resources controlling the menu-bar and tool-bar are
5930 processed specially at startup, and reflected in the mode
5931 variables; ignore them here. */
5932 if (NILP (parent_frame))
5934 x_default_parameter (f, parameters, Qmenu_bar_lines,
5935 NILP (Vmenu_bar_mode)
5936 ? make_number (0) : make_number (1),
5937 NULL, NULL, RES_TYPE_NUMBER);
5939 else
5940 /* No menu bar for child frames. */
5941 store_frame_param (f, Qmenu_bar_lines, make_number (0));
5943 x_default_parameter (f, parameters, Qtool_bar_lines,
5944 NILP (Vtool_bar_mode)
5945 ? make_number (0) : make_number (1),
5946 NULL, NULL, RES_TYPE_NUMBER);
5948 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5949 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5950 x_default_parameter (f, parameters, Qtitle, Qnil,
5951 "title", "Title", RES_TYPE_STRING);
5953 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5954 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5955 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5956 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5957 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5958 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5959 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5960 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5961 f->output_data.w32->left_edge_cursor = w32_load_cursor (IDC_SIZEWE);
5962 f->output_data.w32->top_left_corner_cursor = w32_load_cursor (IDC_SIZENWSE);
5963 f->output_data.w32->top_edge_cursor = w32_load_cursor (IDC_SIZENS);
5964 f->output_data.w32->top_right_corner_cursor = w32_load_cursor (IDC_SIZENESW);
5965 f->output_data.w32->right_edge_cursor = w32_load_cursor (IDC_SIZEWE);
5966 f->output_data.w32->bottom_right_corner_cursor = w32_load_cursor (IDC_SIZENWSE);
5967 f->output_data.w32->bottom_edge_cursor = w32_load_cursor (IDC_SIZENS);
5968 f->output_data.w32->bottom_left_corner_cursor = w32_load_cursor (IDC_SIZENESW);
5970 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5972 window_prompting = x_figure_window_size (f, parameters, true, &x_width, &x_height);
5974 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5975 f->no_split = minibuffer_only || EQ (tem, Qt);
5977 w32_window (f, window_prompting, minibuffer_only);
5978 x_icon (f, parameters);
5980 x_make_gc (f);
5982 /* Now consider the frame official. */
5983 f->terminal->reference_count++;
5984 FRAME_DISPLAY_INFO (f)->reference_count++;
5985 Vframe_list = Fcons (frame, Vframe_list);
5987 /* We need to do this after creating the window, so that the
5988 icon-creation functions can say whose icon they're describing. */
5989 x_default_parameter (f, parameters, Qicon_type, Qnil,
5990 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5992 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5993 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5994 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5995 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5996 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5997 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5998 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5999 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
6000 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
6001 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
6003 /* Allow x_set_window_size, now. */
6004 f->can_x_set_window_size = true;
6006 if (x_width > 0)
6007 SET_FRAME_WIDTH (f, x_width);
6008 if (x_height > 0)
6009 SET_FRAME_HEIGHT (f, x_height);
6011 /* Tell the server what size and position, etc, we want, and how
6012 badly we want them. This should be done after we have the menu
6013 bar so that its size can be taken into account. */
6014 block_input ();
6015 x_wm_set_size_hint (f, window_prompting, false);
6016 unblock_input ();
6018 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
6019 Qx_create_frame_2);
6021 /* Process fullscreen parameter here in the hope that normalizing a
6022 fullheight/fullwidth frame will produce the size set by the last
6023 adjust_frame_size call. */
6024 x_default_parameter (f, parameters, Qfullscreen, Qnil,
6025 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
6026 x_default_parameter (f, parameters, Qz_group, Qnil,
6027 NULL, NULL, RES_TYPE_SYMBOL);
6029 /* Make the window appear on the frame and enable display, unless
6030 the caller says not to. However, with explicit parent, Emacs
6031 cannot control visibility, so don't try. */
6032 if (!f->output_data.w32->explicit_parent)
6034 Lisp_Object visibility
6035 = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
6037 if (EQ (visibility, Qicon))
6038 x_iconify_frame (f);
6039 else
6041 if (EQ (visibility, Qunbound))
6042 visibility = Qt;
6044 if (!NILP (visibility))
6045 x_make_frame_visible (f);
6048 store_frame_param (f, Qvisibility, visibility);
6051 /* For `no-focus-on-map' frames set alpha here. */
6052 if (FRAME_NO_FOCUS_ON_MAP (f))
6053 x_default_parameter (f, parameters, Qalpha, Qnil,
6054 "alpha", "Alpha", RES_TYPE_NUMBER);
6056 /* Initialize `default-minibuffer-frame' in case this is the first
6057 frame on this terminal. */
6058 if (FRAME_HAS_MINIBUF_P (f)
6059 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
6060 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
6061 kset_default_minibuffer_frame (kb, frame);
6063 /* All remaining specified parameters, which have not been "used"
6064 by x_get_arg and friends, now go in the misc. alist of the frame. */
6065 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
6066 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
6067 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
6069 /* Make sure windows on this frame appear in calls to next-window
6070 and similar functions. */
6071 Vwindow_list = Qnil;
6073 return unbind_to (count, frame);
6076 /* FRAME is used only to get a handle on the X display. We don't pass the
6077 display info directly because we're called from frame.c, which doesn't
6078 know about that structure. */
6079 Lisp_Object
6080 x_get_focus_frame (struct frame *frame)
6082 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
6083 Lisp_Object xfocus;
6084 if (! dpyinfo->w32_focus_frame)
6085 return Qnil;
6087 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
6088 return xfocus;
6091 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6092 doc: /* SKIP: real doc in xfns.c. */)
6093 (Lisp_Object color, Lisp_Object frame)
6095 XColor foo;
6096 struct frame *f = decode_window_system_frame (frame);
6098 CHECK_STRING (color);
6100 if (w32_defined_color (f, SSDATA (color), &foo, false))
6101 return Qt;
6102 else
6103 return Qnil;
6106 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6107 doc: /* SKIP: real doc in xfns.c. */)
6108 (Lisp_Object color, Lisp_Object frame)
6110 XColor foo;
6111 struct frame *f = decode_window_system_frame (frame);
6113 CHECK_STRING (color);
6115 if (w32_defined_color (f, SSDATA (color), &foo, false))
6116 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
6117 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
6118 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
6119 else
6120 return Qnil;
6123 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6124 doc: /* SKIP: real doc in xfns.c. */)
6125 (Lisp_Object display)
6127 struct w32_display_info *dpyinfo = check_x_display_info (display);
6129 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6130 return Qnil;
6132 return Qt;
6135 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6136 Sx_display_grayscale_p, 0, 1, 0,
6137 doc: /* SKIP: real doc in xfns.c. */)
6138 (Lisp_Object display)
6140 struct w32_display_info *dpyinfo = check_x_display_info (display);
6142 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6143 return Qnil;
6145 return Qt;
6148 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6149 Sx_display_pixel_width, 0, 1, 0,
6150 doc: /* SKIP: real doc in xfns.c. */)
6151 (Lisp_Object display)
6153 struct w32_display_info *dpyinfo = check_x_display_info (display);
6155 return make_number (x_display_pixel_width (dpyinfo));
6158 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6159 Sx_display_pixel_height, 0, 1, 0,
6160 doc: /* SKIP: real doc in xfns.c. */)
6161 (Lisp_Object display)
6163 struct w32_display_info *dpyinfo = check_x_display_info (display);
6165 return make_number (x_display_pixel_height (dpyinfo));
6168 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6169 0, 1, 0,
6170 doc: /* SKIP: real doc in xfns.c. */)
6171 (Lisp_Object display)
6173 struct w32_display_info *dpyinfo = check_x_display_info (display);
6175 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6178 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6179 0, 1, 0,
6180 doc: /* SKIP: real doc in xfns.c. */)
6181 (Lisp_Object display)
6183 struct w32_display_info *dpyinfo = check_x_display_info (display);
6184 int cap;
6186 /* Don't use NCOLORS: it returns incorrect results under remote
6187 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
6188 * overflow and because probably is more meaningful on Windows
6189 * anyway. */
6191 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
6192 return make_number (cap);
6195 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6196 Sx_server_max_request_size,
6197 0, 1, 0,
6198 doc: /* SKIP: real doc in xfns.c. */)
6199 (Lisp_Object display)
6201 return make_number (1);
6204 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6205 doc: /* SKIP: real doc in xfns.c. */)
6206 (Lisp_Object terminal)
6208 return build_string ("Microsoft Corp.");
6211 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6212 doc: /* SKIP: real doc in xfns.c. */)
6213 (Lisp_Object terminal)
6215 return list3i (w32_major_version, w32_minor_version, w32_build_number);
6218 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6219 doc: /* SKIP: real doc in xfns.c. */)
6220 (Lisp_Object display)
6222 return make_number (1);
6225 DEFUN ("x-display-mm-height", Fx_display_mm_height,
6226 Sx_display_mm_height, 0, 1, 0,
6227 doc: /* SKIP: real doc in xfns.c. */)
6228 (Lisp_Object display)
6230 struct w32_display_info *dpyinfo = check_x_display_info (display);
6231 HDC hdc;
6232 double mm_per_pixel;
6234 hdc = GetDC (NULL);
6235 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6236 / GetDeviceCaps (hdc, VERTRES));
6237 ReleaseDC (NULL, hdc);
6239 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
6242 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6243 doc: /* SKIP: real doc in xfns.c. */)
6244 (Lisp_Object display)
6246 struct w32_display_info *dpyinfo = check_x_display_info (display);
6247 HDC hdc;
6248 double mm_per_pixel;
6250 hdc = GetDC (NULL);
6251 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6252 / GetDeviceCaps (hdc, HORZRES));
6253 ReleaseDC (NULL, hdc);
6255 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
6258 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6259 Sx_display_backing_store, 0, 1, 0,
6260 doc: /* SKIP: real doc in xfns.c. */)
6261 (Lisp_Object display)
6263 return intern ("not-useful");
6266 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6267 Sx_display_visual_class, 0, 1, 0,
6268 doc: /* SKIP: real doc in xfns.c. */)
6269 (Lisp_Object display)
6271 struct w32_display_info *dpyinfo = check_x_display_info (display);
6272 Lisp_Object result = Qnil;
6274 if (dpyinfo->has_palette)
6275 result = intern ("pseudo-color");
6276 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6277 result = intern ("static-gray");
6278 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6279 result = intern ("static-color");
6280 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6281 result = intern ("true-color");
6283 return result;
6286 DEFUN ("x-display-save-under", Fx_display_save_under,
6287 Sx_display_save_under, 0, 1, 0,
6288 doc: /* SKIP: real doc in xfns.c. */)
6289 (Lisp_Object display)
6291 return Qnil;
6294 static BOOL CALLBACK ALIGN_STACK
6295 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
6297 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
6299 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
6301 return TRUE;
6304 static Lisp_Object
6305 w32_display_monitor_attributes_list (void)
6307 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
6308 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
6309 int i, n_monitors;
6310 HMONITOR *monitors;
6312 if (!(enum_display_monitors_fn && get_monitor_info_fn
6313 && monitor_from_window_fn))
6314 return Qnil;
6316 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
6317 (LPARAM) &monitor_list)
6318 || NILP (monitor_list))
6319 return Qnil;
6321 n_monitors = 0;
6322 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
6323 n_monitors++;
6325 monitors = xmalloc (n_monitors * sizeof (*monitors));
6326 for (i = 0; i < n_monitors; i++)
6328 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
6329 monitor_list = XCDR (monitor_list);
6332 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
6333 FOR_EACH_FRAME (rest, frame)
6335 struct frame *f = XFRAME (frame);
6337 if (FRAME_W32_P (f) && !FRAME_TOOLTIP_P (f))
6339 HMONITOR monitor =
6340 monitor_from_window_fn (FRAME_W32_WINDOW (f),
6341 MONITOR_DEFAULT_TO_NEAREST);
6343 for (i = 0; i < n_monitors; i++)
6344 if (monitors[i] == monitor)
6345 break;
6347 if (i < n_monitors)
6348 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
6352 for (i = 0; i < n_monitors; i++)
6354 Lisp_Object geometry, workarea, name, attributes = Qnil;
6355 HDC hdc;
6356 int width_mm, height_mm;
6357 struct MONITOR_INFO_EX mi;
6359 mi.cbSize = sizeof (mi);
6360 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
6361 continue;
6363 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
6364 if (hdc == NULL)
6365 continue;
6366 width_mm = GetDeviceCaps (hdc, HORZSIZE);
6367 height_mm = GetDeviceCaps (hdc, VERTSIZE);
6368 DeleteDC (hdc);
6370 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
6371 attributes);
6373 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
6375 attributes = Fcons (Fcons (Qname, name), attributes);
6377 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6378 attributes);
6380 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
6381 mi.rcWork.right - mi.rcWork.left,
6382 mi.rcWork.bottom - mi.rcWork.top);
6383 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6385 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
6386 mi.rcMonitor.right - mi.rcMonitor.left,
6387 mi.rcMonitor.bottom - mi.rcMonitor.top);
6388 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6390 if (mi.dwFlags & MONITORINFOF_PRIMARY)
6391 primary_monitor_attributes = attributes;
6392 else
6393 attributes_list = Fcons (attributes, attributes_list);
6396 if (!NILP (primary_monitor_attributes))
6397 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
6399 xfree (monitors);
6401 return attributes_list;
6404 static Lisp_Object
6405 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
6407 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
6408 HDC hdc;
6409 double mm_per_pixel;
6410 int pixel_width, pixel_height, width_mm, height_mm;
6411 RECT workarea_rect;
6413 /* Fallback: treat (possibly) multiple physical monitors as if they
6414 formed a single monitor as a whole. This should provide a
6415 consistent result at least on single monitor environments. */
6416 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
6417 attributes);
6419 frames = Qnil;
6420 FOR_EACH_FRAME (rest, frame)
6422 struct frame *f = XFRAME (frame);
6424 if (FRAME_W32_P (f) && !FRAME_TOOLTIP_P (f))
6425 frames = Fcons (frame, frames);
6427 attributes = Fcons (Fcons (Qframes, frames), attributes);
6429 pixel_width = x_display_pixel_width (dpyinfo);
6430 pixel_height = x_display_pixel_height (dpyinfo);
6432 hdc = GetDC (NULL);
6433 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6434 / GetDeviceCaps (hdc, HORZRES));
6435 width_mm = pixel_width * mm_per_pixel + 0.5;
6436 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6437 / GetDeviceCaps (hdc, VERTRES));
6438 height_mm = pixel_height * mm_per_pixel + 0.5;
6439 ReleaseDC (NULL, hdc);
6440 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6441 attributes);
6443 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
6444 we don't care. */
6445 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
6446 GetSystemMetrics (SM_YVIRTUALSCREEN),
6447 pixel_width, pixel_height);
6448 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
6449 workarea = list4i (workarea_rect.left, workarea_rect.top,
6450 workarea_rect.right - workarea_rect.left,
6451 workarea_rect.bottom - workarea_rect.top);
6452 else
6453 workarea = geometry;
6454 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6456 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6458 return list1 (attributes);
6461 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
6462 Sw32_display_monitor_attributes_list,
6463 0, 1, 0,
6464 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
6466 The optional argument DISPLAY specifies which display to ask about.
6467 DISPLAY should be either a frame or a display name (a string).
6468 If omitted or nil, that stands for the selected frame's display.
6470 Internal use only, use `display-monitor-attributes-list' instead. */)
6471 (Lisp_Object display)
6473 struct w32_display_info *dpyinfo = check_x_display_info (display);
6474 Lisp_Object attributes_list;
6476 block_input ();
6477 attributes_list = w32_display_monitor_attributes_list ();
6478 if (NILP (attributes_list))
6479 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
6480 unblock_input ();
6482 return attributes_list;
6485 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
6486 doc: /* Set the sound generated when the bell is rung.
6487 SOUND is `asterisk', `exclamation', `hand', `question', `ok', or `silent'
6488 to use the corresponding system sound for the bell. The `silent' sound
6489 prevents Emacs from making any sound at all.
6490 SOUND is nil to use the normal beep. */)
6491 (Lisp_Object sound)
6493 CHECK_SYMBOL (sound);
6495 if (NILP (sound))
6496 sound_type = 0xFFFFFFFF;
6497 else if (EQ (sound, intern ("asterisk")))
6498 sound_type = MB_ICONASTERISK;
6499 else if (EQ (sound, intern ("exclamation")))
6500 sound_type = MB_ICONEXCLAMATION;
6501 else if (EQ (sound, intern ("hand")))
6502 sound_type = MB_ICONHAND;
6503 else if (EQ (sound, intern ("question")))
6504 sound_type = MB_ICONQUESTION;
6505 else if (EQ (sound, intern ("ok")))
6506 sound_type = MB_OK;
6507 else if (EQ (sound, intern ("silent")))
6508 sound_type = MB_EMACS_SILENT;
6509 else
6510 sound_type = 0xFFFFFFFF;
6512 return sound;
6515 #if 0 /* unused */
6517 x_screen_planes (register struct frame *f)
6519 return FRAME_DISPLAY_INFO (f)->n_planes;
6521 #endif
6523 /* Return the display structure for the display named NAME.
6524 Open a new connection if necessary. */
6526 struct w32_display_info *
6527 x_display_info_for_name (Lisp_Object name)
6529 struct w32_display_info *dpyinfo;
6531 CHECK_STRING (name);
6533 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
6534 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
6535 return dpyinfo;
6537 /* Use this general default value to start with. */
6538 Vx_resource_name = Vinvocation_name;
6540 validate_x_resource_name ();
6542 dpyinfo = w32_term_init (name, NULL, SSDATA (Vx_resource_name));
6544 if (dpyinfo == 0)
6545 error ("Cannot connect to server %s", SDATA (name));
6547 XSETFASTINT (Vwindow_system_version, w32_major_version);
6549 return dpyinfo;
6552 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6553 1, 3, 0, doc: /* SKIP: real doc in xfns.c. */)
6554 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
6556 char *xrm_option;
6557 struct w32_display_info *dpyinfo;
6559 CHECK_STRING (display);
6561 /* Signal an error in order to encourage correct use from callers.
6562 * If we ever support multiple window systems in the same Emacs,
6563 * we'll need callers to be precise about what window system they
6564 * want. */
6566 if (strcmp (SSDATA (display), "w32") != 0)
6567 error ("The name of the display in this Emacs must be \"w32\"");
6569 /* If initialization has already been done, return now to avoid
6570 overwriting critical parts of one_w32_display_info. */
6571 if (window_system_available (NULL))
6572 return Qnil;
6574 if (! NILP (xrm_string))
6575 CHECK_STRING (xrm_string);
6577 /* Allow color mapping to be defined externally; first look in user's
6578 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6580 Lisp_Object color_file;
6582 color_file = build_string ("~/rgb.txt");
6584 if (NILP (Ffile_readable_p (color_file)))
6585 color_file =
6586 Fexpand_file_name (build_string ("rgb.txt"),
6587 Fsymbol_value (intern ("data-directory")));
6589 Vw32_color_map = Fx_load_color_file (color_file);
6591 if (NILP (Vw32_color_map))
6592 Vw32_color_map = w32_default_color_map ();
6594 /* Merge in system logical colors. */
6595 add_system_logical_colors_to_map (&Vw32_color_map);
6597 if (! NILP (xrm_string))
6598 xrm_option = SSDATA (xrm_string);
6599 else
6600 xrm_option = NULL;
6602 /* Use this general default value to start with. */
6603 /* First remove .exe suffix from invocation-name - it looks ugly. */
6605 char basename[ MAX_PATH ], *str;
6607 lispstpcpy (basename, Vinvocation_name);
6608 str = strrchr (basename, '.');
6609 if (str) *str = 0;
6610 Vinvocation_name = build_string (basename);
6612 Vx_resource_name = Vinvocation_name;
6614 validate_x_resource_name ();
6616 /* This is what opens the connection and sets x_current_display.
6617 This also initializes many symbols, such as those used for input. */
6618 dpyinfo = w32_term_init (display, xrm_option, SSDATA (Vx_resource_name));
6620 if (dpyinfo == 0)
6622 if (!NILP (must_succeed))
6623 fatal ("Cannot connect to server %s.\n",
6624 SDATA (display));
6625 else
6626 error ("Cannot connect to server %s", SDATA (display));
6629 XSETFASTINT (Vwindow_system_version, w32_major_version);
6630 return Qnil;
6633 DEFUN ("x-close-connection", Fx_close_connection,
6634 Sx_close_connection, 1, 1, 0,
6635 doc: /* SKIP: real doc in xfns.c. */)
6636 (Lisp_Object display)
6638 struct w32_display_info *dpyinfo = check_x_display_info (display);
6640 if (dpyinfo->reference_count > 0)
6641 error ("Display still has frames on it");
6643 block_input ();
6644 x_destroy_all_bitmaps (dpyinfo);
6646 x_delete_display (dpyinfo);
6647 unblock_input ();
6649 return Qnil;
6652 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6653 doc: /* SKIP: real doc in xfns.c. */)
6654 (void)
6656 Lisp_Object result = Qnil;
6657 struct w32_display_info *wdi;
6659 for (wdi = x_display_list; wdi; wdi = wdi->next)
6660 result = Fcons (XCAR (wdi->name_list_element), result);
6662 return result;
6665 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6666 doc: /* SKIP: real doc in xfns.c. */)
6667 (Lisp_Object on, Lisp_Object display)
6669 return Qnil;
6674 /***********************************************************************
6675 Window properties
6676 ***********************************************************************/
6678 #if 0 /* TODO : port window properties to W32 */
6680 DEFUN ("x-change-window-property", Fx_change_window_property,
6681 Sx_change_window_property, 2, 6, 0,
6682 doc: /* SKIP: real doc in xfns.c. */)
6683 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6684 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6686 struct frame *f = decode_window_system_frame (frame);
6687 Atom prop_atom;
6689 CHECK_STRING (prop);
6690 CHECK_STRING (value);
6692 block_input ();
6693 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6694 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6695 prop_atom, XA_STRING, 8, PropModeReplace,
6696 SDATA (value), SCHARS (value));
6698 /* Make sure the property is set when we return. */
6699 XFlush (FRAME_W32_DISPLAY (f));
6700 unblock_input ();
6702 return value;
6706 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6707 Sx_delete_window_property, 1, 2, 0,
6708 doc: /* SKIP: real doc in xfns.c. */)
6709 (Lisp_Object prop, Lisp_Object frame)
6711 struct frame *f = decode_window_system_frame (frame);
6712 Atom prop_atom;
6714 CHECK_STRING (prop);
6715 block_input ();
6716 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6717 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6719 /* Make sure the property is removed when we return. */
6720 XFlush (FRAME_W32_DISPLAY (f));
6721 unblock_input ();
6723 return prop;
6727 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6728 1, 6, 0,
6729 doc: /* SKIP: real doc in xfns.c. */)
6730 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6731 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6733 struct frame *f = decode_window_system_frame (frame);
6734 Atom prop_atom;
6735 int rc;
6736 Lisp_Object prop_value = Qnil;
6737 char *tmp_data = NULL;
6738 Atom actual_type;
6739 int actual_format;
6740 unsigned long actual_size, bytes_remaining;
6742 CHECK_STRING (prop);
6743 block_input ();
6744 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6745 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6746 prop_atom, 0, 0, False, XA_STRING,
6747 &actual_type, &actual_format, &actual_size,
6748 &bytes_remaining, (unsigned char **) &tmp_data);
6749 if (rc == Success)
6751 int size = bytes_remaining;
6753 XFree (tmp_data);
6754 tmp_data = NULL;
6756 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6757 prop_atom, 0, bytes_remaining,
6758 False, XA_STRING,
6759 &actual_type, &actual_format,
6760 &actual_size, &bytes_remaining,
6761 (unsigned char **) &tmp_data);
6762 if (rc == Success)
6763 prop_value = make_string (tmp_data, size);
6765 XFree (tmp_data);
6768 unblock_input ();
6770 return prop_value;
6772 return Qnil;
6775 #endif /* TODO */
6777 /***********************************************************************
6778 Tool tips
6779 ***********************************************************************/
6781 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6782 Lisp_Object, int, int, int *, int *);
6784 /* The frame of the currently visible tooltip. */
6785 Lisp_Object tip_frame;
6787 /* The window-system window corresponding to the frame of the
6788 currently visible tooltip. */
6789 Window tip_window;
6791 /* A timer that hides or deletes the currently visible tooltip when it
6792 fires. */
6793 Lisp_Object tip_timer;
6795 /* STRING argument of last `x-show-tip' call. */
6796 Lisp_Object tip_last_string;
6798 /* Normalized FRAME argument of last `x-show-tip' call. */
6799 Lisp_Object tip_last_frame;
6801 /* PARMS argument of last `x-show-tip' call. */
6802 Lisp_Object tip_last_parms;
6805 static void
6806 unwind_create_tip_frame (Lisp_Object frame)
6808 Lisp_Object deleted;
6810 deleted = unwind_create_frame (frame);
6811 if (EQ (deleted, Qt))
6813 tip_window = NULL;
6814 tip_frame = Qnil;
6819 /* Create a frame for a tooltip on the display described by DPYINFO.
6820 PARMS is a list of frame parameters. Value is the frame.
6822 Note that functions called here, esp. x_default_parameter can
6823 signal errors, for instance when a specified color name is
6824 undefined. We have to make sure that we're in a consistent state
6825 when this happens. */
6827 static Lisp_Object
6828 x_create_tip_frame (struct w32_display_info *dpyinfo, Lisp_Object parms)
6830 struct frame *f;
6831 Lisp_Object frame;
6832 Lisp_Object name;
6833 int width, height;
6834 ptrdiff_t count = SPECPDL_INDEX ();
6835 struct kboard *kb;
6836 bool face_change_before = face_change;
6837 int x_width = 0, x_height = 0;
6839 /* Use this general default value to start with until we know if
6840 this frame has a specified name. */
6841 Vx_resource_name = Vinvocation_name;
6843 kb = dpyinfo->terminal->kboard;
6845 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6846 avoid destructive changes behind our caller's back. */
6847 parms = Fcopy_alist (parms);
6849 /* Get the name of the frame to use for resource lookup. */
6850 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6851 if (!STRINGP (name)
6852 && !EQ (name, Qunbound)
6853 && !NILP (name))
6854 error ("Invalid frame name--not a string or nil");
6855 Vx_resource_name = name;
6857 frame = Qnil;
6858 /* Make a frame without minibuffer nor mode-line. */
6859 f = make_frame (false);
6860 f->wants_modeline = false;
6861 XSETFRAME (frame, f);
6863 record_unwind_protect (unwind_create_tip_frame, frame);
6865 /* By setting the output method, we're essentially saying that
6866 the frame is live, as per FRAME_LIVE_P. If we get a signal
6867 from this point on, x_destroy_window might screw up reference
6868 counts etc. */
6869 f->terminal = dpyinfo->terminal;
6870 f->output_method = output_w32;
6871 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6873 FRAME_FONTSET (f) = -1;
6874 fset_icon_name (f, Qnil);
6875 f->tooltip = true;
6877 #ifdef GLYPH_DEBUG
6878 image_cache_refcount =
6879 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6880 dpyinfo_refcount = dpyinfo->reference_count;
6881 #endif /* GLYPH_DEBUG */
6882 FRAME_KBOARD (f) = kb;
6884 /* Set the name; the functions to which we pass f expect the name to
6885 be set. */
6886 if (EQ (name, Qunbound) || NILP (name))
6888 fset_name (f, build_string (dpyinfo->w32_id_name));
6889 f->explicit_name = false;
6891 else
6893 fset_name (f, name);
6894 f->explicit_name = true;
6895 /* Use the frame's title when getting resources for this frame. */
6896 specbind (Qx_resource_name, name);
6899 if (uniscribe_available)
6900 register_font_driver (&uniscribe_font_driver, f);
6901 register_font_driver (&w32font_driver, f);
6903 x_default_parameter (f, parms, Qfont_backend, Qnil,
6904 "fontBackend", "FontBackend", RES_TYPE_STRING);
6906 /* Extract the window parameters from the supplied values
6907 that are needed to determine window geometry. */
6908 x_default_font_parameter (f, parms);
6910 x_default_parameter (f, parms, Qborder_width, make_number (2),
6911 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6912 /* This defaults to 2 in order to match xterm. We recognize either
6913 internalBorderWidth or internalBorder (which is what xterm calls
6914 it). */
6915 if (NILP (Fassq (Qinternal_border_width, parms)))
6917 Lisp_Object value;
6919 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6920 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
6921 if (! EQ (value, Qunbound))
6922 parms = Fcons (Fcons (Qinternal_border_width, value),
6923 parms);
6926 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6927 "internalBorderWidth", "internalBorderWidth",
6928 RES_TYPE_NUMBER);
6929 /* Also do the stuff which must be set before the window exists. */
6930 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6931 "foreground", "Foreground", RES_TYPE_STRING);
6932 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6933 "background", "Background", RES_TYPE_STRING);
6934 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6935 "pointerColor", "Foreground", RES_TYPE_STRING);
6936 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6937 "cursorColor", "Foreground", RES_TYPE_STRING);
6938 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6939 "borderColor", "BorderColor", RES_TYPE_STRING);
6940 x_default_parameter (f, parms, Qno_special_glyphs, Qt,
6941 NULL, NULL, RES_TYPE_BOOLEAN);
6943 /* Init faces before x_default_parameter is called for the
6944 scroll-bar-width parameter because otherwise we end up in
6945 init_iterator with a null face cache, which should not happen. */
6946 init_frame_faces (f);
6948 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6949 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6950 f->output_data.w32->explicit_parent = false;
6952 x_figure_window_size (f, parms, true, &x_width, &x_height);
6954 /* No fringes on tip frame. */
6955 f->fringe_cols = 0;
6956 f->left_fringe_width = 0;
6957 f->right_fringe_width = 0;
6958 /* No dividers on tip frame. */
6959 f->right_divider_width = 0;
6960 f->bottom_divider_width = 0;
6962 block_input ();
6963 my_create_tip_window (f);
6964 unblock_input ();
6966 x_make_gc (f);
6968 x_default_parameter (f, parms, Qauto_raise, Qnil,
6969 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6970 x_default_parameter (f, parms, Qauto_lower, Qnil,
6971 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6972 x_default_parameter (f, parms, Qcursor_type, Qbox,
6973 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6974 /* Process alpha here (Bug#17344). */
6975 x_default_parameter (f, parms, Qalpha, Qnil,
6976 "alpha", "Alpha", RES_TYPE_NUMBER);
6978 /* Dimensions, especially FRAME_LINES (f), must be done via
6979 change_frame_size. Change will not be effected unless different
6980 from the current FRAME_LINES (f). */
6981 width = FRAME_COLS (f);
6982 height = FRAME_LINES (f);
6983 SET_FRAME_COLS (f, 0);
6984 SET_FRAME_LINES (f, 0);
6985 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
6986 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
6987 /* Add `tooltip' frame parameter's default value. */
6988 if (NILP (Fframe_parameter (frame, Qtooltip)))
6989 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
6991 /* Set up faces after all frame parameters are known. This call
6992 also merges in face attributes specified for new frames.
6994 Frame parameters may be changed if .Xdefaults contains
6995 specifications for the default font. For example, if there is an
6996 `Emacs.default.attributeBackground: pink', the `background-color'
6997 attribute of the frame get's set, which let's the internal border
6998 of the tooltip frame appear in pink. Prevent this. */
7000 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
7001 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
7002 Lisp_Object colors = Qnil;
7004 call2 (Qface_set_after_frame_default, frame, Qnil);
7006 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
7007 colors = Fcons (Fcons (Qbackground_color, bg), colors);
7008 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
7009 colors = Fcons (Fcons (Qforeground_color, fg), colors);
7011 if (!NILP (colors))
7012 Fmodify_frame_parameters (frame, colors);
7015 f->no_split = true;
7017 /* Now that the frame is official, it counts as a reference to
7018 its display. */
7019 FRAME_DISPLAY_INFO (f)->reference_count++;
7020 f->terminal->reference_count++;
7022 /* It is now ok to make the frame official even if we get an error
7023 below. And the frame needs to be on Vframe_list or making it
7024 visible won't work. */
7025 Vframe_list = Fcons (frame, Vframe_list);
7026 f->can_x_set_window_size = true;
7028 /* Setting attributes of faces of the tooltip frame from resources
7029 and similar will set face_change, which leads to the
7030 clearing of all current matrices. Since this isn't necessary
7031 here, avoid it by resetting face_change to the value it
7032 had before we created the tip frame. */
7033 face_change = face_change_before;
7035 /* Discard the unwind_protect. */
7036 return unbind_to (count, frame);
7040 /* Compute where to display tip frame F. PARMS is the list of frame
7041 parameters for F. DX and DY are specified offsets from the current
7042 location of the mouse. WIDTH and HEIGHT are the width and height
7043 of the tooltip. Return coordinates relative to the root window of
7044 the display in *ROOT_X and *ROOT_Y. */
7046 static void
7047 compute_tip_xy (struct frame *f,
7048 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
7049 int width, int height, int *root_x, int *root_y)
7051 Lisp_Object left, top, right, bottom;
7052 int min_x = 0, min_y = 0, max_x = 0, max_y = 0;
7054 /* User-specified position? */
7055 left = Fcdr (Fassq (Qleft, parms));
7056 top = Fcdr (Fassq (Qtop, parms));
7057 right = Fcdr (Fassq (Qright, parms));
7058 bottom = Fcdr (Fassq (Qbottom, parms));
7060 /* Move the tooltip window where the mouse pointer is. Resize and
7061 show it. */
7062 if ((!INTEGERP (left) && !INTEGERP (right))
7063 || (!INTEGERP (top) && !INTEGERP (bottom)))
7065 POINT pt;
7067 /* Default min and max values. */
7068 min_x = 0;
7069 min_y = 0;
7070 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
7071 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
7073 block_input ();
7074 GetCursorPos (&pt);
7075 *root_x = pt.x;
7076 *root_y = pt.y;
7077 unblock_input ();
7079 /* If multiple monitor support is available, constrain the tip onto
7080 the current monitor. This improves the above by allowing negative
7081 co-ordinates if monitor positions are such that they are valid, and
7082 snaps a tooltip onto a single monitor if we are close to the edge
7083 where it would otherwise flow onto the other monitor (or into
7084 nothingness if there is a gap in the overlap). */
7085 if (monitor_from_point_fn && get_monitor_info_fn)
7087 struct MONITOR_INFO info;
7088 HMONITOR monitor
7089 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
7090 info.cbSize = sizeof (info);
7092 if (get_monitor_info_fn (monitor, &info))
7094 min_x = info.rcWork.left;
7095 min_y = info.rcWork.top;
7096 max_x = info.rcWork.right;
7097 max_y = info.rcWork.bottom;
7102 if (INTEGERP (top))
7103 *root_y = XINT (top);
7104 else if (INTEGERP (bottom))
7105 *root_y = XINT (bottom) - height;
7106 else if (*root_y + XINT (dy) <= min_y)
7107 *root_y = min_y; /* Can happen for negative dy */
7108 else if (*root_y + XINT (dy) + height <= max_y)
7109 /* It fits below the pointer */
7110 *root_y += XINT (dy);
7111 else if (height + XINT (dy) + min_y <= *root_y)
7112 /* It fits above the pointer. */
7113 *root_y -= height + XINT (dy);
7114 else
7115 /* Put it on the top. */
7116 *root_y = min_y;
7118 if (INTEGERP (left))
7119 *root_x = XINT (left);
7120 else if (INTEGERP (right))
7121 *root_x = XINT (right) - width;
7122 else if (*root_x + XINT (dx) <= min_x)
7123 *root_x = 0; /* Can happen for negative dx */
7124 else if (*root_x + XINT (dx) + width <= max_x)
7125 /* It fits to the right of the pointer. */
7126 *root_x += XINT (dx);
7127 else if (width + XINT (dx) + min_x <= *root_x)
7128 /* It fits to the left of the pointer. */
7129 *root_x -= width + XINT (dx);
7130 else
7131 /* Put it left justified on the screen -- it ought to fit that way. */
7132 *root_x = min_x;
7136 * x_hide_tip:
7138 * Hide currently visible tooltip and cancel its timer.
7140 * This will try to make tooltip_frame invisible (if DELETE is false)
7141 * or delete tooltip_frame (if DELETE is true).
7143 * Return Qt if the tooltip was either deleted or made invisible, Qnil
7144 * otherwise.
7146 static Lisp_Object
7147 x_hide_tip (bool delete)
7149 if (!NILP (tip_timer))
7151 call1 (Qcancel_timer, tip_timer);
7152 tip_timer = Qnil;
7155 if (NILP (tip_frame)
7156 || (!delete && FRAMEP (tip_frame)
7157 && !FRAME_VISIBLE_P (XFRAME (tip_frame))))
7158 return Qnil;
7159 else
7161 ptrdiff_t count;
7162 Lisp_Object was_open = Qnil;
7164 count = SPECPDL_INDEX ();
7165 specbind (Qinhibit_redisplay, Qt);
7166 specbind (Qinhibit_quit, Qt);
7168 if (FRAMEP (tip_frame))
7170 if (FRAME_LIVE_P (XFRAME (tip_frame)))
7172 if (delete)
7174 delete_frame (tip_frame, Qnil);
7175 tip_frame = Qnil;
7177 else
7178 x_make_frame_invisible (XFRAME (tip_frame));
7180 was_open = Qt;
7182 else
7183 tip_frame = Qnil;
7185 else
7186 tip_frame = Qnil;
7188 return unbind_to (count, was_open);
7193 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
7194 doc: /* SKIP: real doc in xfns.c. */)
7195 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms,
7196 Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
7198 struct frame *tip_f;
7199 struct window *w;
7200 int root_x, root_y;
7201 struct buffer *old_buffer;
7202 struct text_pos pos;
7203 int width, height;
7204 int old_windows_or_buffers_changed = windows_or_buffers_changed;
7205 ptrdiff_t count = SPECPDL_INDEX ();
7206 ptrdiff_t count_1;
7207 Lisp_Object window, size, tip_buf;
7208 AUTO_STRING (tip, " *tip*");
7210 specbind (Qinhibit_redisplay, Qt);
7212 CHECK_STRING (string);
7214 if (NILP (frame))
7215 frame = selected_frame;
7216 decode_window_system_frame (frame);
7218 if (NILP (timeout))
7219 timeout = make_number (5);
7220 else
7221 CHECK_NATNUM (timeout);
7223 if (NILP (dx))
7224 dx = make_number (5);
7225 else
7226 CHECK_NUMBER (dx);
7228 if (NILP (dy))
7229 dy = make_number (-10);
7230 else
7231 CHECK_NUMBER (dy);
7233 if (FRAMEP (tip_frame) && FRAME_LIVE_P (XFRAME (tip_frame)))
7235 if (FRAME_VISIBLE_P (XFRAME (tip_frame))
7236 && EQ (frame, tip_last_frame)
7237 && !NILP (Fequal_including_properties (string, tip_last_string))
7238 && !NILP (Fequal (parms, tip_last_parms)))
7240 /* Only DX and DY have changed. */
7241 tip_f = XFRAME (tip_frame);
7242 if (!NILP (tip_timer))
7244 Lisp_Object timer = tip_timer;
7246 tip_timer = Qnil;
7247 call1 (Qcancel_timer, timer);
7250 block_input ();
7251 compute_tip_xy (tip_f, parms, dx, dy, FRAME_PIXEL_WIDTH (tip_f),
7252 FRAME_PIXEL_HEIGHT (tip_f), &root_x, &root_y);
7254 /* Put tooltip in topmost group and in position. */
7255 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7256 root_x, root_y, 0, 0,
7257 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7259 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7260 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7261 0, 0, 0, 0,
7262 SWP_NOMOVE | SWP_NOSIZE
7263 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7265 /* Let redisplay know that we have made the frame visible already. */
7266 SET_FRAME_VISIBLE (tip_f, 1);
7267 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7268 unblock_input ();
7270 goto start_timer;
7272 else if (tooltip_reuse_hidden_frame && EQ (frame, tip_last_frame))
7274 bool delete = false;
7275 Lisp_Object tail, elt, parm, last;
7277 /* Check if every parameter in PARMS has the same value in
7278 tip_last_parms. This may destruct tip_last_parms
7279 which, however, will be recreated below. */
7280 for (tail = parms; CONSP (tail); tail = XCDR (tail))
7282 elt = XCAR (tail);
7283 parm = Fcar (elt);
7284 /* The left, top, right and bottom parameters are handled
7285 by compute_tip_xy so they can be ignored here. */
7286 if (!EQ (parm, Qleft) && !EQ (parm, Qtop)
7287 && !EQ (parm, Qright) && !EQ (parm, Qbottom))
7289 last = Fassq (parm, tip_last_parms);
7290 if (NILP (Fequal (Fcdr (elt), Fcdr (last))))
7292 /* We lost, delete the old tooltip. */
7293 delete = true;
7294 break;
7296 else
7297 tip_last_parms =
7298 call2 (Qassq_delete_all, parm, tip_last_parms);
7300 else
7301 tip_last_parms =
7302 call2 (Qassq_delete_all, parm, tip_last_parms);
7305 /* Now check if there's a parameter left in tip_last_parms with a
7306 non-nil value. */
7307 for (tail = tip_last_parms; CONSP (tail); tail = XCDR (tail))
7309 elt = XCAR (tail);
7310 parm = Fcar (elt);
7311 if (!EQ (parm, Qleft) && !EQ (parm, Qtop) && !EQ (parm, Qright)
7312 && !EQ (parm, Qbottom) && !NILP (Fcdr (elt)))
7314 /* We lost, delete the old tooltip. */
7315 delete = true;
7316 break;
7320 x_hide_tip (delete);
7322 else
7323 x_hide_tip (true);
7325 else
7326 x_hide_tip (true);
7328 tip_last_frame = frame;
7329 tip_last_string = string;
7330 tip_last_parms = parms;
7332 /* Block input until the tip has been fully drawn, to avoid crashes
7333 when drawing tips in menus. */
7334 block_input ();
7336 if (!FRAMEP (tip_frame) || !FRAME_LIVE_P (XFRAME (tip_frame)))
7338 /* Add default values to frame parameters. */
7339 if (NILP (Fassq (Qname, parms)))
7340 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7341 if (NILP (Fassq (Qinternal_border_width, parms)))
7342 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7343 if (NILP (Fassq (Qborder_width, parms)))
7344 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7345 if (NILP (Fassq (Qborder_color, parms)))
7346 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")),
7347 parms);
7348 if (NILP (Fassq (Qbackground_color, parms)))
7349 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7350 parms);
7352 /* Create a frame for the tooltip and record it in the global
7353 variable tip_frame. */
7354 struct frame *f; /* The value is unused. */
7355 if (NILP (tip_frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms)))
7357 /* Creating the tip frame failed. */
7358 unblock_input ();
7359 return unbind_to (count, Qnil);
7363 tip_f = XFRAME (tip_frame);
7364 window = FRAME_ROOT_WINDOW (tip_f);
7365 tip_buf = Fget_buffer_create (tip);
7366 /* We will mark the tip window a "pseudo-window" below, and such
7367 windows cannot have display margins. */
7368 bset_left_margin_cols (XBUFFER (tip_buf), make_number (0));
7369 bset_right_margin_cols (XBUFFER (tip_buf), make_number (0));
7370 set_window_buffer (window, tip_buf, false, false);
7371 w = XWINDOW (window);
7372 w->pseudo_window_p = true;
7374 /* Set up the frame's root window. Note: The following code does not
7375 try to size the window or its frame correctly. Its only purpose is
7376 to make the subsequent text size calculations work. The right
7377 sizes should get installed when the toolkit gets back to us. */
7378 w->left_col = 0;
7379 w->top_line = 0;
7380 w->pixel_left = 0;
7381 w->pixel_top = 0;
7383 if (CONSP (Vx_max_tooltip_size)
7384 && RANGED_INTEGERP (1, XCAR (Vx_max_tooltip_size), INT_MAX)
7385 && RANGED_INTEGERP (1, XCDR (Vx_max_tooltip_size), INT_MAX))
7387 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
7388 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
7390 else
7392 w->total_cols = 80;
7393 w->total_lines = 40;
7396 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (tip_f);
7397 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (tip_f);
7398 FRAME_TOTAL_COLS (tip_f) = WINDOW_TOTAL_COLS (w);
7399 adjust_frame_glyphs (tip_f);
7401 /* Insert STRING into the root window's buffer and fit the frame to
7402 the buffer. */
7403 count_1 = SPECPDL_INDEX ();
7404 old_buffer = current_buffer;
7405 set_buffer_internal_1 (XBUFFER (w->contents));
7406 bset_truncate_lines (current_buffer, Qnil);
7407 specbind (Qinhibit_read_only, Qt);
7408 specbind (Qinhibit_modification_hooks, Qt);
7409 specbind (Qinhibit_point_motion_hooks, Qt);
7410 Ferase_buffer ();
7411 Finsert (1, &string);
7412 clear_glyph_matrix (w->desired_matrix);
7413 clear_glyph_matrix (w->current_matrix);
7414 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7415 try_window (window, pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
7416 /* Calculate size of tooltip window. */
7417 size = Fwindow_text_pixel_size (window, Qnil, Qnil, Qnil,
7418 make_number (w->pixel_height), Qnil);
7419 /* Add the frame's internal border to calculated size. */
7420 width = XINT (Fcar (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7421 height = XINT (Fcdr (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7422 /* Calculate position of tooltip frame. */
7423 compute_tip_xy (tip_f, parms, dx, dy, width, height, &root_x, &root_y);
7425 /* Show tooltip frame. */
7427 RECT rect;
7428 int pad = (NUMBERP (Vw32_tooltip_extra_pixels)
7429 ? max (0, XINT (Vw32_tooltip_extra_pixels))
7430 : FRAME_COLUMN_WIDTH (tip_f));
7432 rect.left = rect.top = 0;
7433 rect.right = width;
7434 rect.bottom = height;
7435 AdjustWindowRect (&rect, tip_f->output_data.w32->dwStyle,
7436 FRAME_EXTERNAL_MENU_BAR (tip_f));
7438 /* Position and size tooltip and put it in the topmost group. */
7439 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7440 root_x, root_y,
7441 rect.right - rect.left + pad,
7442 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7444 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7445 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7446 0, 0, 0, 0,
7447 SWP_NOMOVE | SWP_NOSIZE
7448 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7450 /* Let redisplay know that we have made the frame visible already. */
7451 SET_FRAME_VISIBLE (tip_f, 1);
7453 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7456 w->must_be_updated_p = true;
7457 update_single_window (w);
7458 set_buffer_internal_1 (old_buffer);
7459 unbind_to (count_1, Qnil);
7460 unblock_input ();
7461 windows_or_buffers_changed = old_windows_or_buffers_changed;
7463 start_timer:
7464 /* Let the tip disappear after timeout seconds. */
7465 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7466 intern ("x-hide-tip"));
7468 return unbind_to (count, Qnil);
7472 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7473 doc: /* SKIP: real doc in xfns.c. */)
7474 (void)
7476 return x_hide_tip (!tooltip_reuse_hidden_frame);
7479 /***********************************************************************
7480 File selection dialog
7481 ***********************************************************************/
7483 #define FILE_NAME_TEXT_FIELD edt1
7484 #define FILE_NAME_COMBO_BOX cmb13
7485 #define FILE_NAME_LIST lst1
7487 /* Callback for altering the behavior of the Open File dialog.
7488 Makes the Filename text field contain "Current Directory" and be
7489 read-only when "Directories" is selected in the filter. This
7490 allows us to work around the fact that the standard Open File
7491 dialog does not support directories. */
7492 static UINT_PTR CALLBACK
7493 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
7495 if (msg == WM_NOTIFY)
7497 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
7498 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
7499 int dropdown_changed;
7500 int dir_index;
7501 #ifdef NTGUI_UNICODE
7502 const int use_unicode = 1;
7503 #else /* !NTGUI_UNICODE */
7504 int use_unicode = w32_unicode_filenames;
7505 #endif /* NTGUI_UNICODE */
7507 /* Detect when the Filter dropdown is changed. */
7508 if (use_unicode)
7509 dropdown_changed =
7510 notify_w->hdr.code == CDN_TYPECHANGE
7511 || notify_w->hdr.code == CDN_INITDONE;
7512 else
7513 dropdown_changed =
7514 notify_a->hdr.code == CDN_TYPECHANGE
7515 || notify_a->hdr.code == CDN_INITDONE;
7516 if (dropdown_changed)
7518 HWND dialog = GetParent (hwnd);
7519 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7520 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
7521 int hdr_code;
7523 /* At least on Windows 7, the above attempt to get the window handle
7524 to the File Name Text Field fails. The following code does the
7525 job though. Note that this code is based on my examination of the
7526 window hierarchy using Microsoft Spy++. bk */
7527 if (edit_control == NULL)
7529 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
7530 if (tmp)
7532 tmp = GetWindow (tmp, GW_CHILD);
7533 if (tmp)
7534 edit_control = GetWindow (tmp, GW_CHILD);
7538 /* Directories is in index 2. */
7539 if (use_unicode)
7541 dir_index = notify_w->lpOFN->nFilterIndex;
7542 hdr_code = notify_w->hdr.code;
7544 else
7546 dir_index = notify_a->lpOFN->nFilterIndex;
7547 hdr_code = notify_a->hdr.code;
7549 if (dir_index == 2)
7551 if (use_unicode)
7552 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7553 (LPARAM)L"Current Directory");
7554 else
7555 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7556 (LPARAM)"Current Directory");
7557 EnableWindow (edit_control, FALSE);
7558 /* Note that at least on Windows 7, the above call to EnableWindow
7559 disables the window that would ordinarily have focus. If we
7560 do not set focus to some other window here, focus will land in
7561 no man's land and the user will be unable to tab through the
7562 dialog box (pressing tab will only result in a beep).
7563 Avoid that problem by setting focus to the list here. */
7564 if (hdr_code == CDN_INITDONE)
7565 SetFocus (list);
7567 else
7569 /* Don't override default filename on init done. */
7570 if (hdr_code == CDN_TYPECHANGE)
7572 if (use_unicode)
7573 SendMessageW (dialog, CDM_SETCONTROLTEXT,
7574 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
7575 else
7576 SendMessageA (dialog, CDM_SETCONTROLTEXT,
7577 FILE_NAME_TEXT_FIELD, (LPARAM)"");
7579 EnableWindow (edit_control, TRUE);
7583 return 0;
7586 void
7587 w32_dialog_in_progress (Lisp_Object in_progress)
7589 Lisp_Object frames, frame;
7591 /* Don't let frames in `above' z-group obscure popups. */
7592 FOR_EACH_FRAME (frames, frame)
7594 struct frame *f = XFRAME (frame);
7596 if (!NILP (in_progress) && FRAME_Z_GROUP_ABOVE (f))
7597 x_set_z_group (f, Qabove_suspended, Qabove);
7598 else if (NILP (in_progress) && FRAME_Z_GROUP_ABOVE_SUSPENDED (f))
7599 x_set_z_group (f, Qabove, Qabove_suspended);
7603 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7604 doc: /* SKIP: real doc in xfns.c. */)
7605 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
7607 /* Filter index: 1: All Files, 2: Directories only */
7608 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
7609 #ifndef NTGUI_UNICODE
7610 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
7611 #endif
7613 Lisp_Object filename = default_filename;
7614 struct frame *f = SELECTED_FRAME ();
7615 BOOL file_opened = FALSE;
7616 Lisp_Object orig_dir = dir;
7617 Lisp_Object orig_prompt = prompt;
7619 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
7620 compatibility) we end up with the old file dialogs. Define a big
7621 enough struct for the new dialog to trick GetOpenFileName into
7622 giving us the new dialogs on newer versions of Windows. */
7623 struct {
7624 OPENFILENAMEW details;
7625 #if _WIN32_WINNT < 0x500 /* < win2k */
7626 PVOID pvReserved;
7627 DWORD dwReserved;
7628 DWORD FlagsEx;
7629 #endif /* < win2k */
7630 } new_file_details_w;
7632 #ifdef NTGUI_UNICODE
7633 wchar_t filename_buf_w[32*1024 + 1]; /* NT kernel maximum */
7634 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7635 const int use_unicode = 1;
7636 #else /* not NTGUI_UNICODE */
7637 struct {
7638 OPENFILENAMEA details;
7639 #if _WIN32_WINNT < 0x500 /* < win2k */
7640 PVOID pvReserved;
7641 DWORD dwReserved;
7642 DWORD FlagsEx;
7643 #endif /* < win2k */
7644 } new_file_details_a;
7645 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7646 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7647 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7648 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7649 int use_unicode = w32_unicode_filenames;
7650 wchar_t *prompt_w;
7651 char *prompt_a UNINIT;
7652 int len;
7653 char fname_ret[MAX_UTF8_PATH];
7654 #endif /* NTGUI_UNICODE */
7657 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7658 system file encoding expected by the platform APIs (e.g. Cygwin's
7659 POSIX implementation) may not be the same as the encoding expected
7660 by the Windows "ANSI" APIs! */
7662 CHECK_STRING (prompt);
7663 CHECK_STRING (dir);
7665 dir = Fexpand_file_name (dir, Qnil);
7667 if (STRINGP (filename))
7668 filename = Ffile_name_nondirectory (filename);
7669 else
7670 filename = empty_unibyte_string;
7672 #ifdef CYGWIN
7673 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7674 if (SCHARS (filename) > 0)
7675 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7676 #endif
7678 CHECK_STRING (dir);
7679 CHECK_STRING (filename);
7681 /* The code in file_dialog_callback that attempts to set the text
7682 of the file name edit window when handling the CDN_INITDONE
7683 WM_NOTIFY message does not work. Setting filename to "Current
7684 Directory" in the only_dir_p case here does work however. */
7685 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7686 filename = build_string ("Current Directory");
7688 /* Convert the values we've computed so far to system form. */
7689 #ifdef NTGUI_UNICODE
7690 to_unicode (prompt, &prompt);
7691 to_unicode (dir, &dir);
7692 to_unicode (filename, &filename);
7693 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7694 report_file_error ("filename too long", default_filename);
7696 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7697 #else /* !NTGUI_UNICODE */
7698 prompt = ENCODE_FILE (prompt);
7699 dir = ENCODE_FILE (dir);
7700 filename = ENCODE_FILE (filename);
7702 /* We modify these in-place, so make copies for safety. */
7703 dir = Fcopy_sequence (dir);
7704 unixtodos_filename (SSDATA (dir));
7705 filename = Fcopy_sequence (filename);
7706 unixtodos_filename (SSDATA (filename));
7707 if (SBYTES (filename) >= MAX_UTF8_PATH)
7708 report_file_error ("filename too long", default_filename);
7709 if (w32_unicode_filenames)
7711 filename_to_utf16 (SSDATA (dir), dir_w);
7712 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7714 /* filename_to_utf16 sets errno to ENOENT when the file
7715 name is too long or cannot be converted to UTF-16. */
7716 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7717 report_file_error ("filename too long", default_filename);
7719 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7720 SSDATA (prompt), -1, NULL, 0);
7721 if (len > 32768)
7722 len = 32768;
7723 prompt_w = alloca (len * sizeof (wchar_t));
7724 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7725 SSDATA (prompt), -1, prompt_w, len);
7727 else
7729 filename_to_ansi (SSDATA (dir), dir_a);
7730 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7732 /* filename_to_ansi sets errno to ENOENT when the file
7733 name is too long or cannot be converted to UTF-16. */
7734 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7735 report_file_error ("filename too long", default_filename);
7737 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7738 SSDATA (prompt), -1, NULL, 0);
7739 if (len > 32768)
7740 len = 32768;
7741 prompt_w = alloca (len * sizeof (wchar_t));
7742 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7743 SSDATA (prompt), -1, prompt_w, len);
7744 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7745 if (len > 32768)
7746 len = 32768;
7747 prompt_a = alloca (len);
7748 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7750 #endif /* NTGUI_UNICODE */
7752 /* Fill in the structure for the call to GetOpenFileName below.
7753 For NTGUI_UNICODE builds (which run only on NT), we just use
7754 the actual size of the structure. For non-NTGUI_UNICODE
7755 builds, we tell the OS we're using an old version of the
7756 structure if the OS isn't new enough to support the newer
7757 version. */
7758 if (use_unicode)
7760 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7761 if (w32_major_version > 4 && w32_major_version < 95)
7762 file_details_w->lStructSize = sizeof (new_file_details_w);
7763 else
7764 file_details_w->lStructSize = sizeof (*file_details_w);
7765 /* Set up the inout parameter for the selected file name. */
7766 file_details_w->lpstrFile = filename_buf_w;
7767 file_details_w->nMaxFile =
7768 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7769 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7770 /* Undocumented Bug in Common File Dialog:
7771 If a filter is not specified, shell links are not resolved. */
7772 file_details_w->lpstrFilter = filter_w;
7773 #ifdef NTGUI_UNICODE
7774 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7775 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7776 #else
7777 file_details_w->lpstrInitialDir = dir_w;
7778 file_details_w->lpstrTitle = prompt_w;
7779 #endif
7780 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7781 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7782 | OFN_EXPLORER | OFN_ENABLEHOOK);
7783 if (!NILP (mustmatch))
7785 /* Require that the path to the parent directory exists. */
7786 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7787 /* If we are looking for a file, require that it exists. */
7788 if (NILP (only_dir_p))
7789 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7792 #ifndef NTGUI_UNICODE
7793 else
7795 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7796 if (w32_major_version > 4 && w32_major_version < 95)
7797 file_details_a->lStructSize = sizeof (new_file_details_a);
7798 else
7799 file_details_a->lStructSize = sizeof (*file_details_a);
7800 file_details_a->lpstrFile = filename_buf_a;
7801 file_details_a->nMaxFile =
7802 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7803 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7804 file_details_a->lpstrFilter = filter_a;
7805 file_details_a->lpstrInitialDir = dir_a;
7806 file_details_a->lpstrTitle = prompt_a;
7807 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7808 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7809 | OFN_EXPLORER | OFN_ENABLEHOOK);
7810 if (!NILP (mustmatch))
7812 /* Require that the path to the parent directory exists. */
7813 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7814 /* If we are looking for a file, require that it exists. */
7815 if (NILP (only_dir_p))
7816 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7819 #endif /* !NTGUI_UNICODE */
7822 int count = SPECPDL_INDEX ();
7824 w32_dialog_in_progress (Qt);
7826 /* Prevent redisplay. */
7827 specbind (Qinhibit_redisplay, Qt);
7828 record_unwind_protect (w32_dialog_in_progress, Qnil);
7829 block_input ();
7830 if (use_unicode)
7832 file_details_w->lpfnHook = file_dialog_callback;
7834 file_opened = GetOpenFileNameW (file_details_w);
7836 #ifndef NTGUI_UNICODE
7837 else
7839 file_details_a->lpfnHook = file_dialog_callback;
7841 file_opened = GetOpenFileNameA (file_details_a);
7843 #endif /* !NTGUI_UNICODE */
7844 unblock_input ();
7845 unbind_to (count, Qnil);
7848 if (file_opened)
7850 /* Get an Emacs string from the value Windows gave us. */
7851 #ifdef NTGUI_UNICODE
7852 filename = from_unicode_buffer (filename_buf_w);
7853 #else /* !NTGUI_UNICODE */
7854 if (use_unicode)
7855 filename_from_utf16 (filename_buf_w, fname_ret);
7856 else
7857 filename_from_ansi (filename_buf_a, fname_ret);
7858 dostounix_filename (fname_ret);
7859 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7860 #endif /* NTGUI_UNICODE */
7862 #ifdef CYGWIN
7863 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7864 #endif /* CYGWIN */
7866 /* Strip the dummy filename off the end of the string if we
7867 added it to select a directory. */
7868 if ((use_unicode && file_details_w->nFilterIndex == 2)
7869 #ifndef NTGUI_UNICODE
7870 || (!use_unicode && file_details_a->nFilterIndex == 2)
7871 #endif
7873 filename = Ffile_name_directory (filename);
7875 /* User canceled the dialog without making a selection. */
7876 else if (!CommDlgExtendedError ())
7877 filename = Qnil;
7878 /* An error occurred, fallback on reading from the mini-buffer. */
7879 else
7880 filename = Fcompleting_read (
7881 orig_prompt,
7882 intern ("read-file-name-internal"),
7883 orig_dir,
7884 mustmatch,
7885 orig_dir,
7886 Qfile_name_history,
7887 default_filename,
7888 Qnil);
7891 /* Make "Cancel" equivalent to C-g. */
7892 if (NILP (filename))
7893 quit ();
7895 return filename;
7899 #ifdef WINDOWSNT
7900 /* Moving files to the system recycle bin.
7901 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
7902 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
7903 Ssystem_move_file_to_trash, 1, 1, 0,
7904 doc: /* Move file or directory named FILENAME to the recycle bin. */)
7905 (Lisp_Object filename)
7907 Lisp_Object handler;
7908 Lisp_Object encoded_file;
7909 Lisp_Object operation;
7911 operation = Qdelete_file;
7912 if (!NILP (Ffile_directory_p (filename))
7913 && NILP (Ffile_symlink_p (filename)))
7915 operation = intern ("delete-directory");
7916 filename = Fdirectory_file_name (filename);
7919 /* Must have fully qualified file names for moving files to Recycle
7920 Bin. */
7921 filename = Fexpand_file_name (filename, Qnil);
7923 handler = Ffind_file_name_handler (filename, operation);
7924 if (!NILP (handler))
7925 return call2 (handler, operation, filename);
7926 else
7928 const char * path;
7929 int result;
7931 encoded_file = ENCODE_FILE (filename);
7933 path = map_w32_filename (SSDATA (encoded_file), NULL);
7935 /* The Unicode version of SHFileOperation is not supported on
7936 Windows 9X. */
7937 if (w32_unicode_filenames && os_subtype != OS_9X)
7939 SHFILEOPSTRUCTW file_op_w;
7940 /* We need one more element beyond MAX_PATH because this is
7941 a list of file names, with the last element double-null
7942 terminated. */
7943 wchar_t tmp_path_w[MAX_PATH + 1];
7945 memset (tmp_path_w, 0, sizeof (tmp_path_w));
7946 filename_to_utf16 (path, tmp_path_w);
7948 /* On Windows, write permission is required to delete/move files. */
7949 _wchmod (tmp_path_w, 0666);
7951 memset (&file_op_w, 0, sizeof (file_op_w));
7952 file_op_w.hwnd = HWND_DESKTOP;
7953 file_op_w.wFunc = FO_DELETE;
7954 file_op_w.pFrom = tmp_path_w;
7955 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7956 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7957 file_op_w.fAnyOperationsAborted = FALSE;
7959 result = SHFileOperationW (&file_op_w);
7961 else
7963 SHFILEOPSTRUCTA file_op_a;
7964 char tmp_path_a[MAX_PATH + 1];
7966 memset (tmp_path_a, 0, sizeof (tmp_path_a));
7967 filename_to_ansi (path, tmp_path_a);
7969 /* If a file cannot be represented in ANSI codepage, don't
7970 let them inadvertently delete other files because some
7971 characters are interpreted as a wildcards. */
7972 if (_mbspbrk ((unsigned char *)tmp_path_a,
7973 (const unsigned char *)"?*"))
7974 result = ERROR_FILE_NOT_FOUND;
7975 else
7977 _chmod (tmp_path_a, 0666);
7979 memset (&file_op_a, 0, sizeof (file_op_a));
7980 file_op_a.hwnd = HWND_DESKTOP;
7981 file_op_a.wFunc = FO_DELETE;
7982 file_op_a.pFrom = tmp_path_a;
7983 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7984 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7985 file_op_a.fAnyOperationsAborted = FALSE;
7987 result = SHFileOperationA (&file_op_a);
7990 if (result != 0)
7991 report_file_error ("Removing old name", list1 (filename));
7993 return Qnil;
7996 #endif /* WINDOWSNT */
7999 /***********************************************************************
8000 w32 specialized functions
8001 ***********************************************************************/
8003 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
8004 Sw32_send_sys_command, 1, 2, 0,
8005 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
8006 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
8007 to minimize), #xf120 to restore frame to original size, and #xf100
8008 to activate the menubar for keyboard access. #xf140 activates the
8009 screen saver if defined.
8011 If optional parameter FRAME is not specified, use selected frame. */)
8012 (Lisp_Object command, Lisp_Object frame)
8014 struct frame *f = decode_window_system_frame (frame);
8016 CHECK_NUMBER (command);
8018 if (FRAME_W32_P (f))
8019 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
8021 return Qnil;
8024 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
8025 doc: /* Get Windows to perform OPERATION on DOCUMENT.
8026 This is a wrapper around the ShellExecute system function, which
8027 invokes the application registered to handle OPERATION for DOCUMENT.
8029 OPERATION is either nil or a string that names a supported operation.
8030 What operations can be used depends on the particular DOCUMENT and its
8031 handler application, but typically it is one of the following common
8032 operations:
8034 \"open\" - open DOCUMENT, which could be a file, a directory, or an
8035 executable program (application). If it is an application,
8036 that application is launched in the current buffer's default
8037 directory. Otherwise, the application associated with
8038 DOCUMENT is launched in the buffer's default directory.
8039 \"opennew\" - like \"open\", but instruct the application to open
8040 DOCUMENT in a new window.
8041 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
8042 \"print\" - print DOCUMENT, which must be a file.
8043 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
8044 The printer should be provided in PARAMETERS, see below.
8045 \"explore\" - start the Windows Explorer on DOCUMENT.
8046 \"edit\" - launch an editor and open DOCUMENT for editing; which
8047 editor is launched depends on the association for the
8048 specified DOCUMENT.
8049 \"find\" - initiate search starting from DOCUMENT, which must specify
8050 a directory.
8051 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
8052 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
8053 the clipboard.
8054 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
8055 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
8056 which must be a directory.
8057 \"pastelink\"
8058 - create a shortcut in DOCUMENT (which must be a directory)
8059 the file or directory whose name is in the clipboard.
8060 \"runas\" - run DOCUMENT, which must be an excutable file, with
8061 elevated privileges (a.k.a. \"as Administrator\").
8062 \"properties\"
8063 - open the property sheet dialog for DOCUMENT.
8064 nil - invoke the default OPERATION, or \"open\" if default is
8065 not defined or unavailable.
8067 DOCUMENT is typically the name of a document file or a URL, but can
8068 also be an executable program to run, or a directory to open in the
8069 Windows Explorer. If it is a file or a directory, it must be a local
8070 one; this function does not support remote file names.
8072 If DOCUMENT is an executable program, the optional third arg PARAMETERS
8073 can be a string containing command line parameters, separated by blanks,
8074 that will be passed to the program. Some values of OPERATION also require
8075 parameters (e.g., \"printto\" requires the printer address). Otherwise,
8076 PARAMETERS should be nil or unspecified. Note that double quote characters
8077 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
8079 Optional fourth argument SHOW-FLAG can be used to control how the
8080 application will be displayed when it is invoked. If SHOW-FLAG is nil
8081 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
8082 specified, otherwise it is an integer between 0 and 11 representing
8083 a ShowWindow flag:
8085 0 - start hidden
8086 1 - start as normal-size window
8087 3 - start in a maximized window
8088 6 - start in a minimized window
8089 10 - start as the application itself specifies; this is the default. */)
8090 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
8092 char *errstr;
8093 Lisp_Object current_dir = BVAR (current_buffer, directory);;
8094 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
8095 #ifdef CYGWIN
8096 intptr_t result;
8097 #else
8098 int use_unicode = w32_unicode_filenames;
8099 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
8100 Lisp_Object absdoc, handler;
8101 BOOL success;
8102 #endif
8104 CHECK_STRING (document);
8106 #ifdef CYGWIN
8107 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
8108 document = Fcygwin_convert_file_name_to_windows (document, Qt);
8110 /* Encode filename, current directory and parameters. */
8111 current_dir = GUI_ENCODE_FILE (current_dir);
8112 document = GUI_ENCODE_FILE (document);
8113 doc_w = GUI_SDATA (document);
8114 if (STRINGP (parameters))
8116 parameters = GUI_ENCODE_SYSTEM (parameters);
8117 params_w = GUI_SDATA (parameters);
8119 if (STRINGP (operation))
8121 operation = GUI_ENCODE_SYSTEM (operation);
8122 ops_w = GUI_SDATA (operation);
8124 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
8125 GUI_SDATA (current_dir),
8126 (INTEGERP (show_flag)
8127 ? XINT (show_flag) : SW_SHOWDEFAULT));
8129 if (result > 32)
8130 return Qt;
8132 switch (result)
8134 case SE_ERR_ACCESSDENIED:
8135 errstr = w32_strerror (ERROR_ACCESS_DENIED);
8136 break;
8137 case SE_ERR_ASSOCINCOMPLETE:
8138 case SE_ERR_NOASSOC:
8139 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
8140 break;
8141 case SE_ERR_DDEBUSY:
8142 case SE_ERR_DDEFAIL:
8143 errstr = w32_strerror (ERROR_DDE_FAIL);
8144 break;
8145 case SE_ERR_DDETIMEOUT:
8146 errstr = w32_strerror (ERROR_TIMEOUT);
8147 break;
8148 case SE_ERR_DLLNOTFOUND:
8149 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
8150 break;
8151 case SE_ERR_FNF:
8152 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
8153 break;
8154 case SE_ERR_OOM:
8155 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
8156 break;
8157 case SE_ERR_PNF:
8158 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
8159 break;
8160 case SE_ERR_SHARE:
8161 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
8162 break;
8163 default:
8164 errstr = w32_strerror (0);
8165 break;
8168 #else /* !CYGWIN */
8170 const char file_url_str[] = "file:///";
8171 const int file_url_len = sizeof (file_url_str) - 1;
8172 int doclen;
8174 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
8176 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
8177 start a thread in some rare system configurations, for
8178 unknown reasons. That thread is started in the context of
8179 the Emacs process, but out of control of our code, and seems
8180 to never exit afterwards. Each such thread reserves 8MB of
8181 stack space (because that's the value recorded in the Emacs
8182 executable at link time: Emacs needs a large stack). So a
8183 large enough number of invocations of w32-shell-execute can
8184 potentially cause the Emacs process to run out of available
8185 address space, which is nasty. To work around this, we
8186 convert such URLs to local file names, which seems to prevent
8187 those threads from starting. See bug #20220. */
8188 char *p = SSDATA (document) + file_url_len;
8190 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
8191 document = Fsubstring_no_properties (document,
8192 make_number (file_url_len), Qnil);
8194 /* We have a situation here. If DOCUMENT is a relative file name,
8195 but its name includes leading directories, i.e. it lives not in
8196 CURRENT_DIR, but in its subdirectory, then ShellExecute below
8197 will fail to find it. So we need to make the file name is
8198 absolute. But DOCUMENT does not have to be a file, it can be a
8199 URL, for example. So we make it absolute only if it is an
8200 existing file; if it is a file that does not exist, tough. */
8201 absdoc = Fexpand_file_name (document, Qnil);
8202 /* Don't call file handlers for file-exists-p, since they might
8203 attempt to access the file, which could fail or produce undesired
8204 consequences, see bug#16558 for an example. */
8205 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
8206 if (NILP (handler))
8208 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
8210 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
8212 /* ShellExecute fails if DOCUMENT is a UNC with forward
8213 slashes (expand-file-name above converts all backslashes
8214 to forward slashes). Now that we know DOCUMENT is a
8215 file, we can mirror all forward slashes into backslashes. */
8216 unixtodos_filename (SSDATA (absdoc_encoded));
8217 document = absdoc_encoded;
8219 else
8220 document = ENCODE_FILE (document);
8222 else
8223 document = ENCODE_FILE (document);
8225 current_dir = ENCODE_FILE (current_dir);
8226 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
8227 be a URL that is not limited to MAX_PATH chararcters. */
8228 doclen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
8229 SSDATA (document), -1, NULL, 0);
8230 doc_w = xmalloc (doclen * sizeof (wchar_t));
8231 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
8232 SSDATA (document), -1, doc_w, doclen);
8233 if (use_unicode)
8235 wchar_t current_dir_w[MAX_PATH];
8236 SHELLEXECUTEINFOW shexinfo_w;
8238 /* Encode the current directory and parameters, and convert
8239 operation to UTF-16. */
8240 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
8241 if (STRINGP (parameters))
8243 int len;
8245 parameters = ENCODE_SYSTEM (parameters);
8246 len = pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
8247 SSDATA (parameters), -1, NULL, 0);
8248 if (len > 32768)
8249 len = 32768;
8250 params_w = alloca (len * sizeof (wchar_t));
8251 pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
8252 SSDATA (parameters), -1, params_w, len);
8253 params_w[len - 1] = 0;
8255 if (STRINGP (operation))
8257 /* Assume OPERATION is pure ASCII. */
8258 const char *s = SSDATA (operation);
8259 wchar_t *d;
8260 int len = SBYTES (operation) + 1;
8262 if (len > 32768)
8263 len = 32768;
8264 d = ops_w = alloca (len * sizeof (wchar_t));
8265 while (d < ops_w + len - 1)
8266 *d++ = *s++;
8267 *d = 0;
8270 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
8271 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
8272 able to invoke verbs from shortcut menu extensions, not just
8273 static verbs listed in the Registry. */
8274 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
8275 shexinfo_w.cbSize = sizeof (shexinfo_w);
8276 shexinfo_w.fMask =
8277 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8278 shexinfo_w.hwnd = NULL;
8279 shexinfo_w.lpVerb = ops_w;
8280 shexinfo_w.lpFile = doc_w;
8281 shexinfo_w.lpParameters = params_w;
8282 shexinfo_w.lpDirectory = current_dir_w;
8283 shexinfo_w.nShow =
8284 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8285 success = ShellExecuteExW (&shexinfo_w);
8286 xfree (doc_w);
8288 else
8290 char current_dir_a[MAX_PATH];
8291 SHELLEXECUTEINFOA shexinfo_a;
8292 int codepage = codepage_for_filenames (NULL);
8293 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
8294 NULL, NULL);
8296 doc_a = xmalloc (ldoc_a);
8297 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
8298 filename_to_ansi (SSDATA (current_dir), current_dir_a);
8299 if (STRINGP (parameters))
8301 parameters = ENCODE_SYSTEM (parameters);
8302 params_a = SSDATA (parameters);
8304 if (STRINGP (operation))
8306 /* Assume OPERATION is pure ASCII. */
8307 ops_a = SSDATA (operation);
8309 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
8310 shexinfo_a.cbSize = sizeof (shexinfo_a);
8311 shexinfo_a.fMask =
8312 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8313 shexinfo_a.hwnd = NULL;
8314 shexinfo_a.lpVerb = ops_a;
8315 shexinfo_a.lpFile = doc_a;
8316 shexinfo_a.lpParameters = params_a;
8317 shexinfo_a.lpDirectory = current_dir_a;
8318 shexinfo_a.nShow =
8319 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8320 success = ShellExecuteExA (&shexinfo_a);
8321 xfree (doc_w);
8322 xfree (doc_a);
8325 if (success)
8326 return Qt;
8328 errstr = w32_strerror (0);
8330 #endif /* !CYGWIN */
8332 /* The error string might be encoded in the locale's encoding. */
8333 if (!NILP (Vlocale_coding_system))
8335 Lisp_Object decoded =
8336 code_convert_string_norecord (build_unibyte_string (errstr),
8337 Vlocale_coding_system, 0);
8338 errstr = SSDATA (decoded);
8340 error ("ShellExecute failed: %s", errstr);
8343 /* Lookup virtual keycode from string representing the name of a
8344 non-ascii keystroke into the corresponding virtual key, using
8345 lispy_function_keys. */
8346 static int
8347 lookup_vk_code (char *key)
8349 int i;
8351 for (i = 0; i < 256; i++)
8352 if (lispy_function_keys[i]
8353 && strcmp (lispy_function_keys[i], key) == 0)
8354 return i;
8356 if (w32_kbdhook_active)
8358 /* Alphanumerics map to themselves. */
8359 if (key[1] == 0)
8361 if ((key[0] >= 'A' && key[0] <= 'Z')
8362 || (key[0] >= '0' && key[0] <= '9'))
8363 return key[0];
8364 if (key[0] >= 'a' && key[0] <= 'z')
8365 return toupper(key[0]);
8369 return -1;
8372 /* Convert a one-element vector style key sequence to a hot key
8373 definition. */
8374 static Lisp_Object
8375 w32_parse_and_hook_hot_key (Lisp_Object key, int hook)
8377 /* Copied from Fdefine_key and store_in_keymap. */
8378 register Lisp_Object c;
8379 int vk_code = 0;
8380 int lisp_modifiers = 0;
8381 int w32_modifiers;
8382 Lisp_Object res = Qnil;
8383 char* vkname;
8385 CHECK_VECTOR (key);
8387 if (ASIZE (key) != 1)
8388 return Qnil;
8390 c = AREF (key, 0);
8392 if (CONSP (c) && lucid_event_type_list_p (c))
8393 c = Fevent_convert_list (c);
8395 if (! INTEGERP (c) && ! SYMBOLP (c))
8396 error ("Key definition is invalid");
8398 /* Work out the base key and the modifiers. */
8399 if (SYMBOLP (c))
8401 c = parse_modifiers (c);
8402 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8403 c = Fcar (c);
8404 if (!SYMBOLP (c))
8405 emacs_abort ();
8406 vkname = SSDATA (SYMBOL_NAME (c));
8407 /* [s-], [M-], [h-]: Register all keys for this modifier */
8408 if (w32_kbdhook_active && vkname[0] == 0)
8409 vk_code = VK_ANY;
8410 else
8411 vk_code = lookup_vk_code (vkname);
8413 else if (INTEGERP (c))
8415 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8416 /* Many ascii characters are their own virtual key code. */
8417 vk_code = XINT (c) & CHARACTERBITS;
8420 if (vk_code < 0 || vk_code > 255)
8421 return Qnil;
8423 if ((lisp_modifiers & meta_modifier) != 0
8424 && !NILP (Vw32_alt_is_meta))
8425 lisp_modifiers |= alt_modifier;
8427 /* Supply defs missing from mingw32. */
8428 #ifndef MOD_ALT
8429 #define MOD_ALT 0x0001
8430 #define MOD_CONTROL 0x0002
8431 #define MOD_SHIFT 0x0004
8432 #define MOD_WIN 0x0008
8433 #endif
8435 if (w32_kbdhook_active)
8437 /* Register Alt-x combinations. */
8438 if (lisp_modifiers & alt_modifier)
8440 hook_w32_key (hook, VK_MENU, vk_code);
8441 res = Qt;
8443 /* Register Win-x combinations based on modifier mappings. */
8444 if (((lisp_modifiers & hyper_modifier)
8445 && EQ (Vw32_lwindow_modifier, Qhyper))
8446 || ((lisp_modifiers & super_modifier)
8447 && EQ (Vw32_lwindow_modifier, Qsuper)))
8449 hook_w32_key (hook, VK_LWIN, vk_code);
8450 res = Qt;
8452 if (((lisp_modifiers & hyper_modifier)
8453 && EQ (Vw32_rwindow_modifier, Qhyper))
8454 || ((lisp_modifiers & super_modifier)
8455 && EQ (Vw32_rwindow_modifier, Qsuper)))
8457 hook_w32_key (hook, VK_RWIN, vk_code);
8458 res = Qt;
8460 return res;
8462 else
8464 /* Convert lisp modifiers to Windows hot-key form. */
8465 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8466 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8467 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8468 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8470 return HOTKEY (vk_code, w32_modifiers);
8474 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8475 Sw32_register_hot_key, 1, 1, 0,
8476 doc: /* Register KEY as a hot-key combination.
8477 Certain key combinations like Alt-Tab and Win-R are reserved for
8478 system use on Windows, and therefore are normally intercepted by the
8479 system. These key combinations can be received by registering them
8480 as hot-keys, except for Win-L which always locks the computer.
8482 On Windows 98 and ME, KEY must be a one element key definition in
8483 vector form that would be acceptable to `define-key' (e.g. [A-tab] for
8484 Alt-Tab). The meta modifier is interpreted as Alt if
8485 `w32-alt-is-meta' is t, and hyper is always interpreted as the Windows
8486 modifier keys. The return value is the hotkey-id if registered, otherwise nil.
8488 On Windows versions since NT, KEY can also be specified as [M-], [s-] or
8489 [h-] to indicate that all combinations of that key should be processed
8490 by Emacs instead of the operating system. The super and hyper
8491 modifiers are interpreted according to the current values of
8492 `w32-lwindow-modifier' and `w32-rwindow-modifier'. For instance,
8493 setting `w32-lwindow-modifier' to `super' and then calling
8494 `(register-hot-key [s-])' grabs all combinations of the left Windows
8495 key to Emacs, but leaves the right Windows key free for the operating
8496 system keyboard shortcuts. The return value is t if the call affected
8497 any key combinations, otherwise nil. */)
8498 (Lisp_Object key)
8500 key = w32_parse_and_hook_hot_key (key, 1);
8502 if (!w32_kbdhook_active
8503 && !NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8505 /* Reuse an empty slot if possible. */
8506 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8508 /* Safe to add new key to list, even if we have focus. */
8509 if (NILP (item))
8510 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8511 else
8512 XSETCAR (item, key);
8514 /* Notify input thread about new hot-key definition, so that it
8515 takes effect without needing to switch focus. */
8516 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8517 (WPARAM) XINT (key), 0);
8520 return key;
8523 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8524 Sw32_unregister_hot_key, 1, 1, 0,
8525 doc: /* Unregister KEY as a hot-key combination. */)
8526 (Lisp_Object key)
8528 Lisp_Object item;
8530 if (!INTEGERP (key))
8531 key = w32_parse_and_hook_hot_key (key, 0);
8533 if (w32_kbdhook_active)
8534 return key;
8536 item = Fmemq (key, w32_grabbed_keys);
8538 if (!NILP (item))
8540 LPARAM lparam;
8542 eassert (CONSP (item));
8543 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
8544 so that it works in a --with-wide-int build as well. */
8545 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
8547 /* Notify input thread about hot-key definition being removed, so
8548 that it takes effect without needing focus switch. */
8549 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8550 (WPARAM) XINT (XCAR (item)), lparam))
8552 MSG msg;
8553 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8555 return Qt;
8557 return Qnil;
8560 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8561 Sw32_registered_hot_keys, 0, 0, 0,
8562 doc: /* Return list of registered hot-key IDs. */)
8563 (void)
8565 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8568 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8569 Sw32_reconstruct_hot_key, 1, 1, 0,
8570 doc: /* Convert hot-key ID to a lisp key combination.
8571 usage: (w32-reconstruct-hot-key ID) */)
8572 (Lisp_Object hotkeyid)
8574 int vk_code, w32_modifiers;
8575 Lisp_Object key;
8577 CHECK_NUMBER (hotkeyid);
8579 vk_code = HOTKEY_VK_CODE (hotkeyid);
8580 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8582 if (vk_code < 256 && lispy_function_keys[vk_code])
8583 key = intern (lispy_function_keys[vk_code]);
8584 else
8585 key = make_number (vk_code);
8587 key = Fcons (key, Qnil);
8588 if (w32_modifiers & MOD_SHIFT)
8589 key = Fcons (Qshift, key);
8590 if (w32_modifiers & MOD_CONTROL)
8591 key = Fcons (Qctrl, key);
8592 if (w32_modifiers & MOD_ALT)
8593 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8594 if (w32_modifiers & MOD_WIN)
8595 key = Fcons (Qhyper, key);
8597 return key;
8600 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8601 Sw32_toggle_lock_key, 1, 2, 0,
8602 doc: /* Toggle the state of the lock key KEY.
8603 KEY can be `capslock', `kp-numlock', or `scroll'.
8604 If the optional parameter NEW-STATE is a number, then the state of KEY
8605 is set to off if the low bit of NEW-STATE is zero, otherwise on.
8606 If NEW-STATE is omitted or nil, the function toggles the state,
8608 Value is the new state of the key, or nil if the function failed
8609 to change the state. */)
8610 (Lisp_Object key, Lisp_Object new_state)
8612 int vk_code;
8613 LPARAM lparam;
8615 if (EQ (key, intern ("capslock")))
8616 vk_code = VK_CAPITAL;
8617 else if (EQ (key, intern ("kp-numlock")))
8618 vk_code = VK_NUMLOCK;
8619 else if (EQ (key, intern ("scroll")))
8620 vk_code = VK_SCROLL;
8621 else
8622 return Qnil;
8624 if (!dwWindowsThreadId)
8625 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8627 if (NILP (new_state))
8628 lparam = -1;
8629 else
8630 lparam = (XUINT (new_state)) & 1;
8631 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8632 (WPARAM) vk_code, lparam))
8634 MSG msg;
8635 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8636 return make_number (msg.wParam);
8638 return Qnil;
8641 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8642 2, 2, 0,
8643 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8645 This is a direct interface to the Windows API FindWindow function. */)
8646 (Lisp_Object class, Lisp_Object name)
8648 HWND hnd;
8650 if (!NILP (class))
8651 CHECK_STRING (class);
8652 if (!NILP (name))
8653 CHECK_STRING (name);
8655 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8656 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8657 if (!hnd)
8658 return Qnil;
8659 return Qt;
8662 DEFUN ("w32-frame-geometry", Fw32_frame_geometry, Sw32_frame_geometry, 0, 1, 0,
8663 doc: /* Return geometric attributes of FRAME.
8664 FRAME must be a live frame and defaults to the selected one. The return
8665 value is an association list of the attributes listed below. All height
8666 and width values are in pixels.
8668 `outer-position' is a cons of the outer left and top edges of FRAME
8669 relative to the origin - the position (0, 0) - of FRAME's display.
8671 `outer-size' is a cons of the outer width and height of FRAME. The
8672 outer size includes the title bar and the external borders as well as
8673 any menu and/or tool bar of frame.
8675 `external-border-size' is a cons of the horizontal and vertical width of
8676 FRAME's external borders as supplied by the window manager.
8678 `title-bar-size' is a cons of the width and height of the title bar of
8679 FRAME as supplied by the window manager. If both of them are zero,
8680 FRAME has no title bar. If only the width is zero, Emacs was not
8681 able to retrieve the width information.
8683 `menu-bar-external', if non-nil, means the menu bar is external (never
8684 included in the inner edges of FRAME).
8686 `menu-bar-size' is a cons of the width and height of the menu bar of
8687 FRAME.
8689 `tool-bar-external', if non-nil, means the tool bar is external (never
8690 included in the inner edges of FRAME).
8692 `tool-bar-position' tells on which side the tool bar on FRAME is and can
8693 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
8694 has no tool bar.
8696 `tool-bar-size' is a cons of the width and height of the tool bar of
8697 FRAME.
8699 `internal-border-width' is the width of the internal border of
8700 FRAME. */)
8701 (Lisp_Object frame)
8703 struct frame *f = decode_live_frame (frame);
8705 MENUBARINFO menu_bar;
8706 WINDOWINFO window;
8707 int left, top, right, bottom;
8708 unsigned int external_border_width, external_border_height;
8709 int title_bar_width = 0, title_bar_height = 0;
8710 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8711 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8712 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8714 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8715 return Qnil;
8717 block_input ();
8718 /* Outer rectangle and borders. */
8719 window.cbSize = sizeof (window);
8720 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8721 external_border_width = window.cxWindowBorders;
8722 external_border_height = window.cyWindowBorders;
8723 /* Title bar. */
8724 if (get_title_bar_info_fn)
8726 TITLEBAR_INFO title_bar;
8728 title_bar.cbSize = sizeof (title_bar);
8729 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8730 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8731 for (int i = 0; i < 6; i++)
8732 title_bar.rgstate[i] = 0;
8733 if (get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar)
8734 && !(title_bar.rgstate[0] & 0x00008001))
8736 title_bar_width
8737 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8738 title_bar_height
8739 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8742 else if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8743 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8744 /* Menu bar. */
8745 menu_bar.cbSize = sizeof (menu_bar);
8746 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8747 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8748 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8749 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8750 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8751 unblock_input ();
8753 left = window.rcWindow.left;
8754 top = window.rcWindow.top;
8755 right = window.rcWindow.right;
8756 bottom = window.rcWindow.bottom;
8758 /* Menu bar. */
8759 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8760 /* Fix menu bar height reported by GetMenuBarInfo. */
8761 if (menu_bar_height > single_menu_bar_height)
8762 /* A wrapped menu bar. */
8763 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8764 else if (menu_bar_height > 0)
8765 /* A single line menu bar. */
8766 menu_bar_height = single_menu_bar_height;
8768 return listn (CONSTYPE_HEAP, 10,
8769 Fcons (Qouter_position,
8770 Fcons (make_number (left), make_number (top))),
8771 Fcons (Qouter_size,
8772 Fcons (make_number (right - left),
8773 make_number (bottom - top))),
8774 Fcons (Qexternal_border_size,
8775 Fcons (make_number (external_border_width),
8776 make_number (external_border_height))),
8777 Fcons (Qtitle_bar_size,
8778 Fcons (make_number (title_bar_width),
8779 make_number (title_bar_height))),
8780 Fcons (Qmenu_bar_external, Qt),
8781 Fcons (Qmenu_bar_size,
8782 Fcons (make_number
8783 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8784 make_number (menu_bar_height))),
8785 Fcons (Qtool_bar_external, Qnil),
8786 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8787 Fcons (Qtool_bar_size,
8788 Fcons (make_number
8789 (tool_bar_height
8790 ? (right - left - 2 * external_border_width
8791 - 2 * internal_border_width)
8792 : 0),
8793 make_number (tool_bar_height))),
8794 Fcons (Qinternal_border_width,
8795 make_number (internal_border_width)));
8798 DEFUN ("w32-frame-edges", Fw32_frame_edges, Sw32_frame_edges, 0, 2, 0,
8799 doc: /* Return edge coordinates of FRAME.
8800 FRAME must be a live frame and defaults to the selected one. The return
8801 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8802 in pixels relative to the origin - the position (0, 0) - of FRAME's
8803 display.
8805 If optional argument TYPE is the symbol `outer-edges', return the outer
8806 edges of FRAME. The outer edges comprise the decorations of the window
8807 manager (like the title bar or external borders) as well as any external
8808 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8809 `native-edges' or nil, return the native edges of FRAME. The native
8810 edges exclude the decorations of the window manager and any external
8811 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8812 the inner edges of FRAME. These edges exclude title bar, any borders,
8813 menu bar or tool bar of FRAME. */)
8814 (Lisp_Object frame, Lisp_Object type)
8816 struct frame *f = decode_live_frame (frame);
8818 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8819 return Qnil;
8821 if (EQ (type, Qouter_edges))
8823 RECT rectangle;
8824 BOOL success = false;
8826 block_input ();
8827 /* Outer frame rectangle, including outer borders and title bar. */
8828 success = GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8829 unblock_input ();
8831 if (success)
8832 return list4 (make_number (rectangle.left),
8833 make_number (rectangle.top),
8834 make_number (rectangle.right),
8835 make_number (rectangle.bottom));
8836 else
8837 return Qnil;
8839 else
8841 RECT rectangle;
8842 POINT pt;
8843 int left, top, right, bottom;
8844 BOOL success;
8846 block_input ();
8847 /* Inner frame rectangle, excluding borders and title bar. */
8848 success = GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
8849 /* Get top-left corner of native rectangle in screen
8850 coordinates. */
8851 if (!success)
8853 unblock_input ();
8854 return Qnil;
8857 pt.x = 0;
8858 pt.y = 0;
8859 success = ClientToScreen (FRAME_W32_WINDOW (f), &pt);
8860 unblock_input ();
8862 if (!success)
8863 return Qnil;
8865 left = pt.x;
8866 top = pt.y;
8867 right = left + rectangle.right;
8868 bottom = top + rectangle.bottom;
8870 if (EQ (type, Qinner_edges))
8872 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8874 return list4 (make_number (left + internal_border_width),
8875 make_number (top
8876 + FRAME_TOOL_BAR_HEIGHT (f)
8877 + internal_border_width),
8878 make_number (right - internal_border_width),
8879 make_number (bottom - internal_border_width));
8881 else
8882 return list4 (make_number (left), make_number (top),
8883 make_number (right), make_number (bottom));
8888 * w32_frame_list_z_order:
8890 * Recursively add list of all frames on the display specified via
8891 * DPYINFO and whose window-system window's parent is specified by
8892 * WINDOW to FRAMES and return FRAMES.
8894 static Lisp_Object
8895 w32_frame_list_z_order (struct w32_display_info *dpyinfo, HWND window)
8897 Lisp_Object frame, frames = Qnil;
8899 while (window)
8901 struct frame *f = x_window_to_frame (dpyinfo, window);
8903 if (f)
8905 XSETFRAME (frame, f);
8906 frames = Fcons (frame, frames);
8909 block_input ();
8910 window = GetNextWindow (window, GW_HWNDNEXT);
8911 unblock_input ();
8914 return Fnreverse (frames);
8917 DEFUN ("w32-frame-list-z-order", Fw32_frame_list_z_order,
8918 Sw32_frame_list_z_order, 0, 1, 0,
8919 doc: /* Return list of Emacs' frames, in Z (stacking) order.
8920 The optional argument DISPLAY specifies which display to ask about.
8921 DISPLAY should be either a frame or a display name (a string). If
8922 omitted or nil, that stands for the selected frame's display.
8924 As a special case, if DISPLAY is non-nil and specifies a live frame,
8925 return the child frames of that frame in Z (stacking) order.
8927 Frames are listed from topmost (first) to bottommost (last). */)
8928 (Lisp_Object display)
8930 struct w32_display_info *dpyinfo = check_x_display_info (display);
8931 HWND window;
8933 block_input ();
8934 if (FRAMEP (display) && FRAME_LIVE_P (XFRAME (display)))
8935 window = GetWindow (FRAME_W32_WINDOW (XFRAME (display)), GW_CHILD);
8936 else
8937 window = GetTopWindow (NULL);
8938 unblock_input ();
8940 return w32_frame_list_z_order (dpyinfo, window);
8944 * w32_frame_restack:
8946 * Restack frame F1 below frame F2, above if ABOVE_FLAG is non-nil. In
8947 * practice this is a two-step action: The first step removes F1's
8948 * window-system window from the display. The second step reinserts
8949 * F1's window below (above if ABOVE_FLAG is true) that of F2.
8951 static void
8952 w32_frame_restack (struct frame *f1, struct frame *f2, bool above_flag)
8954 HWND hwnd1 = FRAME_W32_WINDOW (f1);
8955 HWND hwnd2 = FRAME_W32_WINDOW (f2);
8957 block_input ();
8958 if (above_flag)
8959 /* Put F1 above F2 in the z-order. */
8961 if (GetNextWindow (hwnd1, GW_HWNDNEXT) != hwnd2)
8963 /* Make sure F1 is below F2 first because we must not
8964 change the relative position of F2 wrt any other
8965 window but F1. */
8966 if (GetNextWindow (hwnd2, GW_HWNDNEXT) != hwnd1)
8967 SetWindowPos (hwnd1, hwnd2, 0, 0, 0, 0,
8968 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
8969 | SWP_FRAMECHANGED);
8970 /* Now put F1 above F2. */
8971 SetWindowPos (hwnd2, hwnd1, 0, 0, 0, 0,
8972 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
8973 | SWP_FRAMECHANGED);
8976 else if (GetNextWindow (hwnd2, GW_HWNDNEXT) != hwnd1)
8977 /* Put F1 below F2 in the z-order. */
8978 SetWindowPos (hwnd1, hwnd2, 0, 0, 0, 0,
8979 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
8980 | SWP_FRAMECHANGED);
8981 unblock_input ();
8984 DEFUN ("w32-frame-restack", Fw32_frame_restack, Sw32_frame_restack, 2, 3, 0,
8985 doc: /* Restack FRAME1 below FRAME2.
8986 This means that if both frames are visible and the display areas of
8987 these frames overlap, FRAME2 (partially) obscures FRAME1. If optional
8988 third argument ABOVE is non-nil, restack FRAME1 above FRAME2. This
8989 means that if both frames are visible and the display areas of these
8990 frames overlap, FRAME1 (partially) obscures FRAME2.
8992 This may be thought of as an atomic action performed in two steps: The
8993 first step removes FRAME1's window-system window from the display. The
8994 second step reinserts FRAME1's window below (above if ABOVE is true)
8995 that of FRAME2. Hence the position of FRAME2 in its display's Z
8996 \(stacking) order relative to all other frames excluding FRAME1 remains
8997 unaltered.
8999 Some window managers may refuse to restack windows. */)
9000 (Lisp_Object frame1, Lisp_Object frame2, Lisp_Object above)
9002 struct frame *f1 = decode_live_frame (frame1);
9003 struct frame *f2 = decode_live_frame (frame2);
9005 if (FRAME_W32_P (f1) && FRAME_W32_P (f2))
9007 w32_frame_restack (f1, f2, !NILP (above));
9008 return Qt;
9010 else
9012 error ("Cannot restack frames");
9013 return Qnil;
9017 DEFUN ("w32-mouse-absolute-pixel-position", Fw32_mouse_absolute_pixel_position,
9018 Sw32_mouse_absolute_pixel_position, 0, 0, 0,
9019 doc: /* Return absolute position of mouse cursor in pixels.
9020 The position is returned as a cons cell (X . Y) of the coordinates of
9021 the mouse cursor position in pixels relative to a position (0, 0) of the
9022 selected frame's display. */)
9023 (void)
9025 POINT pt;
9027 block_input ();
9028 GetCursorPos (&pt);
9029 unblock_input ();
9031 return Fcons (make_number (pt.x), make_number (pt.y));
9034 DEFUN ("w32-set-mouse-absolute-pixel-position", Fw32_set_mouse_absolute_pixel_position,
9035 Sw32_set_mouse_absolute_pixel_position, 2, 2, 0,
9036 doc: /* Move mouse pointer to absolute pixel position (X, Y).
9037 The coordinates X and Y are interpreted in pixels relative to a position
9038 \(0, 0) of the selected frame's display. */)
9039 (Lisp_Object x, Lisp_Object y)
9041 UINT trail_num = 0;
9042 BOOL ret = false;
9044 CHECK_TYPE_RANGED_INTEGER (int, x);
9045 CHECK_TYPE_RANGED_INTEGER (int, y);
9047 block_input ();
9048 /* When "mouse trails" are in effect, moving the mouse cursor
9049 sometimes leaves behind an annoying "ghost" of the pointer.
9050 Avoid that by momentarily switching off mouse trails. */
9051 if (os_subtype == OS_NT
9052 && w32_major_version + w32_minor_version >= 6)
9053 ret = SystemParametersInfo (SPI_GETMOUSETRAILS, 0, &trail_num, 0);
9054 SetCursorPos (XINT (x), XINT (y));
9055 if (ret)
9056 SystemParametersInfo (SPI_SETMOUSETRAILS, trail_num, NULL, 0);
9057 unblock_input ();
9059 return Qnil;
9063 #ifdef WINDOWSNT
9064 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
9065 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
9066 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
9067 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
9069 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
9070 doc: /* SKIP: Real doc in fileio.c. */)
9071 (Lisp_Object filename)
9073 Lisp_Object encoded, value;
9075 CHECK_STRING (filename);
9076 filename = Fexpand_file_name (filename, Qnil);
9077 encoded = ENCODE_FILE (filename);
9079 /* If the file name has special constructs in it,
9080 call the corresponding file handler. */
9081 Lisp_Object handler = Ffind_file_name_handler (encoded, Qfile_system_info);
9082 if (!NILP (handler))
9084 value = call2 (handler, Qfile_system_info, encoded);
9085 if (CONSP (value) || NILP (value))
9086 return value;
9087 error ("Invalid handler in `file-name-handler-alist'");
9090 value = Qnil;
9092 /* Determining the required information on Windows turns out, sadly,
9093 to be more involved than one would hope. The original Windows API
9094 call for this will return bogus information on some systems, but we
9095 must dynamically probe for the replacement api, since that was
9096 added rather late on. */
9098 HMODULE hKernel = GetModuleHandle ("kernel32");
9099 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
9100 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
9101 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
9102 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
9103 bool have_pfn_GetDiskFreeSpaceEx =
9104 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
9105 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
9107 /* On Windows, we may need to specify the root directory of the
9108 volume holding FILENAME. */
9109 char rootname[MAX_UTF8_PATH];
9110 wchar_t rootname_w[MAX_PATH];
9111 char rootname_a[MAX_PATH];
9112 char *name = SSDATA (encoded);
9113 BOOL result;
9115 /* find the root name of the volume if given */
9116 if (isalpha (name[0]) && name[1] == ':')
9118 rootname[0] = name[0];
9119 rootname[1] = name[1];
9120 rootname[2] = '\\';
9121 rootname[3] = 0;
9123 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
9125 char *str = rootname;
9126 int slashes = 4;
9129 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
9130 break;
9131 *str++ = *name++;
9133 while ( *name );
9135 *str++ = '\\';
9136 *str = 0;
9139 if (w32_unicode_filenames)
9140 filename_to_utf16 (rootname, rootname_w);
9141 else
9142 filename_to_ansi (rootname, rootname_a);
9144 if (have_pfn_GetDiskFreeSpaceEx)
9146 /* Unsigned large integers cannot be cast to double, so
9147 use signed ones instead. */
9148 LARGE_INTEGER availbytes;
9149 LARGE_INTEGER freebytes;
9150 LARGE_INTEGER totalbytes;
9152 if (w32_unicode_filenames)
9153 result = pfn_GetDiskFreeSpaceExW (rootname_w,
9154 (ULARGE_INTEGER *)&availbytes,
9155 (ULARGE_INTEGER *)&totalbytes,
9156 (ULARGE_INTEGER *)&freebytes);
9157 else
9158 result = pfn_GetDiskFreeSpaceExA (rootname_a,
9159 (ULARGE_INTEGER *)&availbytes,
9160 (ULARGE_INTEGER *)&totalbytes,
9161 (ULARGE_INTEGER *)&freebytes);
9162 if (result)
9163 value = list3 (make_float ((double) totalbytes.QuadPart),
9164 make_float ((double) freebytes.QuadPart),
9165 make_float ((double) availbytes.QuadPart));
9167 else
9169 DWORD sectors_per_cluster;
9170 DWORD bytes_per_sector;
9171 DWORD free_clusters;
9172 DWORD total_clusters;
9174 if (w32_unicode_filenames)
9175 result = GetDiskFreeSpaceW (rootname_w,
9176 &sectors_per_cluster,
9177 &bytes_per_sector,
9178 &free_clusters,
9179 &total_clusters);
9180 else
9181 result = GetDiskFreeSpaceA (rootname_a,
9182 &sectors_per_cluster,
9183 &bytes_per_sector,
9184 &free_clusters,
9185 &total_clusters);
9186 if (result)
9187 value = list3 (make_float ((double) total_clusters
9188 * sectors_per_cluster * bytes_per_sector),
9189 make_float ((double) free_clusters
9190 * sectors_per_cluster * bytes_per_sector),
9191 make_float ((double) free_clusters
9192 * sectors_per_cluster * bytes_per_sector));
9196 return value;
9198 #endif /* WINDOWSNT */
9201 #ifdef WINDOWSNT
9202 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
9203 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
9204 (void)
9206 static char pname_buf[256];
9207 int err;
9208 HANDLE hPrn;
9209 PRINTER_INFO_2W *ppi2w = NULL;
9210 PRINTER_INFO_2A *ppi2a = NULL;
9211 DWORD dwNeeded = 0, dwReturned = 0;
9212 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
9213 char port_name[MAX_UTF8_PATH];
9215 /* Retrieve the default string from Win.ini (the registry).
9216 * String will be in form "printername,drivername,portname".
9217 * This is the most portable way to get the default printer. */
9218 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
9219 return Qnil;
9220 /* printername precedes first "," character */
9221 strtok (pname_buf, ",");
9222 /* We want to know more than the printer name */
9223 if (!OpenPrinter (pname_buf, &hPrn, NULL))
9224 return Qnil;
9225 /* GetPrinterW is not supported by unicows.dll. */
9226 if (w32_unicode_filenames && os_subtype != OS_9X)
9227 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
9228 else
9229 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
9230 if (dwNeeded == 0)
9232 ClosePrinter (hPrn);
9233 return Qnil;
9235 /* Call GetPrinter again with big enough memory block. */
9236 if (w32_unicode_filenames && os_subtype != OS_9X)
9238 /* Allocate memory for the PRINTER_INFO_2 struct. */
9239 ppi2w = xmalloc (dwNeeded);
9240 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
9241 ClosePrinter (hPrn);
9242 if (!err)
9244 xfree (ppi2w);
9245 return Qnil;
9248 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
9249 && ppi2w->pServerName)
9251 filename_from_utf16 (ppi2w->pServerName, server_name);
9252 filename_from_utf16 (ppi2w->pShareName, share_name);
9254 else
9256 server_name[0] = '\0';
9257 filename_from_utf16 (ppi2w->pPortName, port_name);
9260 else
9262 ppi2a = xmalloc (dwNeeded);
9263 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
9264 ClosePrinter (hPrn);
9265 if (!err)
9267 xfree (ppi2a);
9268 return Qnil;
9271 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
9272 && ppi2a->pServerName)
9274 filename_from_ansi (ppi2a->pServerName, server_name);
9275 filename_from_ansi (ppi2a->pShareName, share_name);
9277 else
9279 server_name[0] = '\0';
9280 filename_from_ansi (ppi2a->pPortName, port_name);
9284 if (server_name[0])
9286 /* a remote printer */
9287 if (server_name[0] == '\\')
9288 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
9289 share_name);
9290 else
9291 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
9292 share_name);
9293 pname_buf[sizeof (pname_buf) - 1] = '\0';
9295 else
9297 /* a local printer */
9298 strncpy (pname_buf, port_name, sizeof (pname_buf));
9299 pname_buf[sizeof (pname_buf) - 1] = '\0';
9300 /* `pPortName' can include several ports, delimited by ','.
9301 * we only use the first one. */
9302 strtok (pname_buf, ",");
9305 return DECODE_FILE (build_unibyte_string (pname_buf));
9307 #endif /* WINDOWSNT */
9310 /* Equivalent of strerror for W32 error codes. */
9311 char *
9312 w32_strerror (int error_no)
9314 static char buf[500];
9315 DWORD ret;
9317 if (error_no == 0)
9318 error_no = GetLastError ();
9320 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
9321 FORMAT_MESSAGE_IGNORE_INSERTS,
9322 NULL,
9323 error_no,
9324 0, /* choose most suitable language */
9325 buf, sizeof (buf), NULL);
9327 while (ret > 0 && (buf[ret - 1] == '\n' ||
9328 buf[ret - 1] == '\r' ))
9329 --ret;
9330 buf[ret] = '\0';
9331 if (!ret)
9332 sprintf (buf, "w32 error %d", error_no);
9334 return buf;
9337 /* For convenience when debugging. (You cannot call GetLastError
9338 directly from GDB: it will crash, because it uses the __stdcall
9339 calling convention, not the _cdecl convention assumed by GDB.) */
9340 DWORD w32_last_error (void);
9342 DWORD
9343 w32_last_error (void)
9345 return GetLastError ();
9348 /* Cache information describing the NT system for later use. */
9349 void
9350 cache_system_info (void)
9352 union
9354 struct info
9356 char major;
9357 char minor;
9358 short platform;
9359 } info;
9360 DWORD data;
9361 } version;
9363 /* Cache the module handle of Emacs itself. */
9364 hinst = GetModuleHandle (NULL);
9366 /* Cache the version of the operating system. */
9367 version.data = GetVersion ();
9368 w32_major_version = version.info.major;
9369 w32_minor_version = version.info.minor;
9371 if (version.info.platform & 0x8000)
9372 os_subtype = OS_9X;
9373 else
9374 os_subtype = OS_NT;
9376 /* Cache page size, allocation unit, processor type, etc. */
9377 GetSystemInfo (&sysinfo_cache);
9378 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
9380 /* Cache os info. */
9381 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
9382 GetVersionEx (&osinfo_cache);
9384 w32_build_number = osinfo_cache.dwBuildNumber;
9385 if (os_subtype == OS_9X)
9386 w32_build_number &= 0xffff;
9388 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
9391 #ifdef EMACSDEBUG
9392 void
9393 _DebPrint (const char *fmt, ...)
9395 char buf[1024];
9396 va_list args;
9398 va_start (args, fmt);
9399 vsprintf (buf, fmt, args);
9400 va_end (args);
9401 #if CYGWIN
9402 fprintf (stderr, "%s", buf);
9403 #endif
9404 OutputDebugString (buf);
9406 #endif
9409 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
9411 int cur_state = (GetKeyState (vk_code) & 1);
9413 if (NILP (new_state)
9414 || (NUMBERP (new_state)
9415 && ((XUINT (new_state)) & 1) != cur_state))
9417 #ifdef WINDOWSNT
9418 faked_key = vk_code;
9419 #endif /* WINDOWSNT */
9421 keybd_event ((BYTE) vk_code,
9422 (BYTE) MapVirtualKey (vk_code, 0),
9423 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9424 keybd_event ((BYTE) vk_code,
9425 (BYTE) MapVirtualKey (vk_code, 0),
9426 KEYEVENTF_EXTENDEDKEY | 0, 0);
9427 keybd_event ((BYTE) vk_code,
9428 (BYTE) MapVirtualKey (vk_code, 0),
9429 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9430 cur_state = !cur_state;
9433 return cur_state;
9436 /* Translate console modifiers to emacs modifiers.
9437 German keyboard support (Kai Morgan Zeise 2/18/95). */
9439 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
9441 int retval = 0;
9443 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
9444 pressed, first remove those modifiers. */
9445 if (!NILP (Vw32_recognize_altgr)
9446 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9447 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9448 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
9450 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
9451 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
9453 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9455 retval |= ctrl_modifier;
9456 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9457 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9458 retval |= meta_modifier;
9461 if (mods & LEFT_WIN_PRESSED)
9462 retval |= w32_key_to_modifier (VK_LWIN);
9463 if (mods & RIGHT_WIN_PRESSED)
9464 retval |= w32_key_to_modifier (VK_RWIN);
9465 if (mods & APPS_PRESSED)
9466 retval |= w32_key_to_modifier (VK_APPS);
9467 if (mods & SCROLLLOCK_ON)
9468 retval |= w32_key_to_modifier (VK_SCROLL);
9470 /* Just in case someone wanted the original behavior, make it
9471 optional by setting w32-capslock-is-shiftlock to t. */
9472 if (NILP (Vw32_capslock_is_shiftlock)
9473 /* Keys that should _not_ be affected by CapsLock. */
9474 && ( (key == VK_BACK)
9475 || (key == VK_TAB)
9476 || (key == VK_CLEAR)
9477 || (key == VK_RETURN)
9478 || (key == VK_ESCAPE)
9479 || ((key >= VK_SPACE) && (key <= VK_HELP))
9480 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
9481 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
9484 /* Only consider shift state. */
9485 if ((mods & SHIFT_PRESSED) != 0)
9486 retval |= shift_modifier;
9488 else
9490 /* Ignore CapsLock state if not enabled. */
9491 if (NILP (Vw32_enable_caps_lock))
9492 mods &= ~CAPSLOCK_ON;
9493 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
9494 retval |= shift_modifier;
9497 return retval;
9500 /* The return code indicates key code size. cpID is the codepage to
9501 use for translation to Unicode; -1 means use the current console
9502 input codepage. */
9504 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
9506 unsigned int key_code = event->wVirtualKeyCode;
9507 unsigned int mods = event->dwControlKeyState;
9508 BYTE keystate[256];
9509 static BYTE ansi_code[4];
9510 static int isdead = 0;
9512 if (isdead == 2)
9514 event->uChar.AsciiChar = ansi_code[2];
9515 isdead = 0;
9516 return 1;
9518 if (event->uChar.AsciiChar != 0)
9519 return 1;
9521 memset (keystate, 0, sizeof (keystate));
9522 keystate[key_code] = 0x80;
9523 if (mods & SHIFT_PRESSED)
9524 keystate[VK_SHIFT] = 0x80;
9525 if (mods & CAPSLOCK_ON)
9526 keystate[VK_CAPITAL] = 1;
9527 /* If we recognize right-alt and left-ctrl as AltGr, set the key
9528 states accordingly before invoking ToAscii. */
9529 if (!NILP (Vw32_recognize_altgr)
9530 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
9532 keystate[VK_CONTROL] = 0x80;
9533 keystate[VK_LCONTROL] = 0x80;
9534 keystate[VK_MENU] = 0x80;
9535 keystate[VK_RMENU] = 0x80;
9538 #if 0
9539 /* Because of an OS bug, ToAscii corrupts the stack when called to
9540 convert a dead key in console mode on NT4. Unfortunately, trying
9541 to check for dead keys using MapVirtualKey doesn't work either -
9542 these functions apparently use internal information about keyboard
9543 layout which doesn't get properly updated in console programs when
9544 changing layout (though apparently it gets partly updated,
9545 otherwise ToAscii wouldn't crash). */
9546 if (is_dead_key (event->wVirtualKeyCode))
9547 return 0;
9548 #endif
9550 /* On NT, call ToUnicode instead and then convert to the current
9551 console input codepage. */
9552 if (os_subtype == OS_NT)
9554 WCHAR buf[128];
9556 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
9557 keystate, buf, 128, 0);
9558 if (isdead > 0)
9560 /* When we are called from the GUI message processing code,
9561 we are passed the current keyboard codepage, a positive
9562 number, to use below. */
9563 if (cpId == -1)
9564 cpId = GetConsoleCP ();
9566 event->uChar.UnicodeChar = buf[isdead - 1];
9567 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
9568 (LPSTR)ansi_code, 4, NULL, NULL);
9570 else
9571 isdead = 0;
9573 else
9575 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
9576 keystate, (LPWORD) ansi_code, 0);
9579 if (isdead == 0)
9580 return 0;
9581 event->uChar.AsciiChar = ansi_code[0];
9582 return isdead;
9586 void
9587 w32_sys_ring_bell (struct frame *f)
9589 if (sound_type == 0xFFFFFFFF)
9591 Beep (666, 100);
9593 else if (sound_type == MB_EMACS_SILENT)
9595 /* Do nothing. */
9597 else
9598 MessageBeep (sound_type);
9601 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
9602 0, 0, 0,
9603 doc: /* Return non-nil when a menu-bar menu is being used.
9604 Internal use only. */)
9605 (void)
9607 return menubar_in_use ? Qt : Qnil;
9610 #if defined WINDOWSNT && !defined HAVE_DBUS
9612 /***********************************************************************
9613 Tray notifications
9614 ***********************************************************************/
9615 /* A private struct declaration to avoid compile-time limits. */
9616 typedef struct MY_NOTIFYICONDATAW {
9617 DWORD cbSize;
9618 HWND hWnd;
9619 UINT uID;
9620 UINT uFlags;
9621 UINT uCallbackMessage;
9622 HICON hIcon;
9623 WCHAR szTip[128];
9624 DWORD dwState;
9625 DWORD dwStateMask;
9626 WCHAR szInfo[256];
9627 _ANONYMOUS_UNION union {
9628 UINT uTimeout;
9629 UINT uVersion;
9630 } DUMMYUNIONNAME;
9631 WCHAR szInfoTitle[64];
9632 DWORD dwInfoFlags;
9633 GUID guidItem;
9634 HICON hBalloonIcon;
9635 } MY_NOTIFYICONDATAW;
9637 #define MYNOTIFYICONDATAW_V1_SIZE offsetof (MY_NOTIFYICONDATAW, szTip[64])
9638 #define MYNOTIFYICONDATAW_V2_SIZE offsetof (MY_NOTIFYICONDATAW, guidItem)
9639 #define MYNOTIFYICONDATAW_V3_SIZE offsetof (MY_NOTIFYICONDATAW, hBalloonIcon)
9640 #ifndef NIF_INFO
9641 # define NIF_INFO 0x00000010
9642 #endif
9643 #ifndef NIIF_NONE
9644 # define NIIF_NONE 0x00000000
9645 #endif
9646 #ifndef NIIF_INFO
9647 # define NIIF_INFO 0x00000001
9648 #endif
9649 #ifndef NIIF_WARNING
9650 # define NIIF_WARNING 0x00000002
9651 #endif
9652 #ifndef NIIF_ERROR
9653 # define NIIF_ERROR 0x00000003
9654 #endif
9657 #define EMACS_TRAY_NOTIFICATION_ID 42 /* arbitrary */
9658 #define EMACS_NOTIFICATION_MSG (WM_APP + 1)
9660 enum NI_Severity {
9661 Ni_None,
9662 Ni_Info,
9663 Ni_Warn,
9664 Ni_Err
9667 /* Report the version of a DLL given by its name. The return value is
9668 constructed using MAKEDLLVERULL. */
9669 static ULONGLONG
9670 get_dll_version (const char *dll_name)
9672 ULONGLONG version = 0;
9673 HINSTANCE hdll = LoadLibrary (dll_name);
9675 if (hdll)
9677 DLLGETVERSIONPROC pDllGetVersion
9678 = (DLLGETVERSIONPROC) GetProcAddress (hdll, "DllGetVersion");
9680 if (pDllGetVersion)
9682 DLLVERSIONINFO dvi;
9683 HRESULT result;
9685 memset (&dvi, 0, sizeof(dvi));
9686 dvi.cbSize = sizeof(dvi);
9687 result = pDllGetVersion (&dvi);
9688 if (SUCCEEDED (result))
9689 version = MAKEDLLVERULL (dvi.dwMajorVersion, dvi.dwMinorVersion,
9690 0, 0);
9692 FreeLibrary (hdll);
9695 return version;
9698 /* Return the number of bytes in UTF-8 encoded string STR that
9699 corresponds to at most LIM characters. If STR ends before LIM
9700 characters, return the number of bytes in STR including the
9701 terminating null byte. */
9702 static int
9703 utf8_mbslen_lim (const char *str, int lim)
9705 const char *p = str;
9706 int mblen = 0, nchars = 0;
9708 while (*p && nchars < lim)
9710 int nbytes = CHAR_BYTES (*p);
9712 mblen += nbytes;
9713 nchars++;
9714 p += nbytes;
9717 if (!*p && nchars < lim)
9718 mblen++;
9720 return mblen;
9723 /* Low-level subroutine to show tray notifications. All strings are
9724 supposed to be unibyte UTF-8 encoded by the caller. */
9725 static EMACS_INT
9726 add_tray_notification (struct frame *f, const char *icon, const char *tip,
9727 enum NI_Severity severity, unsigned timeout,
9728 const char *title, const char *msg)
9730 EMACS_INT retval = EMACS_TRAY_NOTIFICATION_ID;
9732 if (FRAME_W32_P (f))
9734 MY_NOTIFYICONDATAW nidw;
9735 ULONGLONG shell_dll_version = get_dll_version ("Shell32.dll");
9736 wchar_t tipw[128], msgw[256], titlew[64];
9737 int tiplen;
9739 memset (&nidw, 0, sizeof(nidw));
9741 /* MSDN says the full struct is supported since Vista, whose
9742 Shell32.dll version is said to be 6.0.6. But DllGetVersion
9743 cannot report the 3rd field value, it reports "build number"
9744 instead, which is something else. So we use the Windows 7's
9745 version 6.1 as cutoff, and Vista loses. (Actually, the loss
9746 is not a real one, since we don't expose the hBalloonIcon
9747 member of the struct to Lisp.) */
9748 if (shell_dll_version >= MAKEDLLVERULL (6, 1, 0, 0)) /* >= Windows 7 */
9749 nidw.cbSize = sizeof (nidw);
9750 else if (shell_dll_version >= MAKEDLLVERULL (6, 0, 0, 0)) /* XP */
9751 nidw.cbSize = MYNOTIFYICONDATAW_V3_SIZE;
9752 else if (shell_dll_version >= MAKEDLLVERULL (5, 0, 0, 0)) /* W2K */
9753 nidw.cbSize = MYNOTIFYICONDATAW_V2_SIZE;
9754 else
9755 nidw.cbSize = MYNOTIFYICONDATAW_V1_SIZE; /* < W2K */
9756 nidw.hWnd = FRAME_W32_WINDOW (f);
9757 nidw.uID = EMACS_TRAY_NOTIFICATION_ID;
9758 nidw.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO;
9759 nidw.uCallbackMessage = EMACS_NOTIFICATION_MSG;
9760 if (!*icon)
9761 nidw.hIcon = LoadIcon (hinst, EMACS_CLASS);
9762 else
9764 if (w32_unicode_filenames)
9766 wchar_t icon_w[MAX_PATH];
9768 if (filename_to_utf16 (icon, icon_w) != 0)
9770 errno = ENOENT;
9771 return -1;
9773 nidw.hIcon = LoadImageW (NULL, icon_w, IMAGE_ICON, 0, 0,
9774 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9776 else
9778 char icon_a[MAX_PATH];
9780 if (filename_to_ansi (icon, icon_a) != 0)
9782 errno = ENOENT;
9783 return -1;
9785 nidw.hIcon = LoadImageA (NULL, icon_a, IMAGE_ICON, 0, 0,
9786 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9789 if (!nidw.hIcon)
9791 switch (GetLastError ())
9793 case ERROR_FILE_NOT_FOUND:
9794 errno = ENOENT;
9795 break;
9796 default:
9797 errno = ENOMEM;
9798 break;
9800 return -1;
9803 /* Windows 9X and NT4 support only 64 characters in the Tip,
9804 later versions support up to 128. */
9805 if (nidw.cbSize == MYNOTIFYICONDATAW_V1_SIZE)
9807 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9808 tip, utf8_mbslen_lim (tip, 63),
9809 tipw, 64);
9810 if (tiplen >= 63)
9811 tipw[63] = 0;
9813 else
9815 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9816 tip, utf8_mbslen_lim (tip, 127),
9817 tipw, 128);
9818 if (tiplen >= 127)
9819 tipw[127] = 0;
9821 if (tiplen == 0)
9823 errno = EINVAL;
9824 retval = -1;
9825 goto done;
9827 wcscpy (nidw.szTip, tipw);
9829 /* The rest of the structure is only supported since Windows 2000. */
9830 if (nidw.cbSize > MYNOTIFYICONDATAW_V1_SIZE)
9832 int slen;
9834 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9835 msg, utf8_mbslen_lim (msg, 255),
9836 msgw, 256);
9837 if (slen >= 255)
9838 msgw[255] = 0;
9839 else if (slen == 0)
9841 errno = EINVAL;
9842 retval = -1;
9843 goto done;
9845 wcscpy (nidw.szInfo, msgw);
9846 nidw.uTimeout = timeout;
9847 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9848 title, utf8_mbslen_lim (title, 63),
9849 titlew, 64);
9850 if (slen >= 63)
9851 titlew[63] = 0;
9852 else if (slen == 0)
9854 errno = EINVAL;
9855 retval = -1;
9856 goto done;
9858 wcscpy (nidw.szInfoTitle, titlew);
9860 switch (severity)
9862 case Ni_None:
9863 nidw.dwInfoFlags = NIIF_NONE;
9864 break;
9865 case Ni_Info:
9866 default:
9867 nidw.dwInfoFlags = NIIF_INFO;
9868 break;
9869 case Ni_Warn:
9870 nidw.dwInfoFlags = NIIF_WARNING;
9871 break;
9872 case Ni_Err:
9873 nidw.dwInfoFlags = NIIF_ERROR;
9874 break;
9878 if (!Shell_NotifyIconW (NIM_ADD, (PNOTIFYICONDATAW)&nidw))
9880 /* GetLastError returns meaningless results when
9881 Shell_NotifyIcon fails. */
9882 DebPrint (("Shell_NotifyIcon ADD failed (err=%d)\n",
9883 GetLastError ()));
9884 errno = EINVAL;
9885 retval = -1;
9887 done:
9888 if (*icon && !DestroyIcon (nidw.hIcon))
9889 DebPrint (("DestroyIcon failed (err=%d)\n", GetLastError ()));
9891 return retval;
9894 /* Low-level subroutine to remove a tray notification. Note: we only
9895 pass the minimum data about the notification: its ID and the handle
9896 of the window to which it sends messages. MSDN doesn't say this is
9897 enough, but it works in practice. This allows us to avoid keeping
9898 the notification data around after we show the notification. */
9899 static void
9900 delete_tray_notification (struct frame *f, int id)
9902 if (FRAME_W32_P (f))
9904 MY_NOTIFYICONDATAW nidw;
9906 memset (&nidw, 0, sizeof(nidw));
9907 nidw.hWnd = FRAME_W32_WINDOW (f);
9908 nidw.uID = id;
9910 if (!Shell_NotifyIconW (NIM_DELETE, (PNOTIFYICONDATAW)&nidw))
9912 /* GetLastError returns meaningless results when
9913 Shell_NotifyIcon fails. */
9914 DebPrint (("Shell_NotifyIcon DELETE failed\n"));
9915 errno = EINVAL;
9916 return;
9919 return;
9922 DEFUN ("w32-notification-notify",
9923 Fw32_notification_notify, Sw32_notification_notify,
9924 0, MANY, 0,
9925 doc: /* Display an MS-Windows tray notification as specified by PARAMS.
9927 Value is the integer unique ID of the notification that can be used
9928 to remove the notification using `w32-notification-close', which see.
9929 If the function fails, the return value is nil.
9931 Tray notifications, a.k.a. \"taskbar messages\", are messages that
9932 inform the user about events unrelated to the current user activity,
9933 such as a significant system event, by briefly displaying informative
9934 text in a balloon from an icon in the notification area of the taskbar.
9936 Parameters in PARAMS are specified as keyword/value pairs. All the
9937 parameters are optional, but if no parameters are specified, the
9938 function will do nothing and return nil.
9940 The following parameters are supported:
9942 :icon ICON -- Display ICON in the system tray. If ICON is a string,
9943 it should specify a file name from which to load the
9944 icon; the specified file should be a .ico Windows icon
9945 file. If ICON is not a string, or if this parameter
9946 is not specified, the standard Emacs icon will be used.
9948 :tip TIP -- Use TIP as the tooltip for the notification. If TIP
9949 is a string, this is the text of a tooltip that will
9950 be shown when the mouse pointer hovers over the tray
9951 icon added by the notification. If TIP is not a
9952 string, or if this parameter is not specified, the
9953 default tooltip text is \"Emacs notification\". The
9954 tooltip text can be up to 127 characters long (63
9955 on Windows versions before W2K). Longer strings
9956 will be truncated.
9958 :level LEVEL -- Notification severity level, one of `info',
9959 `warning', or `error'. If given, the value
9960 determines the icon displayed to the left of the
9961 notification title, but only if the `:title'
9962 parameter (see below) is also specified and is a
9963 string.
9965 :title TITLE -- The title of the notification. If TITLE is a string,
9966 it is displayed in a larger font immediately above
9967 the body text. The title text can be up to 63
9968 characters long; longer text will be truncated.
9970 :body BODY -- The body of the notification. If BODY is a string,
9971 it specifies the text of the notification message.
9972 Use embedded newlines to control how the text is
9973 broken into lines. The body text can be up to 255
9974 characters long, and will be truncated if it's longer.
9976 Note that versions of Windows before W2K support only `:icon' and `:tip'.
9977 You can pass the other parameters, but they will be ignored on those
9978 old systems.
9980 There can be at most one active notification at any given time. An
9981 active notification must be removed by calling `w32-notification-close'
9982 before a new one can be shown.
9984 usage: (w32-notification-notify &rest PARAMS) */)
9985 (ptrdiff_t nargs, Lisp_Object *args)
9987 struct frame *f = SELECTED_FRAME ();
9988 Lisp_Object arg_plist, lres;
9989 EMACS_INT retval;
9990 char *icon, *tip, *title, *msg;
9991 enum NI_Severity severity;
9992 unsigned timeout = 0;
9994 if (nargs == 0)
9995 return Qnil;
9997 arg_plist = Flist (nargs, args);
9999 /* Icon. */
10000 lres = Fplist_get (arg_plist, QCicon);
10001 if (STRINGP (lres))
10002 icon = SSDATA (ENCODE_FILE (Fexpand_file_name (lres, Qnil)));
10003 else
10004 icon = (char *)"";
10006 /* Tip. */
10007 lres = Fplist_get (arg_plist, QCtip);
10008 if (STRINGP (lres))
10009 tip = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10010 else
10011 tip = (char *)"Emacs notification";
10013 /* Severity. */
10014 lres = Fplist_get (arg_plist, QClevel);
10015 if (NILP (lres))
10016 severity = Ni_None;
10017 else if (EQ (lres, Qinfo))
10018 severity = Ni_Info;
10019 else if (EQ (lres, Qwarning))
10020 severity = Ni_Warn;
10021 else if (EQ (lres, Qerror))
10022 severity = Ni_Err;
10023 else
10024 severity = Ni_Info;
10026 /* Title. */
10027 lres = Fplist_get (arg_plist, QCtitle);
10028 if (STRINGP (lres))
10029 title = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10030 else
10031 title = (char *)"";
10033 /* Notification body text. */
10034 lres = Fplist_get (arg_plist, QCbody);
10035 if (STRINGP (lres))
10036 msg = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10037 else
10038 msg = (char *)"";
10040 /* Do it! */
10041 retval = add_tray_notification (f, icon, tip, severity, timeout, title, msg);
10042 return (retval < 0 ? Qnil : make_number (retval));
10045 DEFUN ("w32-notification-close",
10046 Fw32_notification_close, Sw32_notification_close,
10047 1, 1, 0,
10048 doc: /* Remove the MS-Windows tray notification specified by its ID. */)
10049 (Lisp_Object id)
10051 struct frame *f = SELECTED_FRAME ();
10053 if (INTEGERP (id))
10054 delete_tray_notification (f, XINT (id));
10056 return Qnil;
10059 #endif /* WINDOWSNT && !HAVE_DBUS */
10062 /***********************************************************************
10063 Initialization
10064 ***********************************************************************/
10066 /* Keep this list in the same order as frame_parms in frame.c.
10067 Use 0 for unsupported frame parameters. */
10069 frame_parm_handler w32_frame_parm_handlers[] =
10071 x_set_autoraise,
10072 x_set_autolower,
10073 x_set_background_color,
10074 x_set_border_color,
10075 x_set_border_width,
10076 x_set_cursor_color,
10077 x_set_cursor_type,
10078 x_set_font,
10079 x_set_foreground_color,
10080 x_set_icon_name,
10081 x_set_icon_type,
10082 x_set_internal_border_width,
10083 x_set_right_divider_width,
10084 x_set_bottom_divider_width,
10085 x_set_menu_bar_lines,
10086 x_set_mouse_color,
10087 x_explicitly_set_name,
10088 x_set_scroll_bar_width,
10089 x_set_scroll_bar_height,
10090 x_set_title,
10091 x_set_unsplittable,
10092 x_set_vertical_scroll_bars,
10093 x_set_horizontal_scroll_bars,
10094 x_set_visibility,
10095 x_set_tool_bar_lines,
10096 0, /* x_set_scroll_bar_foreground, */
10097 0, /* x_set_scroll_bar_background, */
10098 x_set_screen_gamma,
10099 x_set_line_spacing,
10100 x_set_left_fringe,
10101 x_set_right_fringe,
10102 0, /* x_set_wait_for_wm, */
10103 x_set_fullscreen,
10104 x_set_font_backend,
10105 x_set_alpha,
10106 0, /* x_set_sticky */
10107 0, /* x_set_tool_bar_position */
10108 0, /* x_set_inhibit_double_buffering */
10109 x_set_undecorated,
10110 x_set_parent_frame,
10111 x_set_skip_taskbar,
10112 x_set_no_focus_on_map,
10113 x_set_no_accept_focus,
10114 x_set_z_group,
10115 0, /* x_set_override_redirect */
10116 x_set_no_special_glyphs,
10119 void
10120 syms_of_w32fns (void)
10122 globals_of_w32fns ();
10123 track_mouse_window = NULL;
10125 w32_visible_system_caret_hwnd = NULL;
10127 DEFSYM (Qundefined_color, "undefined-color");
10128 DEFSYM (Qcancel_timer, "cancel-timer");
10129 DEFSYM (Qhyper, "hyper");
10130 DEFSYM (Qsuper, "super");
10131 DEFSYM (Qmeta, "meta");
10132 DEFSYM (Qalt, "alt");
10133 DEFSYM (Qctrl, "ctrl");
10134 DEFSYM (Qcontrol, "control");
10135 DEFSYM (Qshift, "shift");
10136 DEFSYM (Qfont_parameter, "font-parameter");
10137 DEFSYM (Qgeometry, "geometry");
10138 DEFSYM (Qworkarea, "workarea");
10139 DEFSYM (Qmm_size, "mm-size");
10140 DEFSYM (Qframes, "frames");
10141 DEFSYM (Qtip_frame, "tip-frame");
10142 DEFSYM (Qassq_delete_all, "assq-delete-all");
10143 DEFSYM (Qunicode_sip, "unicode-sip");
10144 #if defined WINDOWSNT && !defined HAVE_DBUS
10145 DEFSYM (QCicon, ":icon");
10146 DEFSYM (QCtip, ":tip");
10147 DEFSYM (QClevel, ":level");
10148 DEFSYM (Qinfo, "info");
10149 DEFSYM (Qwarning, "warning");
10150 DEFSYM (QCtitle, ":title");
10151 DEFSYM (QCbody, ":body");
10152 #endif
10154 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
10155 DEFSYM (Qgnutls, "gnutls");
10156 DEFSYM (Qlibxml2, "libxml2");
10157 DEFSYM (Qserif, "serif");
10158 DEFSYM (Qzlib, "zlib");
10159 DEFSYM (Qlcms2, "lcms2");
10160 DEFSYM (Qjson, "json");
10162 Fput (Qundefined_color, Qerror_conditions,
10163 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
10164 Fput (Qundefined_color, Qerror_message,
10165 build_pure_c_string ("Undefined color"));
10167 staticpro (&w32_grabbed_keys);
10168 w32_grabbed_keys = Qnil;
10170 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
10171 doc: /* An array of color name mappings for Windows. */);
10172 Vw32_color_map = Qnil;
10174 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
10175 doc: /* Non-nil if Alt key presses are passed on to Windows.
10176 When non-nil, for example, Alt pressed and released and then space will
10177 open the System menu. When nil, Emacs processes the Alt key events, and
10178 then silently swallows them. */);
10179 Vw32_pass_alt_to_system = Qnil;
10181 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
10182 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
10183 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
10184 Vw32_alt_is_meta = Qt;
10186 DEFVAR_INT ("w32-quit-key", w32_quit_key,
10187 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
10188 w32_quit_key = 0;
10190 DEFVAR_LISP ("w32-pass-lwindow-to-system",
10191 Vw32_pass_lwindow_to_system,
10192 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
10194 When non-nil, the Start menu is opened by tapping the key.
10195 If you set this to nil, the left \"Windows\" key is processed by Emacs
10196 according to the value of `w32-lwindow-modifier', which see.
10198 Note that some combinations of the left \"Windows\" key with other
10199 keys are caught by Windows at low level. For example, <lwindow>-r
10200 pops up the Windows Run dialog, <lwindow>-<Pause> pops up the "System
10201 Properties" dialog, etc. On Windows 10, no \"Windows\" key
10202 combinations are normally handed to applications. To enable Emacs to
10203 process \"Windows\" key combinations, use the function
10204 `w32-register-hot-key`.
10206 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
10207 Vw32_pass_lwindow_to_system = Qt;
10209 DEFVAR_LISP ("w32-pass-rwindow-to-system",
10210 Vw32_pass_rwindow_to_system,
10211 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
10213 When non-nil, the Start menu is opened by tapping the key.
10214 If you set this to nil, the right \"Windows\" key is processed by Emacs
10215 according to the value of `w32-rwindow-modifier', which see.
10217 Note that some combinations of the right \"Windows\" key with other
10218 keys are caught by Windows at low level. For example, <rwindow>-r
10219 pops up the Windows Run dialog, <rwindow>-<Pause> pops up the "System
10220 Properties" dialog, etc. On Windows 10, no \"Windows\" key
10221 combinations are normally handed to applications. To enable Emacs to
10222 process \"Windows\" key combinations, use the function
10223 `w32-register-hot-key`.
10225 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
10226 Vw32_pass_rwindow_to_system = Qt;
10228 DEFVAR_LISP ("w32-phantom-key-code",
10229 Vw32_phantom_key_code,
10230 doc: /* Virtual key code used to generate \"phantom\" key presses.
10231 Value is a number between 0 and 255.
10233 Phantom key presses are generated in order to stop the system from
10234 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
10235 `w32-pass-rwindow-to-system' is nil.
10237 This variable is only used on Windows 98 and ME. For other Windows
10238 versions, see the documentation of the `w32-register-hot-key`
10239 function. */);
10240 /* Although 255 is technically not a valid key code, it works and
10241 means that this hack won't interfere with any real key code. */
10242 XSETINT (Vw32_phantom_key_code, 255);
10244 DEFVAR_LISP ("w32-enable-num-lock",
10245 Vw32_enable_num_lock,
10246 doc: /* If non-nil, the Num Lock key acts normally.
10247 Set to nil to handle Num Lock as the `kp-numlock' key. */);
10248 Vw32_enable_num_lock = Qt;
10250 DEFVAR_LISP ("w32-enable-caps-lock",
10251 Vw32_enable_caps_lock,
10252 doc: /* If non-nil, the Caps Lock key acts normally.
10253 Set to nil to handle Caps Lock as the `capslock' key. */);
10254 Vw32_enable_caps_lock = Qt;
10256 DEFVAR_LISP ("w32-scroll-lock-modifier",
10257 Vw32_scroll_lock_modifier,
10258 doc: /* Modifier to use for the Scroll Lock ON state.
10259 The value can be hyper, super, meta, alt, control or shift for the
10260 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
10261 Any other value will cause the Scroll Lock key to be ignored by Emacs,
10262 and it will have the same effect as in other applications. */);
10263 Vw32_scroll_lock_modifier = Qnil;
10265 DEFVAR_LISP ("w32-lwindow-modifier",
10266 Vw32_lwindow_modifier,
10267 doc: /* Modifier to use for the left \"Windows\" key.
10268 The value can be hyper, super, meta, alt, control or shift for the
10269 respective modifier, or nil to appear as the `lwindow' key.
10270 Any other value will cause the key to be ignored.
10272 Also see the documentation of the `w32-register-hot-key` function. */);
10273 Vw32_lwindow_modifier = Qnil;
10275 DEFVAR_LISP ("w32-rwindow-modifier",
10276 Vw32_rwindow_modifier,
10277 doc: /* Modifier to use for the right \"Windows\" key.
10278 The value can be hyper, super, meta, alt, control or shift for the
10279 respective modifier, or nil to appear as the `rwindow' key.
10280 Any other value will cause the key to be ignored.
10282 Also see the documentation of the `w32-register-hot-key` function. */);
10283 Vw32_rwindow_modifier = Qnil;
10285 DEFVAR_LISP ("w32-apps-modifier",
10286 Vw32_apps_modifier,
10287 doc: /* Modifier to use for the \"Apps\" key.
10288 The value can be hyper, super, meta, alt, control or shift for the
10289 respective modifier, or nil to appear as the `apps' key.
10290 Any other value will cause the key to be ignored. */);
10291 Vw32_apps_modifier = Qnil;
10293 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
10294 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
10295 w32_enable_synthesized_fonts = 0;
10297 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
10298 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
10299 Vw32_enable_palette = Qt;
10301 DEFVAR_INT ("w32-mouse-button-tolerance",
10302 w32_mouse_button_tolerance,
10303 doc: /* Analogue of double click interval for faking middle mouse events.
10304 The value is the minimum time in milliseconds that must elapse between
10305 left and right button down events before they are considered distinct events.
10306 If both mouse buttons are depressed within this interval, a middle mouse
10307 button down event is generated instead. */);
10308 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
10310 DEFVAR_INT ("w32-mouse-move-interval",
10311 w32_mouse_move_interval,
10312 doc: /* Minimum interval between mouse move events.
10313 The value is the minimum time in milliseconds that must elapse between
10314 successive mouse move (or scroll bar drag) events before they are
10315 reported as lisp events. */);
10316 w32_mouse_move_interval = 0;
10318 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
10319 w32_pass_extra_mouse_buttons_to_system,
10320 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
10321 Recent versions of Windows support mice with up to five buttons.
10322 Since most applications don't support these extra buttons, most mouse
10323 drivers will allow you to map them to functions at the system level.
10324 If this variable is non-nil, Emacs will pass them on, allowing the
10325 system to handle them. */);
10326 w32_pass_extra_mouse_buttons_to_system = 0;
10328 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
10329 w32_pass_multimedia_buttons_to_system,
10330 doc: /* If non-nil, media buttons are passed to Windows.
10331 Some modern keyboards contain buttons for controlling media players, web
10332 browsers and other applications. Generally these buttons are handled on a
10333 system wide basis, but by setting this to nil they are made available
10334 to Emacs for binding. Depending on your keyboard, additional keys that
10335 may be available are:
10337 browser-back, browser-forward, browser-refresh, browser-stop,
10338 browser-search, browser-favorites, browser-home,
10339 mail, mail-reply, mail-forward, mail-send,
10340 app-1, app-2,
10341 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
10342 spell-check, correction-list, toggle-dictate-command,
10343 media-next, media-previous, media-stop, media-play-pause, media-select,
10344 media-play, media-pause, media-record, media-fast-forward, media-rewind,
10345 media-channel-up, media-channel-down,
10346 volume-mute, volume-up, volume-down,
10347 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
10348 bass-down, bass-boost, bass-up, treble-down, treble-up */);
10349 w32_pass_multimedia_buttons_to_system = 1;
10351 #if 0 /* TODO: Mouse cursor customization. */
10352 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
10353 doc: /* SKIP: real doc in xfns.c. */);
10354 Vx_pointer_shape = Qnil;
10356 Vx_nontext_pointer_shape = Qnil;
10358 Vx_mode_pointer_shape = Qnil;
10360 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
10361 doc: /* SKIP: real doc in xfns.c. */);
10362 Vx_hourglass_pointer_shape = Qnil;
10364 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
10365 Vx_sensitive_text_pointer_shape,
10366 doc: /* SKIP: real doc in xfns.c. */);
10367 Vx_sensitive_text_pointer_shape = Qnil;
10369 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
10370 Vx_window_horizontal_drag_shape,
10371 doc: /* SKIP: real doc in xfns.c. */);
10372 Vx_window_horizontal_drag_shape = Qnil;
10374 DEFVAR_LISP ("x-window-vertical-drag-cursor",
10375 Vx_window_vertical_drag_shape,
10376 doc: /* SKIP: real doc in xfns.c. */);
10377 Vx_window_vertical_drag_shape = Qnil;
10378 #endif
10380 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
10381 doc: /* SKIP: real doc in xfns.c. */);
10382 Vx_cursor_fore_pixel = Qnil;
10384 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
10385 doc: /* SKIP: real doc in xfns.c. */);
10386 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
10388 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
10389 doc: /* SKIP: real doc in xfns.c. */);
10390 /* We don't have any way to find this out, so set it to nil
10391 and maybe the user would like to set it to t. */
10392 Vx_no_window_manager = Qnil;
10394 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
10395 Vx_pixel_size_width_font_regexp,
10396 doc: /* SKIP: real doc in xfns.c. */);
10397 Vx_pixel_size_width_font_regexp = Qnil;
10399 DEFVAR_LISP ("w32-bdf-filename-alist",
10400 Vw32_bdf_filename_alist,
10401 doc: /* List of bdf fonts and their corresponding filenames. */);
10402 Vw32_bdf_filename_alist = Qnil;
10404 DEFVAR_BOOL ("w32-strict-fontnames",
10405 w32_strict_fontnames,
10406 doc: /* Non-nil means only use fonts that are exact matches for those requested.
10407 Default is nil, which allows old fontnames that are not XLFD compliant,
10408 and allows third-party CJK display to work by specifying false charset
10409 fields to trick Emacs into translating to Big5, SJIS etc.
10410 Setting this to t will prevent wrong fonts being selected when
10411 fontsets are automatically created. */);
10412 w32_strict_fontnames = 0;
10414 DEFVAR_BOOL ("w32-strict-painting",
10415 w32_strict_painting,
10416 doc: /* Non-nil means use strict rules for repainting frames.
10417 Set this to nil to get the old behavior for repainting; this should
10418 only be necessary if the default setting causes problems. */);
10419 w32_strict_painting = 1;
10421 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
10422 w32_use_fallback_wm_chars_method,
10423 doc: /* Non-nil means use old method of processing character keys.
10424 This is intended only for debugging of the new processing method.
10425 Default is nil.
10427 This variable has effect only on NT family of systems, not on Windows 9X. */);
10428 w32_use_fallback_wm_chars_method = 0;
10430 DEFVAR_BOOL ("w32-disable-new-uniscribe-apis",
10431 w32_disable_new_uniscribe_apis,
10432 doc: /* Non-nil means don't use new Uniscribe APIs.
10433 The new APIs are used to access OTF features supported by fonts.
10434 This is intended only for debugging of the new Uniscribe-related code.
10435 Default is nil.
10437 This variable has effect only on Windows Vista and later. */);
10438 w32_disable_new_uniscribe_apis = 0;
10440 DEFVAR_LISP ("w32-tooltip-extra-pixels",
10441 Vw32_tooltip_extra_pixels,
10442 doc: /* Number of pixels added after tooltip text.
10443 On Windows some fonts may cause the last character of a tooltip be
10444 truncated or wrapped around to the next line. Adding some extra space
10445 at the end of the toooltip works around this problem.
10447 This variable specifies the number of pixels that shall be added. The
10448 default value t means to add the width of one canonical character of the
10449 tip frame. */);
10450 Vw32_tooltip_extra_pixels = Qt;
10452 DEFVAR_BOOL ("w32-disable-abort-dialog",
10453 w32_disable_abort_dialog,
10454 doc: /* Non-nil means don't display the abort dialog when aborting. */);
10455 w32_disable_abort_dialog = 0;
10457 #if 0 /* TODO: Port to W32 */
10458 defsubr (&Sx_change_window_property);
10459 defsubr (&Sx_delete_window_property);
10460 defsubr (&Sx_window_property);
10461 #endif
10462 defsubr (&Sxw_display_color_p);
10463 defsubr (&Sx_display_grayscale_p);
10464 defsubr (&Sxw_color_defined_p);
10465 defsubr (&Sxw_color_values);
10466 defsubr (&Sx_server_max_request_size);
10467 defsubr (&Sx_server_vendor);
10468 defsubr (&Sx_server_version);
10469 defsubr (&Sx_display_pixel_width);
10470 defsubr (&Sx_display_pixel_height);
10471 defsubr (&Sx_display_mm_width);
10472 defsubr (&Sx_display_mm_height);
10473 defsubr (&Sx_display_screens);
10474 defsubr (&Sx_display_planes);
10475 defsubr (&Sx_display_color_cells);
10476 defsubr (&Sx_display_visual_class);
10477 defsubr (&Sx_display_backing_store);
10478 defsubr (&Sx_display_save_under);
10479 defsubr (&Sx_create_frame);
10480 defsubr (&Sx_open_connection);
10481 defsubr (&Sx_close_connection);
10482 defsubr (&Sx_display_list);
10483 defsubr (&Sw32_frame_geometry);
10484 defsubr (&Sw32_frame_edges);
10485 defsubr (&Sw32_frame_list_z_order);
10486 defsubr (&Sw32_frame_restack);
10487 defsubr (&Sw32_mouse_absolute_pixel_position);
10488 defsubr (&Sw32_set_mouse_absolute_pixel_position);
10489 defsubr (&Sx_synchronize);
10491 /* W32 specific functions */
10493 defsubr (&Sw32_define_rgb_color);
10494 defsubr (&Sw32_default_color_map);
10495 defsubr (&Sw32_display_monitor_attributes_list);
10496 defsubr (&Sw32_send_sys_command);
10497 defsubr (&Sw32_shell_execute);
10498 defsubr (&Sw32_register_hot_key);
10499 defsubr (&Sw32_unregister_hot_key);
10500 defsubr (&Sw32_registered_hot_keys);
10501 defsubr (&Sw32_reconstruct_hot_key);
10502 defsubr (&Sw32_toggle_lock_key);
10503 defsubr (&Sw32_window_exists_p);
10504 defsubr (&Sw32__menu_bar_in_use);
10505 #if defined WINDOWSNT && !defined HAVE_DBUS
10506 defsubr (&Sw32_notification_notify);
10507 defsubr (&Sw32_notification_close);
10508 #endif
10510 #ifdef WINDOWSNT
10511 defsubr (&Sfile_system_info);
10512 defsubr (&Sdefault_printer_name);
10513 #endif
10515 defsubr (&Sset_message_beep);
10516 defsubr (&Sx_show_tip);
10517 defsubr (&Sx_hide_tip);
10518 tip_timer = Qnil;
10519 staticpro (&tip_timer);
10520 tip_frame = Qnil;
10521 staticpro (&tip_frame);
10522 tip_last_frame = Qnil;
10523 staticpro (&tip_last_frame);
10524 tip_last_string = Qnil;
10525 staticpro (&tip_last_string);
10526 tip_last_parms = Qnil;
10527 staticpro (&tip_last_parms);
10529 defsubr (&Sx_file_dialog);
10530 #ifdef WINDOWSNT
10531 defsubr (&Ssystem_move_file_to_trash);
10532 #endif
10537 /* Crashing and reporting backtrace. */
10539 #ifndef CYGWIN
10540 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
10541 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
10542 #endif
10543 static DWORD except_code;
10544 static PVOID except_addr;
10546 #ifndef CYGWIN
10548 /* Stack overflow recovery. */
10550 /* MinGW headers don't declare this (should be in malloc.h). Also,
10551 the function is not present pre-W2K, so make the call through
10552 a function pointer. */
10553 typedef int (__cdecl *_resetstkoflw_proc) (void);
10554 static _resetstkoflw_proc resetstkoflw;
10556 /* Re-establish the guard page at stack limit. This is needed because
10557 when a stack overflow is detected, Windows removes the guard bit
10558 from the guard page, so if we don't re-establish that protection,
10559 the next stack overflow will cause a crash. */
10560 void
10561 w32_reset_stack_overflow_guard (void)
10563 if (resetstkoflw == NULL)
10564 resetstkoflw =
10565 (_resetstkoflw_proc)GetProcAddress (GetModuleHandle ("msvcrt.dll"),
10566 "_resetstkoflw");
10567 /* We ignore the return value. If _resetstkoflw fails, the next
10568 stack overflow will crash the program. */
10569 if (resetstkoflw != NULL)
10570 (void)resetstkoflw ();
10573 static void
10574 stack_overflow_handler (void)
10576 /* Hard GC error may lead to stack overflow caused by
10577 too nested calls to mark_object. No way to survive. */
10578 if (gc_in_progress)
10579 terminate_due_to_signal (SIGSEGV, 40);
10580 #ifdef _WIN64
10581 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
10582 __builtin_longjmp (return_to_command_loop, 1);
10583 #else
10584 sys_longjmp (return_to_command_loop, 1);
10585 #endif
10588 /* This handler records the exception code and the address where it
10589 was triggered so that this info could be included in the backtrace.
10590 Without that, the backtrace in some cases has no information
10591 whatsoever about the offending code, and looks as if the top-level
10592 exception handler in the MinGW startup code was the one that
10593 crashed. We also recover from stack overflow, by calling our stack
10594 overflow handler that jumps back to top level. */
10595 static LONG CALLBACK
10596 my_exception_handler (EXCEPTION_POINTERS * exception_data)
10598 except_code = exception_data->ExceptionRecord->ExceptionCode;
10599 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
10601 /* If this is a stack overflow exception, attempt to recover. */
10602 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
10603 && exception_data->ExceptionRecord->NumberParameters == 2
10604 /* We can only longjmp to top level from the main thread. */
10605 && GetCurrentThreadId () == dwMainThreadId)
10607 /* Call stack_overflow_handler (). */
10608 #ifdef _WIN64
10609 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
10610 #else
10611 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
10612 #endif
10613 /* Zero this out, so the stale address of the stack overflow
10614 exception we handled is not displayed in some future
10615 unrelated crash. */
10616 except_addr = 0;
10617 return EXCEPTION_CONTINUE_EXECUTION;
10620 if (prev_exception_handler)
10621 return prev_exception_handler (exception_data);
10622 return EXCEPTION_EXECUTE_HANDLER;
10624 #endif
10626 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
10627 PULONG);
10629 #define BACKTRACE_LIMIT_MAX 62
10631 static int
10632 w32_backtrace (void **buffer, int limit)
10634 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
10635 HMODULE hm_kernel32 = NULL;
10637 if (!s_pfn_CaptureStackBackTrace)
10639 hm_kernel32 = LoadLibrary ("Kernel32.dll");
10640 s_pfn_CaptureStackBackTrace =
10641 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
10642 "RtlCaptureStackBackTrace");
10644 if (s_pfn_CaptureStackBackTrace)
10645 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
10646 buffer, NULL);
10647 return 0;
10650 void
10651 emacs_abort (void)
10653 if (w32_disable_abort_dialog)
10654 abort ();
10656 int button;
10657 button = MessageBox (NULL,
10658 "A fatal error has occurred!\n\n"
10659 "Would you like to attach a debugger?\n\n"
10660 "Select:\n"
10661 "YES -- to debug Emacs, or\n"
10662 "NO -- to abort Emacs and produce a backtrace\n"
10663 " (emacs_backtrace.txt in current directory)."
10664 #if __GNUC__
10665 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
10666 "\"continue\" inside GDB before clicking YES.)"
10667 #endif
10668 , "Emacs Abort Dialog",
10669 MB_ICONEXCLAMATION | MB_TASKMODAL
10670 | MB_SETFOREGROUND | MB_YESNO);
10671 switch (button)
10673 case IDYES:
10674 DebugBreak ();
10675 exit (2); /* tell the compiler we will never return */
10676 case IDNO:
10677 default:
10679 void *stack[BACKTRACE_LIMIT_MAX + 1];
10680 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
10682 if (i)
10684 int errfile_fd = -1;
10685 int j;
10686 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
10687 /* The type below should really be 'void *', but
10688 INT_BUFSIZE_BOUND cannot handle that without
10689 triggering compiler warnings (under certain
10690 pedantic warning switches), it wants an
10691 integer type. */
10692 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
10693 #ifdef CYGWIN
10694 int stderr_fd = 2;
10695 #else
10696 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
10697 int stderr_fd = -1;
10699 if (errout && errout != INVALID_HANDLE_VALUE)
10700 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
10701 #endif
10703 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
10704 but not on Windows 7. addr2line doesn't mind a missing
10705 "0x", but will be confused by an extra one. */
10706 if (except_addr)
10707 sprintf (buf, "\r\nException 0x%x at this address:\r\n%p\r\n",
10708 (unsigned int) except_code, except_addr);
10709 if (stderr_fd >= 0)
10711 if (except_addr)
10712 write (stderr_fd, buf, strlen (buf));
10713 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
10715 #ifdef CYGWIN
10716 #define _open open
10717 #endif
10718 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
10719 if (errfile_fd >= 0)
10721 lseek (errfile_fd, 0L, SEEK_END);
10722 if (except_addr)
10723 write (errfile_fd, buf, strlen (buf));
10724 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
10727 for (j = 0; j < i; j++)
10729 /* stack[] gives the return addresses, whereas we want
10730 the address of the call, so decrease each address
10731 by approximate size of 1 CALL instruction. */
10732 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
10733 if (stderr_fd >= 0)
10734 write (stderr_fd, buf, strlen (buf));
10735 if (errfile_fd >= 0)
10736 write (errfile_fd, buf, strlen (buf));
10738 if (i == BACKTRACE_LIMIT_MAX)
10740 if (stderr_fd >= 0)
10741 write (stderr_fd, "...\r\n", 5);
10742 if (errfile_fd >= 0)
10743 write (errfile_fd, "...\r\n", 5);
10745 if (errfile_fd >= 0)
10746 close (errfile_fd);
10748 abort ();
10749 break;
10756 /* Initialization. */
10759 globals_of_w32fns is used to initialize those global variables that
10760 must always be initialized on startup even when the global variable
10761 initialized is non zero (see the function main in emacs.c).
10762 globals_of_w32fns is called from syms_of_w32fns when the global
10763 variable initialized is 0 and directly from main when initialized
10764 is non zero.
10766 void
10767 globals_of_w32fns (void)
10769 HMODULE user32_lib = GetModuleHandle ("user32.dll");
10771 TrackMouseEvent not available in all versions of Windows, so must load
10772 it dynamically. Do it once, here, instead of every time it is used.
10774 track_mouse_event_fn = (TrackMouseEvent_Proc)
10775 GetProcAddress (user32_lib, "TrackMouseEvent");
10777 monitor_from_point_fn = (MonitorFromPoint_Proc)
10778 GetProcAddress (user32_lib, "MonitorFromPoint");
10779 get_monitor_info_fn = (GetMonitorInfo_Proc)
10780 GetProcAddress (user32_lib, "GetMonitorInfoA");
10781 monitor_from_window_fn = (MonitorFromWindow_Proc)
10782 GetProcAddress (user32_lib, "MonitorFromWindow");
10783 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
10784 GetProcAddress (user32_lib, "EnumDisplayMonitors");
10785 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
10786 GetProcAddress (user32_lib, "GetTitleBarInfo");
10789 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
10790 get_composition_string_fn = (ImmGetCompositionString_Proc)
10791 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
10792 get_ime_context_fn = (ImmGetContext_Proc)
10793 GetProcAddress (imm32_lib, "ImmGetContext");
10794 release_ime_context_fn = (ImmReleaseContext_Proc)
10795 GetProcAddress (imm32_lib, "ImmReleaseContext");
10796 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
10797 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
10800 except_code = 0;
10801 except_addr = 0;
10802 #ifndef CYGWIN
10803 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
10804 resetstkoflw = NULL;
10805 #endif
10807 DEFVAR_INT ("w32-ansi-code-page",
10808 w32_ansi_code_page,
10809 doc: /* The ANSI code page used by the system. */);
10810 w32_ansi_code_page = GetACP ();
10812 if (os_subtype == OS_NT)
10813 w32_unicode_gui = 1;
10814 else
10815 w32_unicode_gui = 0;
10817 after_deadkey = -1;
10819 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
10820 InitCommonControls ();
10822 syms_of_w32uniscribe ();
10825 #ifdef NTGUI_UNICODE
10827 Lisp_Object
10828 ntgui_encode_system (Lisp_Object str)
10830 Lisp_Object encoded;
10831 to_unicode (str, &encoded);
10832 return encoded;
10835 #endif /* NTGUI_UNICODE */