Document reserved keys
[emacs.git] / src / w32fns.c
blobe50b7d5c3c3e82c752ecbd8cf7814e03850715fb
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: /* Make a new window, which is called a \"frame\" in Emacs terms.
5674 Return an Emacs frame object.
5675 PARAMETERS is an alist of frame parameters.
5676 If the parameters specify that the frame should not have a minibuffer,
5677 and do not specify a specific minibuffer window to use,
5678 then `default-minibuffer-frame' must be a frame whose minibuffer can
5679 be shared by the new frame.
5681 This function is an internal primitive--use `make-frame' instead. */)
5682 (Lisp_Object parameters)
5684 struct frame *f;
5685 Lisp_Object frame, tem;
5686 Lisp_Object name;
5687 bool minibuffer_only = false;
5688 long window_prompting = 0;
5689 ptrdiff_t count = SPECPDL_INDEX ();
5690 Lisp_Object display;
5691 struct w32_display_info *dpyinfo = NULL;
5692 Lisp_Object parent, parent_frame;
5693 struct kboard *kb;
5694 int x_width = 0, x_height = 0;
5696 if (!FRAME_W32_P (SELECTED_FRAME ())
5697 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
5698 error ("Cannot create a GUI frame in a -nw session");
5700 /* Make copy of frame parameters because the original is in pure
5701 storage now. */
5702 parameters = Fcopy_alist (parameters);
5704 /* Use this general default value to start with
5705 until we know if this frame has a specified name. */
5706 Vx_resource_name = Vinvocation_name;
5708 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
5709 if (EQ (display, Qunbound))
5710 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
5711 if (EQ (display, Qunbound))
5712 display = Qnil;
5713 dpyinfo = check_x_display_info (display);
5714 kb = dpyinfo->terminal->kboard;
5716 if (!dpyinfo->terminal->name)
5717 error ("Terminal is not live, can't create new frames on it");
5719 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5720 if (!STRINGP (name)
5721 && ! EQ (name, Qunbound)
5722 && ! NILP (name))
5723 error ("Invalid frame name--not a string or nil");
5725 if (STRINGP (name))
5726 Vx_resource_name = name;
5728 /* See if parent window is specified. */
5729 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL,
5730 RES_TYPE_NUMBER);
5731 if (EQ (parent, Qunbound))
5732 parent = Qnil;
5733 else if (!NILP (parent))
5734 CHECK_NUMBER (parent);
5736 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5737 /* No need to protect DISPLAY because that's not used after passing
5738 it to make_frame_without_minibuffer. */
5739 frame = Qnil;
5740 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5741 RES_TYPE_SYMBOL);
5742 if (EQ (tem, Qnone) || NILP (tem))
5743 f = make_frame_without_minibuffer (Qnil, kb, display);
5744 else if (EQ (tem, Qonly))
5746 f = make_minibuffer_frame ();
5747 minibuffer_only = true;
5749 else if (WINDOWP (tem))
5750 f = make_frame_without_minibuffer (tem, kb, display);
5751 else
5752 f = make_frame (true);
5754 XSETFRAME (frame, f);
5756 parent_frame = x_get_arg (dpyinfo, parameters, Qparent_frame, NULL, NULL,
5757 RES_TYPE_SYMBOL);
5758 /* Apply `parent-frame' parameter only when no `parent-id' was
5759 specified. */
5760 if (!NILP (parent_frame)
5761 && (!NILP (parent)
5762 || !FRAMEP (parent_frame)
5763 || !FRAME_LIVE_P (XFRAME (parent_frame))
5764 || !FRAME_W32_P (XFRAME (parent_frame))))
5765 parent_frame = Qnil;
5767 fset_parent_frame (f, parent_frame);
5768 store_frame_param (f, Qparent_frame, parent_frame);
5770 tem = x_get_arg (dpyinfo, parameters, Qundecorated, NULL, NULL,
5771 RES_TYPE_BOOLEAN);
5772 FRAME_UNDECORATED (f) = !NILP (tem) && !EQ (tem, Qunbound);
5773 store_frame_param (f, Qundecorated, FRAME_UNDECORATED (f) ? Qt : Qnil);
5775 tem = x_get_arg (dpyinfo, parameters, Qskip_taskbar, NULL, NULL,
5776 RES_TYPE_BOOLEAN);
5777 FRAME_SKIP_TASKBAR (f) = !NILP (tem) && !EQ (tem, Qunbound);
5778 store_frame_param (f, Qskip_taskbar,
5779 (NILP (tem) || EQ (tem, Qunbound)) ? Qnil : Qt);
5781 /* By default, make scrollbars the system standard width and height. */
5782 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5783 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5785 f->terminal = dpyinfo->terminal;
5787 f->output_method = output_w32;
5788 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5789 FRAME_FONTSET (f) = -1;
5791 fset_icon_name
5792 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5793 RES_TYPE_STRING));
5794 if (! STRINGP (f->icon_name))
5795 fset_icon_name (f, Qnil);
5797 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5799 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5800 record_unwind_protect (do_unwind_create_frame, frame);
5802 #ifdef GLYPH_DEBUG
5803 image_cache_refcount =
5804 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5805 dpyinfo_refcount = dpyinfo->reference_count;
5806 #endif /* GLYPH_DEBUG */
5808 /* Specify the parent under which to make this window - this seems to
5809 have no effect on Windows because parent_desc is explicitly reset
5810 below. */
5811 if (!NILP (parent))
5813 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5814 pointer from integer of different size. */
5815 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5816 f->output_data.w32->explicit_parent = true;
5818 else
5820 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5821 f->output_data.w32->explicit_parent = false;
5824 /* Set the name; the functions to which we pass f expect the name to
5825 be set. */
5826 if (EQ (name, Qunbound) || NILP (name))
5828 fset_name (f, build_string (dpyinfo->w32_id_name));
5829 f->explicit_name = false;
5831 else
5833 fset_name (f, name);
5834 f->explicit_name = true;
5835 /* Use the frame's title when getting resources for this frame. */
5836 specbind (Qx_resource_name, name);
5839 if (uniscribe_available)
5840 register_font_driver (&uniscribe_font_driver, f);
5841 register_font_driver (&w32font_driver, f);
5843 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5844 "fontBackend", "FontBackend", RES_TYPE_STRING);
5846 /* Extract the window parameters from the supplied values
5847 that are needed to determine window geometry. */
5848 x_default_font_parameter (f, parameters);
5850 /* Default BorderWidth to 0 to match other platforms. */
5851 x_default_parameter (f, parameters, Qborder_width, make_number (0),
5852 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5854 /* We recognize either internalBorderWidth or internalBorder
5855 (which is what xterm calls it). */
5856 if (NILP (Fassq (Qinternal_border_width, parameters)))
5858 Lisp_Object value;
5860 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5861 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5862 if (! EQ (value, Qunbound))
5863 parameters = Fcons (Fcons (Qinternal_border_width, value),
5864 parameters);
5867 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5868 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5869 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5870 NULL, NULL, RES_TYPE_NUMBER);
5871 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5872 NULL, NULL, RES_TYPE_NUMBER);
5873 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5874 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5875 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5876 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5878 /* Also do the stuff which must be set before the window exists. */
5879 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5880 "foreground", "Foreground", RES_TYPE_STRING);
5881 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5882 "background", "Background", RES_TYPE_STRING);
5883 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5884 "pointerColor", "Foreground", RES_TYPE_STRING);
5885 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5886 "borderColor", "BorderColor", RES_TYPE_STRING);
5887 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5888 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5889 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5890 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5891 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5892 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5893 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5894 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5895 x_default_parameter (f, parameters, Qno_focus_on_map, Qnil,
5896 NULL, NULL, RES_TYPE_BOOLEAN);
5897 x_default_parameter (f, parameters, Qno_accept_focus, Qnil,
5898 NULL, NULL, RES_TYPE_BOOLEAN);
5899 x_default_parameter (f, parameters, Qno_special_glyphs, Qnil,
5900 NULL, NULL, RES_TYPE_BOOLEAN);
5902 /* Process alpha here (Bug#16619). On XP this fails with child
5903 frames. For `no-focus-on-map' frames delay processing of alpha
5904 until the frame becomes visible. */
5905 if (!FRAME_NO_FOCUS_ON_MAP (f))
5906 x_default_parameter (f, parameters, Qalpha, Qnil,
5907 "alpha", "Alpha", RES_TYPE_NUMBER);
5909 /* Init faces first since we need the frame's column width/line
5910 height in various occasions. */
5911 init_frame_faces (f);
5913 /* We have to call adjust_frame_size here since otherwise
5914 x_set_tool_bar_lines will already work with the character sizes
5915 installed by init_frame_faces while the frame's pixel size is still
5916 calculated from a character size of 1 and we subsequently hit the
5917 (height >= 0) assertion in window_box_height.
5919 The non-pixelwise code apparently worked around this because it
5920 had one frame line vs one toolbar line which left us with a zero
5921 root window height which was obviously wrong as well ...
5923 Also process `min-width' and `min-height' parameters right here
5924 because `frame-windows-min-size' needs them. */
5925 tem = x_get_arg (dpyinfo, parameters, Qmin_width, NULL, NULL,
5926 RES_TYPE_NUMBER);
5927 if (NUMBERP (tem))
5928 store_frame_param (f, Qmin_width, tem);
5929 tem = x_get_arg (dpyinfo, parameters, Qmin_height, NULL, NULL,
5930 RES_TYPE_NUMBER);
5931 if (NUMBERP (tem))
5932 store_frame_param (f, Qmin_height, tem);
5933 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5934 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5935 Qx_create_frame_1);
5937 /* The X resources controlling the menu-bar and tool-bar are
5938 processed specially at startup, and reflected in the mode
5939 variables; ignore them here. */
5940 if (NILP (parent_frame))
5942 x_default_parameter (f, parameters, Qmenu_bar_lines,
5943 NILP (Vmenu_bar_mode)
5944 ? make_number (0) : make_number (1),
5945 NULL, NULL, RES_TYPE_NUMBER);
5947 else
5948 /* No menu bar for child frames. */
5949 store_frame_param (f, Qmenu_bar_lines, make_number (0));
5951 x_default_parameter (f, parameters, Qtool_bar_lines,
5952 NILP (Vtool_bar_mode)
5953 ? make_number (0) : make_number (1),
5954 NULL, NULL, RES_TYPE_NUMBER);
5956 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5957 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5958 x_default_parameter (f, parameters, Qtitle, Qnil,
5959 "title", "Title", RES_TYPE_STRING);
5961 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5962 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5963 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5964 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5965 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5966 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5967 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5968 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5969 f->output_data.w32->left_edge_cursor = w32_load_cursor (IDC_SIZEWE);
5970 f->output_data.w32->top_left_corner_cursor = w32_load_cursor (IDC_SIZENWSE);
5971 f->output_data.w32->top_edge_cursor = w32_load_cursor (IDC_SIZENS);
5972 f->output_data.w32->top_right_corner_cursor = w32_load_cursor (IDC_SIZENESW);
5973 f->output_data.w32->right_edge_cursor = w32_load_cursor (IDC_SIZEWE);
5974 f->output_data.w32->bottom_right_corner_cursor = w32_load_cursor (IDC_SIZENWSE);
5975 f->output_data.w32->bottom_edge_cursor = w32_load_cursor (IDC_SIZENS);
5976 f->output_data.w32->bottom_left_corner_cursor = w32_load_cursor (IDC_SIZENESW);
5978 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5980 window_prompting = x_figure_window_size (f, parameters, true, &x_width, &x_height);
5982 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5983 f->no_split = minibuffer_only || EQ (tem, Qt);
5985 w32_window (f, window_prompting, minibuffer_only);
5986 x_icon (f, parameters);
5988 x_make_gc (f);
5990 /* Now consider the frame official. */
5991 f->terminal->reference_count++;
5992 FRAME_DISPLAY_INFO (f)->reference_count++;
5993 Vframe_list = Fcons (frame, Vframe_list);
5995 /* We need to do this after creating the window, so that the
5996 icon-creation functions can say whose icon they're describing. */
5997 x_default_parameter (f, parameters, Qicon_type, Qnil,
5998 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
6000 x_default_parameter (f, parameters, Qauto_raise, Qnil,
6001 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6002 x_default_parameter (f, parameters, Qauto_lower, Qnil,
6003 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6004 x_default_parameter (f, parameters, Qcursor_type, Qbox,
6005 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6006 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
6007 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
6008 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
6009 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
6011 /* Allow x_set_window_size, now. */
6012 f->can_x_set_window_size = true;
6014 if (x_width > 0)
6015 SET_FRAME_WIDTH (f, x_width);
6016 if (x_height > 0)
6017 SET_FRAME_HEIGHT (f, x_height);
6019 /* Tell the server what size and position, etc, we want, and how
6020 badly we want them. This should be done after we have the menu
6021 bar so that its size can be taken into account. */
6022 block_input ();
6023 x_wm_set_size_hint (f, window_prompting, false);
6024 unblock_input ();
6026 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
6027 Qx_create_frame_2);
6029 /* Process fullscreen parameter here in the hope that normalizing a
6030 fullheight/fullwidth frame will produce the size set by the last
6031 adjust_frame_size call. */
6032 x_default_parameter (f, parameters, Qfullscreen, Qnil,
6033 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
6034 x_default_parameter (f, parameters, Qz_group, Qnil,
6035 NULL, NULL, RES_TYPE_SYMBOL);
6037 /* Make the window appear on the frame and enable display, unless
6038 the caller says not to. However, with explicit parent, Emacs
6039 cannot control visibility, so don't try. */
6040 if (!f->output_data.w32->explicit_parent)
6042 Lisp_Object visibility
6043 = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
6045 if (EQ (visibility, Qicon))
6046 x_iconify_frame (f);
6047 else
6049 if (EQ (visibility, Qunbound))
6050 visibility = Qt;
6052 if (!NILP (visibility))
6053 x_make_frame_visible (f);
6056 store_frame_param (f, Qvisibility, visibility);
6059 /* For `no-focus-on-map' frames set alpha here. */
6060 if (FRAME_NO_FOCUS_ON_MAP (f))
6061 x_default_parameter (f, parameters, Qalpha, Qnil,
6062 "alpha", "Alpha", RES_TYPE_NUMBER);
6064 /* Initialize `default-minibuffer-frame' in case this is the first
6065 frame on this terminal. */
6066 if (FRAME_HAS_MINIBUF_P (f)
6067 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
6068 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
6069 kset_default_minibuffer_frame (kb, frame);
6071 /* All remaining specified parameters, which have not been "used"
6072 by x_get_arg and friends, now go in the misc. alist of the frame. */
6073 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
6074 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
6075 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
6077 /* Make sure windows on this frame appear in calls to next-window
6078 and similar functions. */
6079 Vwindow_list = Qnil;
6081 return unbind_to (count, frame);
6084 /* FRAME is used only to get a handle on the X display. We don't pass the
6085 display info directly because we're called from frame.c, which doesn't
6086 know about that structure. */
6087 Lisp_Object
6088 x_get_focus_frame (struct frame *frame)
6090 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
6091 Lisp_Object xfocus;
6092 if (! dpyinfo->w32_focus_frame)
6093 return Qnil;
6095 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
6096 return xfocus;
6099 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6100 doc: /* Internal function called by `color-defined-p', which see.
6101 \(Note that the Nextstep version of this function ignores FRAME.) */)
6102 (Lisp_Object color, Lisp_Object frame)
6104 XColor foo;
6105 struct frame *f = decode_window_system_frame (frame);
6107 CHECK_STRING (color);
6109 if (w32_defined_color (f, SSDATA (color), &foo, false))
6110 return Qt;
6111 else
6112 return Qnil;
6115 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6116 doc: /* Internal function called by `color-values', which see. */)
6117 (Lisp_Object color, Lisp_Object frame)
6119 XColor foo;
6120 struct frame *f = decode_window_system_frame (frame);
6122 CHECK_STRING (color);
6124 if (w32_defined_color (f, SSDATA (color), &foo, false))
6125 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
6126 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
6127 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
6128 else
6129 return Qnil;
6132 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6133 doc: /* Internal function called by `display-color-p', which see. */)
6134 (Lisp_Object display)
6136 struct w32_display_info *dpyinfo = check_x_display_info (display);
6138 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6139 return Qnil;
6141 return Qt;
6144 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6145 Sx_display_grayscale_p, 0, 1, 0,
6146 doc: /* Return t if DISPLAY supports shades of gray.
6147 Note that color displays do support shades of gray.
6148 The optional argument DISPLAY specifies which display to ask about.
6149 DISPLAY should be either a frame or a display name (a string).
6150 If omitted or nil, that stands for the selected frame's display. */)
6151 (Lisp_Object display)
6153 struct w32_display_info *dpyinfo = check_x_display_info (display);
6155 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6156 return Qnil;
6158 return Qt;
6161 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6162 Sx_display_pixel_width, 0, 1, 0,
6163 doc: /* Return the width in pixels of DISPLAY.
6164 The optional argument DISPLAY specifies which display to ask about.
6165 DISPLAY should be either a frame or a display name (a string).
6166 If omitted or nil, that stands for the selected frame's display.
6168 On \"multi-monitor\" setups this refers to the pixel width for all
6169 physical monitors associated with DISPLAY. To get information for
6170 each physical monitor, use `display-monitor-attributes-list'. */)
6171 (Lisp_Object display)
6173 struct w32_display_info *dpyinfo = check_x_display_info (display);
6175 return make_number (x_display_pixel_width (dpyinfo));
6178 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6179 Sx_display_pixel_height, 0, 1, 0,
6180 doc: /* Return the height in pixels of DISPLAY.
6181 The optional argument DISPLAY specifies which display to ask about.
6182 DISPLAY should be either a frame or a display name (a string).
6183 If omitted or nil, that stands for the selected frame's display.
6185 On \"multi-monitor\" setups this refers to the pixel height for all
6186 physical monitors associated with DISPLAY. To get information for
6187 each physical monitor, use `display-monitor-attributes-list'. */)
6188 (Lisp_Object display)
6190 struct w32_display_info *dpyinfo = check_x_display_info (display);
6192 return make_number (x_display_pixel_height (dpyinfo));
6195 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6196 0, 1, 0,
6197 doc: /* Return the number of bitplanes of DISPLAY.
6198 The optional argument DISPLAY specifies which display to ask about.
6199 DISPLAY should be either a frame or a display name (a string).
6200 If omitted or nil, that stands for the selected frame's display. */)
6201 (Lisp_Object display)
6203 struct w32_display_info *dpyinfo = check_x_display_info (display);
6205 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6208 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6209 0, 1, 0,
6210 doc: /* Return the number of color cells of DISPLAY.
6211 The optional argument DISPLAY specifies which display to ask about.
6212 DISPLAY should be either a frame or a display name (a string).
6213 If omitted or nil, that stands for the selected frame's display. */)
6214 (Lisp_Object display)
6216 struct w32_display_info *dpyinfo = check_x_display_info (display);
6217 int cap;
6219 /* Don't use NCOLORS: it returns incorrect results under remote
6220 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
6221 * overflow and because probably is more meaningful on Windows
6222 * anyway. */
6224 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
6225 return make_number (cap);
6228 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6229 Sx_server_max_request_size,
6230 0, 1, 0,
6231 doc: /* Return the maximum request size of the server of DISPLAY.
6232 The optional argument DISPLAY specifies which display to ask about.
6233 DISPLAY should be either a frame or a display name (a string).
6234 If omitted or nil, that stands for the selected frame's display. */)
6235 (Lisp_Object display)
6237 return make_number (1);
6240 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6241 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
6243 \(Labeling every distributor as a "vendor" embodies the false assumption
6244 that operating systems cannot be developed and distributed noncommercially.)
6246 For GNU and Unix systems, this queries the X server software; for
6247 MS-Windows, this queries the OS.
6249 The optional argument TERMINAL specifies which display to ask about.
6250 TERMINAL should be a terminal object, a frame or a display name (a string).
6251 If omitted or nil, that stands for the selected frame's display. */)
6252 (Lisp_Object terminal)
6254 return build_string ("Microsoft Corp.");
6257 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6258 doc: /* Return the version numbers of the GUI software on TERMINAL.
6259 The value is a list of three integers specifying the version of the GUI
6260 software in use.
6262 For GNU and Unix system, the first 2 numbers are the version of the X
6263 Protocol used on TERMINAL and the 3rd number is the distributor-specific
6264 release number. For MS-Windows, the 3 numbers report the version and
6265 the build number of the OS.
6267 See also the function `x-server-vendor'.
6269 The optional argument TERMINAL specifies which display to ask about.
6270 TERMINAL should be a terminal object, a frame or a display name (a string).
6271 If omitted or nil, that stands for the selected frame's display. */)
6272 (Lisp_Object terminal)
6274 return list3i (w32_major_version, w32_minor_version, w32_build_number);
6277 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6278 doc: /* Return the number of screens on the server of DISPLAY.
6279 The optional argument DISPLAY specifies which display to ask about.
6280 DISPLAY should be either a frame or a display name (a string).
6281 If omitted or nil, that stands for the selected frame's display. */)
6282 (Lisp_Object display)
6284 return make_number (1);
6287 DEFUN ("x-display-mm-height", Fx_display_mm_height,
6288 Sx_display_mm_height, 0, 1, 0,
6289 doc: /* Return the height in millimeters of DISPLAY.
6290 The optional argument DISPLAY specifies which display to ask about.
6291 DISPLAY should be either a frame or a display name (a string).
6292 If omitted or nil, that stands for the selected frame's display.
6294 On \"multi-monitor\" setups this refers to the height in millimeters for
6295 all physical monitors associated with DISPLAY. To get information
6296 for each physical monitor, use `display-monitor-attributes-list'. */)
6297 (Lisp_Object display)
6299 struct w32_display_info *dpyinfo = check_x_display_info (display);
6300 HDC hdc;
6301 double mm_per_pixel;
6303 hdc = GetDC (NULL);
6304 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6305 / GetDeviceCaps (hdc, VERTRES));
6306 ReleaseDC (NULL, hdc);
6308 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
6311 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6312 doc: /* Return the width in millimeters of DISPLAY.
6313 The optional argument DISPLAY specifies which display to ask about.
6314 DISPLAY should be either a frame or a display name (a string).
6315 If omitted or nil, that stands for the selected frame's display.
6317 On \"multi-monitor\" setups this refers to the width in millimeters for
6318 all physical monitors associated with TERMINAL. To get information
6319 for each physical monitor, use `display-monitor-attributes-list'. */)
6320 (Lisp_Object display)
6322 struct w32_display_info *dpyinfo = check_x_display_info (display);
6323 HDC hdc;
6324 double mm_per_pixel;
6326 hdc = GetDC (NULL);
6327 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6328 / GetDeviceCaps (hdc, HORZRES));
6329 ReleaseDC (NULL, hdc);
6331 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
6334 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6335 Sx_display_backing_store, 0, 1, 0,
6336 doc: /* Return an indication of whether DISPLAY does backing store.
6337 The value may be `always', `when-mapped', or `not-useful'.
6338 The optional argument DISPLAY specifies which display to ask about.
6339 DISPLAY should be either a frame or a display name (a string).
6340 If omitted or nil, that stands for the selected frame's display. */)
6341 (Lisp_Object display)
6343 return intern ("not-useful");
6346 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6347 Sx_display_visual_class, 0, 1, 0,
6348 doc: /* Return the visual class of DISPLAY.
6349 The value is one of the symbols `static-gray', `gray-scale',
6350 `static-color', `pseudo-color', `true-color', or `direct-color'.
6352 The optional argument DISPLAY specifies which display to ask about.
6353 DISPLAY should be either a frame or a display name (a string).
6354 If omitted or nil, that stands for the selected frame's display. */)
6355 (Lisp_Object display)
6357 struct w32_display_info *dpyinfo = check_x_display_info (display);
6358 Lisp_Object result = Qnil;
6360 if (dpyinfo->has_palette)
6361 result = intern ("pseudo-color");
6362 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6363 result = intern ("static-grey");
6364 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6365 result = intern ("static-color");
6366 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6367 result = intern ("true-color");
6369 return result;
6372 DEFUN ("x-display-save-under", Fx_display_save_under,
6373 Sx_display_save_under, 0, 1, 0,
6374 doc: /* Return t if DISPLAY supports the save-under feature.
6375 The optional argument DISPLAY specifies which display to ask about.
6376 DISPLAY should be either a frame or a display name (a string).
6377 If omitted or nil, that stands for the selected frame's display. */)
6378 (Lisp_Object display)
6380 return Qnil;
6383 static BOOL CALLBACK ALIGN_STACK
6384 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
6386 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
6388 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
6390 return TRUE;
6393 static Lisp_Object
6394 w32_display_monitor_attributes_list (void)
6396 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
6397 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
6398 int i, n_monitors;
6399 HMONITOR *monitors;
6401 if (!(enum_display_monitors_fn && get_monitor_info_fn
6402 && monitor_from_window_fn))
6403 return Qnil;
6405 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
6406 (LPARAM) &monitor_list)
6407 || NILP (monitor_list))
6408 return Qnil;
6410 n_monitors = 0;
6411 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
6412 n_monitors++;
6414 monitors = xmalloc (n_monitors * sizeof (*monitors));
6415 for (i = 0; i < n_monitors; i++)
6417 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
6418 monitor_list = XCDR (monitor_list);
6421 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
6422 FOR_EACH_FRAME (rest, frame)
6424 struct frame *f = XFRAME (frame);
6426 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
6428 HMONITOR monitor =
6429 monitor_from_window_fn (FRAME_W32_WINDOW (f),
6430 MONITOR_DEFAULT_TO_NEAREST);
6432 for (i = 0; i < n_monitors; i++)
6433 if (monitors[i] == monitor)
6434 break;
6436 if (i < n_monitors)
6437 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
6441 for (i = 0; i < n_monitors; i++)
6443 Lisp_Object geometry, workarea, name, attributes = Qnil;
6444 HDC hdc;
6445 int width_mm, height_mm;
6446 struct MONITOR_INFO_EX mi;
6448 mi.cbSize = sizeof (mi);
6449 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
6450 continue;
6452 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
6453 if (hdc == NULL)
6454 continue;
6455 width_mm = GetDeviceCaps (hdc, HORZSIZE);
6456 height_mm = GetDeviceCaps (hdc, VERTSIZE);
6457 DeleteDC (hdc);
6459 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
6460 attributes);
6462 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
6464 attributes = Fcons (Fcons (Qname, name), attributes);
6466 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6467 attributes);
6469 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
6470 mi.rcWork.right - mi.rcWork.left,
6471 mi.rcWork.bottom - mi.rcWork.top);
6472 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6474 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
6475 mi.rcMonitor.right - mi.rcMonitor.left,
6476 mi.rcMonitor.bottom - mi.rcMonitor.top);
6477 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6479 if (mi.dwFlags & MONITORINFOF_PRIMARY)
6480 primary_monitor_attributes = attributes;
6481 else
6482 attributes_list = Fcons (attributes, attributes_list);
6485 if (!NILP (primary_monitor_attributes))
6486 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
6488 xfree (monitors);
6490 return attributes_list;
6493 static Lisp_Object
6494 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
6496 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
6497 HDC hdc;
6498 double mm_per_pixel;
6499 int pixel_width, pixel_height, width_mm, height_mm;
6500 RECT workarea_rect;
6502 /* Fallback: treat (possibly) multiple physical monitors as if they
6503 formed a single monitor as a whole. This should provide a
6504 consistent result at least on single monitor environments. */
6505 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
6506 attributes);
6508 frames = Qnil;
6509 FOR_EACH_FRAME (rest, frame)
6511 struct frame *f = XFRAME (frame);
6513 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
6514 frames = Fcons (frame, frames);
6516 attributes = Fcons (Fcons (Qframes, frames), attributes);
6518 pixel_width = x_display_pixel_width (dpyinfo);
6519 pixel_height = x_display_pixel_height (dpyinfo);
6521 hdc = GetDC (NULL);
6522 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6523 / GetDeviceCaps (hdc, HORZRES));
6524 width_mm = pixel_width * mm_per_pixel + 0.5;
6525 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6526 / GetDeviceCaps (hdc, VERTRES));
6527 height_mm = pixel_height * mm_per_pixel + 0.5;
6528 ReleaseDC (NULL, hdc);
6529 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6530 attributes);
6532 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
6533 we don't care. */
6534 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
6535 GetSystemMetrics (SM_YVIRTUALSCREEN),
6536 pixel_width, pixel_height);
6537 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
6538 workarea = list4i (workarea_rect.left, workarea_rect.top,
6539 workarea_rect.right - workarea_rect.left,
6540 workarea_rect.bottom - workarea_rect.top);
6541 else
6542 workarea = geometry;
6543 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6545 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6547 return list1 (attributes);
6550 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
6551 Sw32_display_monitor_attributes_list,
6552 0, 1, 0,
6553 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
6555 The optional argument DISPLAY specifies which display to ask about.
6556 DISPLAY should be either a frame or a display name (a string).
6557 If omitted or nil, that stands for the selected frame's display.
6559 Internal use only, use `display-monitor-attributes-list' instead. */)
6560 (Lisp_Object display)
6562 struct w32_display_info *dpyinfo = check_x_display_info (display);
6563 Lisp_Object attributes_list;
6565 block_input ();
6566 attributes_list = w32_display_monitor_attributes_list ();
6567 if (NILP (attributes_list))
6568 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
6569 unblock_input ();
6571 return attributes_list;
6574 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
6575 doc: /* Set the sound generated when the bell is rung.
6576 SOUND is `asterisk', `exclamation', `hand', `question', `ok', or `silent'
6577 to use the corresponding system sound for the bell. The `silent' sound
6578 prevents Emacs from making any sound at all.
6579 SOUND is nil to use the normal beep. */)
6580 (Lisp_Object sound)
6582 CHECK_SYMBOL (sound);
6584 if (NILP (sound))
6585 sound_type = 0xFFFFFFFF;
6586 else if (EQ (sound, intern ("asterisk")))
6587 sound_type = MB_ICONASTERISK;
6588 else if (EQ (sound, intern ("exclamation")))
6589 sound_type = MB_ICONEXCLAMATION;
6590 else if (EQ (sound, intern ("hand")))
6591 sound_type = MB_ICONHAND;
6592 else if (EQ (sound, intern ("question")))
6593 sound_type = MB_ICONQUESTION;
6594 else if (EQ (sound, intern ("ok")))
6595 sound_type = MB_OK;
6596 else if (EQ (sound, intern ("silent")))
6597 sound_type = MB_EMACS_SILENT;
6598 else
6599 sound_type = 0xFFFFFFFF;
6601 return sound;
6604 #if 0 /* unused */
6606 x_screen_planes (register struct frame *f)
6608 return FRAME_DISPLAY_INFO (f)->n_planes;
6610 #endif
6612 /* Return the display structure for the display named NAME.
6613 Open a new connection if necessary. */
6615 struct w32_display_info *
6616 x_display_info_for_name (Lisp_Object name)
6618 struct w32_display_info *dpyinfo;
6620 CHECK_STRING (name);
6622 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
6623 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
6624 return dpyinfo;
6626 /* Use this general default value to start with. */
6627 Vx_resource_name = Vinvocation_name;
6629 validate_x_resource_name ();
6631 dpyinfo = w32_term_init (name, NULL, SSDATA (Vx_resource_name));
6633 if (dpyinfo == 0)
6634 error ("Cannot connect to server %s", SDATA (name));
6636 XSETFASTINT (Vwindow_system_version, w32_major_version);
6638 return dpyinfo;
6641 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6642 1, 3, 0, doc: /* Open a connection to a display server.
6643 DISPLAY is the name of the display to connect to.
6644 Optional second arg XRM-STRING is a string of resources in xrdb format.
6645 If the optional third arg MUST-SUCCEED is non-nil,
6646 terminate Emacs if we can't open the connection.
6647 \(In the Nextstep version, the last two arguments are currently ignored.) */)
6648 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
6650 char *xrm_option;
6651 struct w32_display_info *dpyinfo;
6653 CHECK_STRING (display);
6655 /* Signal an error in order to encourage correct use from callers.
6656 * If we ever support multiple window systems in the same Emacs,
6657 * we'll need callers to be precise about what window system they
6658 * want. */
6660 if (strcmp (SSDATA (display), "w32") != 0)
6661 error ("The name of the display in this Emacs must be \"w32\"");
6663 /* If initialization has already been done, return now to avoid
6664 overwriting critical parts of one_w32_display_info. */
6665 if (window_system_available (NULL))
6666 return Qnil;
6668 if (! NILP (xrm_string))
6669 CHECK_STRING (xrm_string);
6671 /* Allow color mapping to be defined externally; first look in user's
6672 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6674 Lisp_Object color_file;
6676 color_file = build_string ("~/rgb.txt");
6678 if (NILP (Ffile_readable_p (color_file)))
6679 color_file =
6680 Fexpand_file_name (build_string ("rgb.txt"),
6681 Fsymbol_value (intern ("data-directory")));
6683 Vw32_color_map = Fx_load_color_file (color_file);
6685 if (NILP (Vw32_color_map))
6686 Vw32_color_map = w32_default_color_map ();
6688 /* Merge in system logical colors. */
6689 add_system_logical_colors_to_map (&Vw32_color_map);
6691 if (! NILP (xrm_string))
6692 xrm_option = SSDATA (xrm_string);
6693 else
6694 xrm_option = NULL;
6696 /* Use this general default value to start with. */
6697 /* First remove .exe suffix from invocation-name - it looks ugly. */
6699 char basename[ MAX_PATH ], *str;
6701 lispstpcpy (basename, Vinvocation_name);
6702 str = strrchr (basename, '.');
6703 if (str) *str = 0;
6704 Vinvocation_name = build_string (basename);
6706 Vx_resource_name = Vinvocation_name;
6708 validate_x_resource_name ();
6710 /* This is what opens the connection and sets x_current_display.
6711 This also initializes many symbols, such as those used for input. */
6712 dpyinfo = w32_term_init (display, xrm_option, SSDATA (Vx_resource_name));
6714 if (dpyinfo == 0)
6716 if (!NILP (must_succeed))
6717 fatal ("Cannot connect to server %s.\n",
6718 SDATA (display));
6719 else
6720 error ("Cannot connect to server %s", SDATA (display));
6723 XSETFASTINT (Vwindow_system_version, w32_major_version);
6724 return Qnil;
6727 DEFUN ("x-close-connection", Fx_close_connection,
6728 Sx_close_connection, 1, 1, 0,
6729 doc: /* Close the connection to DISPLAY's server.
6730 For DISPLAY, specify either a frame or a display name (a string).
6731 If DISPLAY is nil, that stands for the selected frame's display. */)
6732 (Lisp_Object display)
6734 struct w32_display_info *dpyinfo = check_x_display_info (display);
6736 if (dpyinfo->reference_count > 0)
6737 error ("Display still has frames on it");
6739 block_input ();
6740 x_destroy_all_bitmaps (dpyinfo);
6742 x_delete_display (dpyinfo);
6743 unblock_input ();
6745 return Qnil;
6748 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6749 doc: /* Return the list of display names that Emacs has connections to. */)
6750 (void)
6752 Lisp_Object result = Qnil;
6753 struct w32_display_info *wdi;
6755 for (wdi = x_display_list; wdi; wdi = wdi->next)
6756 result = Fcons (XCAR (wdi->name_list_element), result);
6758 return result;
6761 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6762 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
6763 This function only has an effect on X Windows. With MS Windows, it is
6764 defined but does nothing.
6766 If ON is nil, allow buffering of requests.
6767 Turning on synchronization prohibits the Xlib routines from buffering
6768 requests and seriously degrades performance, but makes debugging much
6769 easier.
6770 The optional second argument TERMINAL specifies which display to act on.
6771 TERMINAL should be a terminal object, a frame or a display name (a string).
6772 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
6773 (Lisp_Object on, Lisp_Object display)
6775 return Qnil;
6780 /***********************************************************************
6781 Window properties
6782 ***********************************************************************/
6784 #if 0 /* TODO : port window properties to W32 */
6786 DEFUN ("x-change-window-property", Fx_change_window_property,
6787 Sx_change_window_property, 2, 6, 0,
6788 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6789 PROP must be a string. VALUE may be a string or a list of conses,
6790 numbers and/or strings. If an element in the list is a string, it is
6791 converted to an atom and the value of the Atom is used. If an element
6792 is a cons, it is converted to a 32 bit number where the car is the 16
6793 top bits and the cdr is the lower 16 bits.
6795 FRAME nil or omitted means use the selected frame.
6796 If TYPE is given and non-nil, it is the name of the type of VALUE.
6797 If TYPE is not given or nil, the type is STRING.
6798 FORMAT gives the size in bits of each element if VALUE is a list.
6799 It must be one of 8, 16 or 32.
6800 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6801 If OUTER-P is non-nil, the property is changed for the outer X window of
6802 FRAME. Default is to change on the edit X window. */)
6803 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6804 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6806 struct frame *f = decode_window_system_frame (frame);
6807 Atom prop_atom;
6809 CHECK_STRING (prop);
6810 CHECK_STRING (value);
6812 block_input ();
6813 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6814 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6815 prop_atom, XA_STRING, 8, PropModeReplace,
6816 SDATA (value), SCHARS (value));
6818 /* Make sure the property is set when we return. */
6819 XFlush (FRAME_W32_DISPLAY (f));
6820 unblock_input ();
6822 return value;
6826 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6827 Sx_delete_window_property, 1, 2, 0,
6828 doc: /* Remove window property PROP from X window of FRAME.
6829 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6830 (Lisp_Object prop, Lisp_Object frame)
6832 struct frame *f = decode_window_system_frame (frame);
6833 Atom prop_atom;
6835 CHECK_STRING (prop);
6836 block_input ();
6837 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6838 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6840 /* Make sure the property is removed when we return. */
6841 XFlush (FRAME_W32_DISPLAY (f));
6842 unblock_input ();
6844 return prop;
6848 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6849 1, 6, 0,
6850 doc: /* Value is the value of window property PROP on FRAME.
6851 If FRAME is nil or omitted, use the selected frame.
6853 On X Windows, the following optional arguments are also accepted:
6854 If TYPE is nil or omitted, get the property as a string.
6855 Otherwise TYPE is the name of the atom that denotes the type expected.
6856 If SOURCE is non-nil, get the property on that window instead of from
6857 FRAME. The number 0 denotes the root window.
6858 If DELETE-P is non-nil, delete the property after retrieving it.
6859 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6861 On MS Windows, this function accepts but ignores those optional arguments.
6863 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6864 no value of TYPE (always string in the MS Windows case). */)
6865 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6866 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6868 struct frame *f = decode_window_system_frame (frame);
6869 Atom prop_atom;
6870 int rc;
6871 Lisp_Object prop_value = Qnil;
6872 char *tmp_data = NULL;
6873 Atom actual_type;
6874 int actual_format;
6875 unsigned long actual_size, bytes_remaining;
6877 CHECK_STRING (prop);
6878 block_input ();
6879 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6880 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6881 prop_atom, 0, 0, False, XA_STRING,
6882 &actual_type, &actual_format, &actual_size,
6883 &bytes_remaining, (unsigned char **) &tmp_data);
6884 if (rc == Success)
6886 int size = bytes_remaining;
6888 XFree (tmp_data);
6889 tmp_data = NULL;
6891 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6892 prop_atom, 0, bytes_remaining,
6893 False, XA_STRING,
6894 &actual_type, &actual_format,
6895 &actual_size, &bytes_remaining,
6896 (unsigned char **) &tmp_data);
6897 if (rc == Success)
6898 prop_value = make_string (tmp_data, size);
6900 XFree (tmp_data);
6903 unblock_input ();
6905 return prop_value;
6907 return Qnil;
6910 #endif /* TODO */
6912 /***********************************************************************
6913 Tool tips
6914 ***********************************************************************/
6916 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6917 Lisp_Object, int, int, int *, int *);
6919 /* The frame of a currently visible tooltip. */
6921 Lisp_Object tip_frame;
6923 /* If non-nil, a timer started that hides the last tooltip when it
6924 fires. */
6926 Lisp_Object tip_timer;
6927 Window tip_window;
6929 /* If non-nil, a vector of 3 elements containing the last args
6930 with which x-show-tip was called. See there. */
6932 Lisp_Object last_show_tip_args;
6935 static void
6936 unwind_create_tip_frame (Lisp_Object frame)
6938 Lisp_Object deleted;
6940 deleted = unwind_create_frame (frame);
6941 if (EQ (deleted, Qt))
6943 tip_window = NULL;
6944 tip_frame = Qnil;
6949 /* Create a frame for a tooltip on the display described by DPYINFO.
6950 PARMS is a list of frame parameters. Value is the frame.
6952 Note that functions called here, esp. x_default_parameter can
6953 signal errors, for instance when a specified color name is
6954 undefined. We have to make sure that we're in a consistent state
6955 when this happens. */
6957 static Lisp_Object
6958 x_create_tip_frame (struct w32_display_info *dpyinfo, Lisp_Object parms)
6960 struct frame *f;
6961 Lisp_Object frame;
6962 Lisp_Object name;
6963 int width, height;
6964 ptrdiff_t count = SPECPDL_INDEX ();
6965 struct kboard *kb;
6966 bool face_change_before = face_change;
6967 int x_width = 0, x_height = 0;
6969 /* Use this general default value to start with until we know if
6970 this frame has a specified name. */
6971 Vx_resource_name = Vinvocation_name;
6973 kb = dpyinfo->terminal->kboard;
6975 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6976 avoid destructive changes behind our caller's back. */
6977 parms = Fcopy_alist (parms);
6979 /* Get the name of the frame to use for resource lookup. */
6980 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6981 if (!STRINGP (name)
6982 && !EQ (name, Qunbound)
6983 && !NILP (name))
6984 error ("Invalid frame name--not a string or nil");
6985 Vx_resource_name = name;
6987 frame = Qnil;
6988 /* Make a frame without minibuffer nor mode-line. */
6989 f = make_frame (false);
6990 f->wants_modeline = false;
6991 XSETFRAME (frame, f);
6993 record_unwind_protect (unwind_create_tip_frame, frame);
6995 /* By setting the output method, we're essentially saying that
6996 the frame is live, as per FRAME_LIVE_P. If we get a signal
6997 from this point on, x_destroy_window might screw up reference
6998 counts etc. */
6999 f->terminal = dpyinfo->terminal;
7000 f->output_method = output_w32;
7001 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
7003 FRAME_FONTSET (f) = -1;
7004 fset_icon_name (f, Qnil);
7006 #ifdef GLYPH_DEBUG
7007 image_cache_refcount =
7008 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
7009 dpyinfo_refcount = dpyinfo->reference_count;
7010 #endif /* GLYPH_DEBUG */
7011 FRAME_KBOARD (f) = kb;
7013 /* Set the name; the functions to which we pass f expect the name to
7014 be set. */
7015 if (EQ (name, Qunbound) || NILP (name))
7017 fset_name (f, build_string (dpyinfo->w32_id_name));
7018 f->explicit_name = false;
7020 else
7022 fset_name (f, name);
7023 f->explicit_name = true;
7024 /* Use the frame's title when getting resources for this frame. */
7025 specbind (Qx_resource_name, name);
7028 if (uniscribe_available)
7029 register_font_driver (&uniscribe_font_driver, f);
7030 register_font_driver (&w32font_driver, f);
7032 x_default_parameter (f, parms, Qfont_backend, Qnil,
7033 "fontBackend", "FontBackend", RES_TYPE_STRING);
7035 /* Extract the window parameters from the supplied values
7036 that are needed to determine window geometry. */
7037 x_default_font_parameter (f, parms);
7039 x_default_parameter (f, parms, Qborder_width, make_number (2),
7040 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
7041 /* This defaults to 2 in order to match xterm. We recognize either
7042 internalBorderWidth or internalBorder (which is what xterm calls
7043 it). */
7044 if (NILP (Fassq (Qinternal_border_width, parms)))
7046 Lisp_Object value;
7048 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
7049 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
7050 if (! EQ (value, Qunbound))
7051 parms = Fcons (Fcons (Qinternal_border_width, value),
7052 parms);
7055 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
7056 "internalBorderWidth", "internalBorderWidth",
7057 RES_TYPE_NUMBER);
7058 /* Also do the stuff which must be set before the window exists. */
7059 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
7060 "foreground", "Foreground", RES_TYPE_STRING);
7061 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
7062 "background", "Background", RES_TYPE_STRING);
7063 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
7064 "pointerColor", "Foreground", RES_TYPE_STRING);
7065 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
7066 "cursorColor", "Foreground", RES_TYPE_STRING);
7067 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
7068 "borderColor", "BorderColor", RES_TYPE_STRING);
7069 x_default_parameter (f, parms, Qno_special_glyphs, Qt,
7070 NULL, NULL, RES_TYPE_BOOLEAN);
7072 /* Init faces before x_default_parameter is called for the
7073 scroll-bar-width parameter because otherwise we end up in
7074 init_iterator with a null face cache, which should not happen. */
7075 init_frame_faces (f);
7077 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
7078 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
7079 f->output_data.w32->explicit_parent = false;
7081 x_figure_window_size (f, parms, true, &x_width, &x_height);
7083 /* No fringes on tip frame. */
7084 f->fringe_cols = 0;
7085 f->left_fringe_width = 0;
7086 f->right_fringe_width = 0;
7087 /* No dividers on tip frame. */
7088 f->right_divider_width = 0;
7089 f->bottom_divider_width = 0;
7091 block_input ();
7092 my_create_tip_window (f);
7093 unblock_input ();
7095 x_make_gc (f);
7097 x_default_parameter (f, parms, Qauto_raise, Qnil,
7098 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7099 x_default_parameter (f, parms, Qauto_lower, Qnil,
7100 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7101 x_default_parameter (f, parms, Qcursor_type, Qbox,
7102 "cursorType", "CursorType", RES_TYPE_SYMBOL);
7103 /* Process alpha here (Bug#17344). */
7104 x_default_parameter (f, parms, Qalpha, Qnil,
7105 "alpha", "Alpha", RES_TYPE_NUMBER);
7107 /* Dimensions, especially FRAME_LINES (f), must be done via
7108 change_frame_size. Change will not be effected unless different
7109 from the current FRAME_LINES (f). */
7110 width = FRAME_COLS (f);
7111 height = FRAME_LINES (f);
7112 SET_FRAME_COLS (f, 0);
7113 SET_FRAME_LINES (f, 0);
7114 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
7115 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
7116 /* Add `tooltip' frame parameter's default value. */
7117 if (NILP (Fframe_parameter (frame, Qtooltip)))
7118 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
7120 /* Set up faces after all frame parameters are known. This call
7121 also merges in face attributes specified for new frames.
7123 Frame parameters may be changed if .Xdefaults contains
7124 specifications for the default font. For example, if there is an
7125 `Emacs.default.attributeBackground: pink', the `background-color'
7126 attribute of the frame get's set, which let's the internal border
7127 of the tooltip frame appear in pink. Prevent this. */
7129 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
7130 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
7131 Lisp_Object colors = Qnil;
7133 call2 (Qface_set_after_frame_default, frame, Qnil);
7135 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
7136 colors = Fcons (Fcons (Qbackground_color, bg), colors);
7137 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
7138 colors = Fcons (Fcons (Qforeground_color, fg), colors);
7140 if (!NILP (colors))
7141 Fmodify_frame_parameters (frame, colors);
7144 f->no_split = true;
7146 /* Now that the frame is official, it counts as a reference to
7147 its display. */
7148 FRAME_DISPLAY_INFO (f)->reference_count++;
7149 f->terminal->reference_count++;
7151 /* It is now ok to make the frame official even if we get an error
7152 below. And the frame needs to be on Vframe_list or making it
7153 visible won't work. */
7154 Vframe_list = Fcons (frame, Vframe_list);
7155 f->can_x_set_window_size = true;
7157 /* Setting attributes of faces of the tooltip frame from resources
7158 and similar will set face_change, which leads to the
7159 clearing of all current matrices. Since this isn't necessary
7160 here, avoid it by resetting face_change to the value it
7161 had before we created the tip frame. */
7162 face_change = face_change_before;
7164 /* Discard the unwind_protect. */
7165 return unbind_to (count, frame);
7169 /* Compute where to display tip frame F. PARMS is the list of frame
7170 parameters for F. DX and DY are specified offsets from the current
7171 location of the mouse. WIDTH and HEIGHT are the width and height
7172 of the tooltip. Return coordinates relative to the root window of
7173 the display in *ROOT_X and *ROOT_Y. */
7175 static void
7176 compute_tip_xy (struct frame *f,
7177 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
7178 int width, int height, int *root_x, int *root_y)
7180 Lisp_Object left, top, right, bottom;
7181 int min_x = 0, min_y = 0, max_x = 0, max_y = 0;
7183 /* User-specified position? */
7184 left = Fcdr (Fassq (Qleft, parms));
7185 top = Fcdr (Fassq (Qtop, parms));
7186 right = Fcdr (Fassq (Qright, parms));
7187 bottom = Fcdr (Fassq (Qbottom, parms));
7189 /* Move the tooltip window where the mouse pointer is. Resize and
7190 show it. */
7191 if ((!INTEGERP (left) && !INTEGERP (right))
7192 || (!INTEGERP (top) && !INTEGERP (bottom)))
7194 POINT pt;
7196 /* Default min and max values. */
7197 min_x = 0;
7198 min_y = 0;
7199 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
7200 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
7202 block_input ();
7203 GetCursorPos (&pt);
7204 *root_x = pt.x;
7205 *root_y = pt.y;
7206 unblock_input ();
7208 /* If multiple monitor support is available, constrain the tip onto
7209 the current monitor. This improves the above by allowing negative
7210 co-ordinates if monitor positions are such that they are valid, and
7211 snaps a tooltip onto a single monitor if we are close to the edge
7212 where it would otherwise flow onto the other monitor (or into
7213 nothingness if there is a gap in the overlap). */
7214 if (monitor_from_point_fn && get_monitor_info_fn)
7216 struct MONITOR_INFO info;
7217 HMONITOR monitor
7218 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
7219 info.cbSize = sizeof (info);
7221 if (get_monitor_info_fn (monitor, &info))
7223 min_x = info.rcWork.left;
7224 min_y = info.rcWork.top;
7225 max_x = info.rcWork.right;
7226 max_y = info.rcWork.bottom;
7231 if (INTEGERP (top))
7232 *root_y = XINT (top);
7233 else if (INTEGERP (bottom))
7234 *root_y = XINT (bottom) - height;
7235 else if (*root_y + XINT (dy) <= min_y)
7236 *root_y = min_y; /* Can happen for negative dy */
7237 else if (*root_y + XINT (dy) + height <= max_y)
7238 /* It fits below the pointer */
7239 *root_y += XINT (dy);
7240 else if (height + XINT (dy) + min_y <= *root_y)
7241 /* It fits above the pointer. */
7242 *root_y -= height + XINT (dy);
7243 else
7244 /* Put it on the top. */
7245 *root_y = min_y;
7247 if (INTEGERP (left))
7248 *root_x = XINT (left);
7249 else if (INTEGERP (right))
7250 *root_x = XINT (right) - width;
7251 else if (*root_x + XINT (dx) <= min_x)
7252 *root_x = 0; /* Can happen for negative dx */
7253 else if (*root_x + XINT (dx) + width <= max_x)
7254 /* It fits to the right of the pointer. */
7255 *root_x += XINT (dx);
7256 else if (width + XINT (dx) + min_x <= *root_x)
7257 /* It fits to the left of the pointer. */
7258 *root_x -= width + XINT (dx);
7259 else
7260 /* Put it left justified on the screen -- it ought to fit that way. */
7261 *root_x = min_x;
7264 /* Hide tooltip. Delete its frame if DELETE is true. */
7265 static Lisp_Object
7266 x_hide_tip (bool delete)
7268 if (!NILP (tip_timer))
7270 call1 (Qcancel_timer, tip_timer);
7271 tip_timer = Qnil;
7274 if (NILP (tip_frame)
7275 || (!delete && FRAMEP (tip_frame)
7276 && !FRAME_VISIBLE_P (XFRAME (tip_frame))))
7277 return Qnil;
7278 else
7280 ptrdiff_t count;
7281 Lisp_Object was_open = Qnil;
7283 count = SPECPDL_INDEX ();
7284 specbind (Qinhibit_redisplay, Qt);
7285 specbind (Qinhibit_quit, Qt);
7287 if (FRAMEP (tip_frame))
7289 if (delete)
7291 delete_frame (tip_frame, Qnil);
7292 tip_frame = Qnil;
7294 else
7295 x_make_frame_invisible (XFRAME (tip_frame));
7297 was_open = Qt;
7299 else
7300 tip_frame = Qnil;
7302 return unbind_to (count, was_open);
7307 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
7308 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
7309 A tooltip window is a small window displaying a string.
7311 This is an internal function; Lisp code should call `tooltip-show'.
7313 FRAME nil or omitted means use the selected frame.
7315 PARMS is an optional list of frame parameters which can be
7316 used to change the tooltip's appearance.
7318 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
7319 means use the default timeout of 5 seconds.
7321 If the list of frame parameters PARMS contains a `left' parameter,
7322 display the tooltip at that x-position. If the list of frame parameters
7323 PARMS contains no `left' but a `right' parameter, display the tooltip
7324 right-adjusted at that x-position. Otherwise display it at the
7325 x-position of the mouse, with offset DX added (default is 5 if DX isn't
7326 specified).
7328 Likewise for the y-position: If a `top' frame parameter is specified, it
7329 determines the position of the upper edge of the tooltip window. If a
7330 `bottom' parameter but no `top' frame parameter is specified, it
7331 determines the position of the lower edge of the tooltip window.
7332 Otherwise display the tooltip window at the y-position of the mouse,
7333 with offset DY added (default is -10).
7335 A tooltip's maximum size is specified by `x-max-tooltip-size'.
7336 Text larger than the specified size is clipped. */)
7337 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
7339 struct frame *tip_f;
7340 struct window *w;
7341 int root_x, root_y;
7342 struct buffer *old_buffer;
7343 struct text_pos pos;
7344 int width, height;
7345 int old_windows_or_buffers_changed = windows_or_buffers_changed;
7346 ptrdiff_t count = SPECPDL_INDEX ();
7347 ptrdiff_t count_1;
7348 Lisp_Object window, size;
7349 Lisp_Object tip_buf;
7350 AUTO_STRING (tip, " *tip*");
7352 specbind (Qinhibit_redisplay, Qt);
7354 CHECK_STRING (string);
7355 decode_window_system_frame (frame);
7356 if (NILP (timeout))
7357 timeout = make_number (5);
7358 else
7359 CHECK_NATNUM (timeout);
7361 if (NILP (dx))
7362 dx = make_number (5);
7363 else
7364 CHECK_NUMBER (dx);
7366 if (NILP (dy))
7367 dy = make_number (-10);
7368 else
7369 CHECK_NUMBER (dy);
7371 if (NILP (last_show_tip_args))
7372 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
7374 if (FRAMEP (tip_frame) && FRAME_LIVE_P (XFRAME (tip_frame)))
7376 Lisp_Object last_string = AREF (last_show_tip_args, 0);
7377 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
7378 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
7380 if (FRAME_VISIBLE_P (XFRAME (tip_frame))
7381 && EQ (frame, last_frame)
7382 && !NILP (Fequal_including_properties (last_string, string))
7383 && !NILP (Fequal (last_parms, parms)))
7385 /* Only DX and DY have changed. */
7386 tip_f = XFRAME (tip_frame);
7387 if (!NILP (tip_timer))
7389 Lisp_Object timer = tip_timer;
7391 tip_timer = Qnil;
7392 call1 (Qcancel_timer, timer);
7395 block_input ();
7396 compute_tip_xy (tip_f, parms, dx, dy, FRAME_PIXEL_WIDTH (tip_f),
7397 FRAME_PIXEL_HEIGHT (tip_f), &root_x, &root_y);
7399 /* Put tooltip in topmost group and in position. */
7400 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7401 root_x, root_y, 0, 0,
7402 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7404 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7405 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7406 0, 0, 0, 0,
7407 SWP_NOMOVE | SWP_NOSIZE
7408 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7410 /* Let redisplay know that we have made the frame visible already. */
7411 SET_FRAME_VISIBLE (tip_f, 1);
7412 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7413 unblock_input ();
7415 goto start_timer;
7417 else if (tooltip_reuse_hidden_frame && EQ (frame, last_frame))
7419 bool delete = false;
7420 Lisp_Object tail, elt, parm, last;
7422 /* Check if every parameter in PARMS has the same value in
7423 last_parms. This may destruct last_parms which, however,
7424 will be recreated below. */
7425 for (tail = parms; CONSP (tail); tail = XCDR (tail))
7427 elt = XCAR (tail);
7428 parm = Fcar (elt);
7429 /* The left, top, right and bottom parameters are handled
7430 by compute_tip_xy so they can be ignored here. */
7431 if (!EQ (parm, Qleft) && !EQ (parm, Qtop)
7432 && !EQ (parm, Qright) && !EQ (parm, Qbottom))
7434 last = Fassq (parm, last_parms);
7435 if (NILP (Fequal (Fcdr (elt), Fcdr (last))))
7437 /* We lost, delete the old tooltip. */
7438 delete = true;
7439 break;
7441 else
7442 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7444 else
7445 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7448 /* Now check if there's a parameter left in last_parms with a
7449 non-nil value. */
7450 for (tail = last_parms; CONSP (tail); tail = XCDR (tail))
7452 elt = XCAR (tail);
7453 parm = Fcar (elt);
7454 if (!EQ (parm, Qleft) && !EQ (parm, Qtop) && !EQ (parm, Qright)
7455 && !EQ (parm, Qbottom) && !NILP (Fcdr (elt)))
7457 /* We lost, delete the old tooltip. */
7458 delete = true;
7459 break;
7463 x_hide_tip (delete);
7465 else
7466 x_hide_tip (true);
7468 else
7469 x_hide_tip (true);
7471 ASET (last_show_tip_args, 0, string);
7472 ASET (last_show_tip_args, 1, frame);
7473 ASET (last_show_tip_args, 2, parms);
7475 /* Block input until the tip has been fully drawn, to avoid crashes
7476 when drawing tips in menus. */
7477 block_input ();
7479 if (!FRAMEP (tip_frame) || !FRAME_LIVE_P (XFRAME (tip_frame)))
7481 /* Add default values to frame parameters. */
7482 if (NILP (Fassq (Qname, parms)))
7483 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7484 if (NILP (Fassq (Qinternal_border_width, parms)))
7485 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7486 if (NILP (Fassq (Qborder_width, parms)))
7487 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7488 if (NILP (Fassq (Qborder_color, parms)))
7489 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7490 if (NILP (Fassq (Qbackground_color, parms)))
7491 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7492 parms);
7494 /* Create a frame for the tooltip, and record it in the global
7495 variable tip_frame. */
7496 struct frame *f; /* The value is unused. */
7497 if (NILP (tip_frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms)))
7499 /* Creating the tip frame failed. */
7500 unblock_input ();
7501 return unbind_to (count, Qnil);
7505 tip_f = XFRAME (tip_frame);
7506 window = FRAME_ROOT_WINDOW (tip_f);
7507 tip_buf = Fget_buffer_create (tip);
7508 /* We will mark the tip window a "pseudo-window" below, and such
7509 windows cannot have display margins. */
7510 bset_left_margin_cols (XBUFFER (tip_buf), make_number (0));
7511 bset_right_margin_cols (XBUFFER (tip_buf), make_number (0));
7512 set_window_buffer (window, tip_buf, false, false);
7513 w = XWINDOW (window);
7514 w->pseudo_window_p = true;
7516 /* Set up the frame's root window. Note: The following code does not
7517 try to size the window or its frame correctly. Its only purpose is
7518 to make the subsequent text size calculations work. The right
7519 sizes should get installed when the toolkit gets back to us. */
7520 w->left_col = 0;
7521 w->top_line = 0;
7522 w->pixel_left = 0;
7523 w->pixel_top = 0;
7525 if (CONSP (Vx_max_tooltip_size)
7526 && RANGED_INTEGERP (1, XCAR (Vx_max_tooltip_size), INT_MAX)
7527 && RANGED_INTEGERP (1, XCDR (Vx_max_tooltip_size), INT_MAX))
7529 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
7530 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
7532 else
7534 w->total_cols = 80;
7535 w->total_lines = 40;
7538 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (tip_f);
7539 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (tip_f);
7540 FRAME_TOTAL_COLS (tip_f) = WINDOW_TOTAL_COLS (w);
7541 adjust_frame_glyphs (tip_f);
7543 /* Insert STRING into the root window's buffer and fit the frame to
7544 the buffer. */
7545 count_1 = SPECPDL_INDEX ();
7546 old_buffer = current_buffer;
7547 set_buffer_internal_1 (XBUFFER (w->contents));
7548 bset_truncate_lines (current_buffer, Qnil);
7549 specbind (Qinhibit_read_only, Qt);
7550 specbind (Qinhibit_modification_hooks, Qt);
7551 specbind (Qinhibit_point_motion_hooks, Qt);
7552 Ferase_buffer ();
7553 Finsert (1, &string);
7554 clear_glyph_matrix (w->desired_matrix);
7555 clear_glyph_matrix (w->current_matrix);
7556 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7557 try_window (window, pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
7558 /* Calculate size of tooltip window. */
7559 size = Fwindow_text_pixel_size (window, Qnil, Qnil, Qnil,
7560 make_number (w->pixel_height), Qnil);
7561 /* Add the frame's internal border to calculated size. */
7562 width = XINT (Fcar (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7563 height = XINT (Fcdr (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7564 /* Calculate position of tooltip frame. */
7565 compute_tip_xy (tip_f, parms, dx, dy, width, height, &root_x, &root_y);
7567 /* Show tooltip frame. */
7569 RECT rect;
7570 int pad = (NUMBERP (Vw32_tooltip_extra_pixels)
7571 ? max (0, XINT (Vw32_tooltip_extra_pixels))
7572 : FRAME_COLUMN_WIDTH (tip_f));
7574 rect.left = rect.top = 0;
7575 rect.right = width;
7576 rect.bottom = height;
7577 AdjustWindowRect (&rect, tip_f->output_data.w32->dwStyle,
7578 FRAME_EXTERNAL_MENU_BAR (tip_f));
7580 /* Position and size tooltip and put it in the topmost group. */
7581 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7582 root_x, root_y,
7583 rect.right - rect.left + pad,
7584 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7586 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7587 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7588 0, 0, 0, 0,
7589 SWP_NOMOVE | SWP_NOSIZE
7590 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7592 /* Let redisplay know that we have made the frame visible already. */
7593 SET_FRAME_VISIBLE (tip_f, 1);
7595 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7598 w->must_be_updated_p = true;
7599 update_single_window (w);
7600 set_buffer_internal_1 (old_buffer);
7601 unbind_to (count_1, Qnil);
7602 unblock_input ();
7603 windows_or_buffers_changed = old_windows_or_buffers_changed;
7605 start_timer:
7606 /* Let the tip disappear after timeout seconds. */
7607 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7608 intern ("x-hide-tip"));
7610 return unbind_to (count, Qnil);
7614 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7615 doc: /* Hide the current tooltip window, if there is any.
7616 Value is t if tooltip was open, nil otherwise. */)
7617 (void)
7619 return x_hide_tip (!tooltip_reuse_hidden_frame);
7622 /***********************************************************************
7623 File selection dialog
7624 ***********************************************************************/
7626 #define FILE_NAME_TEXT_FIELD edt1
7627 #define FILE_NAME_COMBO_BOX cmb13
7628 #define FILE_NAME_LIST lst1
7630 /* Callback for altering the behavior of the Open File dialog.
7631 Makes the Filename text field contain "Current Directory" and be
7632 read-only when "Directories" is selected in the filter. This
7633 allows us to work around the fact that the standard Open File
7634 dialog does not support directories. */
7635 static UINT_PTR CALLBACK
7636 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
7638 if (msg == WM_NOTIFY)
7640 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
7641 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
7642 int dropdown_changed;
7643 int dir_index;
7644 #ifdef NTGUI_UNICODE
7645 const int use_unicode = 1;
7646 #else /* !NTGUI_UNICODE */
7647 int use_unicode = w32_unicode_filenames;
7648 #endif /* NTGUI_UNICODE */
7650 /* Detect when the Filter dropdown is changed. */
7651 if (use_unicode)
7652 dropdown_changed =
7653 notify_w->hdr.code == CDN_TYPECHANGE
7654 || notify_w->hdr.code == CDN_INITDONE;
7655 else
7656 dropdown_changed =
7657 notify_a->hdr.code == CDN_TYPECHANGE
7658 || notify_a->hdr.code == CDN_INITDONE;
7659 if (dropdown_changed)
7661 HWND dialog = GetParent (hwnd);
7662 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7663 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
7664 int hdr_code;
7666 /* At least on Windows 7, the above attempt to get the window handle
7667 to the File Name Text Field fails. The following code does the
7668 job though. Note that this code is based on my examination of the
7669 window hierarchy using Microsoft Spy++. bk */
7670 if (edit_control == NULL)
7672 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
7673 if (tmp)
7675 tmp = GetWindow (tmp, GW_CHILD);
7676 if (tmp)
7677 edit_control = GetWindow (tmp, GW_CHILD);
7681 /* Directories is in index 2. */
7682 if (use_unicode)
7684 dir_index = notify_w->lpOFN->nFilterIndex;
7685 hdr_code = notify_w->hdr.code;
7687 else
7689 dir_index = notify_a->lpOFN->nFilterIndex;
7690 hdr_code = notify_a->hdr.code;
7692 if (dir_index == 2)
7694 if (use_unicode)
7695 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7696 (LPARAM)L"Current Directory");
7697 else
7698 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7699 (LPARAM)"Current Directory");
7700 EnableWindow (edit_control, FALSE);
7701 /* Note that at least on Windows 7, the above call to EnableWindow
7702 disables the window that would ordinarily have focus. If we
7703 do not set focus to some other window here, focus will land in
7704 no man's land and the user will be unable to tab through the
7705 dialog box (pressing tab will only result in a beep).
7706 Avoid that problem by setting focus to the list here. */
7707 if (hdr_code == CDN_INITDONE)
7708 SetFocus (list);
7710 else
7712 /* Don't override default filename on init done. */
7713 if (hdr_code == CDN_TYPECHANGE)
7715 if (use_unicode)
7716 SendMessageW (dialog, CDM_SETCONTROLTEXT,
7717 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
7718 else
7719 SendMessageA (dialog, CDM_SETCONTROLTEXT,
7720 FILE_NAME_TEXT_FIELD, (LPARAM)"");
7722 EnableWindow (edit_control, TRUE);
7726 return 0;
7729 void
7730 w32_dialog_in_progress (Lisp_Object in_progress)
7732 Lisp_Object frames, frame;
7734 /* Don't let frames in `above' z-group obscure popups. */
7735 FOR_EACH_FRAME (frames, frame)
7737 struct frame *f = XFRAME (frame);
7739 if (!NILP (in_progress) && FRAME_Z_GROUP_ABOVE (f))
7740 x_set_z_group (f, Qabove_suspended, Qabove);
7741 else if (NILP (in_progress) && FRAME_Z_GROUP_ABOVE_SUSPENDED (f))
7742 x_set_z_group (f, Qabove, Qabove_suspended);
7746 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7747 doc: /* Read file name, prompting with PROMPT in directory DIR.
7748 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
7749 selection box, if specified. If MUSTMATCH is non-nil, the returned file
7750 or directory must exist.
7752 This function is only defined on NS, MS Windows, and X Windows with the
7753 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
7754 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
7755 On Windows 7 and later, the file selection dialog "remembers" the last
7756 directory where the user selected a file, and will open that directory
7757 instead of DIR on subsequent invocations of this function with the same
7758 value of DIR as in previous invocations; this is standard Windows behavior. */)
7759 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
7761 /* Filter index: 1: All Files, 2: Directories only */
7762 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
7763 #ifndef NTGUI_UNICODE
7764 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
7765 #endif
7767 Lisp_Object filename = default_filename;
7768 struct frame *f = SELECTED_FRAME ();
7769 BOOL file_opened = FALSE;
7770 Lisp_Object orig_dir = dir;
7771 Lisp_Object orig_prompt = prompt;
7773 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
7774 compatibility) we end up with the old file dialogs. Define a big
7775 enough struct for the new dialog to trick GetOpenFileName into
7776 giving us the new dialogs on newer versions of Windows. */
7777 struct {
7778 OPENFILENAMEW details;
7779 #if _WIN32_WINNT < 0x500 /* < win2k */
7780 PVOID pvReserved;
7781 DWORD dwReserved;
7782 DWORD FlagsEx;
7783 #endif /* < win2k */
7784 } new_file_details_w;
7786 #ifdef NTGUI_UNICODE
7787 wchar_t filename_buf_w[32*1024 + 1]; /* NT kernel maximum */
7788 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7789 const int use_unicode = 1;
7790 #else /* not NTGUI_UNICODE */
7791 struct {
7792 OPENFILENAMEA details;
7793 #if _WIN32_WINNT < 0x500 /* < win2k */
7794 PVOID pvReserved;
7795 DWORD dwReserved;
7796 DWORD FlagsEx;
7797 #endif /* < win2k */
7798 } new_file_details_a;
7799 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7800 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7801 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7802 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7803 int use_unicode = w32_unicode_filenames;
7804 wchar_t *prompt_w;
7805 char *prompt_a UNINIT;
7806 int len;
7807 char fname_ret[MAX_UTF8_PATH];
7808 #endif /* NTGUI_UNICODE */
7811 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7812 system file encoding expected by the platform APIs (e.g. Cygwin's
7813 POSIX implementation) may not be the same as the encoding expected
7814 by the Windows "ANSI" APIs! */
7816 CHECK_STRING (prompt);
7817 CHECK_STRING (dir);
7819 dir = Fexpand_file_name (dir, Qnil);
7821 if (STRINGP (filename))
7822 filename = Ffile_name_nondirectory (filename);
7823 else
7824 filename = empty_unibyte_string;
7826 #ifdef CYGWIN
7827 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7828 if (SCHARS (filename) > 0)
7829 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7830 #endif
7832 CHECK_STRING (dir);
7833 CHECK_STRING (filename);
7835 /* The code in file_dialog_callback that attempts to set the text
7836 of the file name edit window when handling the CDN_INITDONE
7837 WM_NOTIFY message does not work. Setting filename to "Current
7838 Directory" in the only_dir_p case here does work however. */
7839 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7840 filename = build_string ("Current Directory");
7842 /* Convert the values we've computed so far to system form. */
7843 #ifdef NTGUI_UNICODE
7844 to_unicode (prompt, &prompt);
7845 to_unicode (dir, &dir);
7846 to_unicode (filename, &filename);
7847 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7848 report_file_error ("filename too long", default_filename);
7850 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7851 #else /* !NTGUI_UNICODE */
7852 prompt = ENCODE_FILE (prompt);
7853 dir = ENCODE_FILE (dir);
7854 filename = ENCODE_FILE (filename);
7856 /* We modify these in-place, so make copies for safety. */
7857 dir = Fcopy_sequence (dir);
7858 unixtodos_filename (SSDATA (dir));
7859 filename = Fcopy_sequence (filename);
7860 unixtodos_filename (SSDATA (filename));
7861 if (SBYTES (filename) >= MAX_UTF8_PATH)
7862 report_file_error ("filename too long", default_filename);
7863 if (w32_unicode_filenames)
7865 filename_to_utf16 (SSDATA (dir), dir_w);
7866 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7868 /* filename_to_utf16 sets errno to ENOENT when the file
7869 name is too long or cannot be converted to UTF-16. */
7870 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7871 report_file_error ("filename too long", default_filename);
7873 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7874 SSDATA (prompt), -1, NULL, 0);
7875 if (len > 32768)
7876 len = 32768;
7877 prompt_w = alloca (len * sizeof (wchar_t));
7878 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7879 SSDATA (prompt), -1, prompt_w, len);
7881 else
7883 filename_to_ansi (SSDATA (dir), dir_a);
7884 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7886 /* filename_to_ansi sets errno to ENOENT when the file
7887 name is too long or cannot be converted to UTF-16. */
7888 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7889 report_file_error ("filename too long", default_filename);
7891 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7892 SSDATA (prompt), -1, NULL, 0);
7893 if (len > 32768)
7894 len = 32768;
7895 prompt_w = alloca (len * sizeof (wchar_t));
7896 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7897 SSDATA (prompt), -1, prompt_w, len);
7898 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7899 if (len > 32768)
7900 len = 32768;
7901 prompt_a = alloca (len);
7902 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7904 #endif /* NTGUI_UNICODE */
7906 /* Fill in the structure for the call to GetOpenFileName below.
7907 For NTGUI_UNICODE builds (which run only on NT), we just use
7908 the actual size of the structure. For non-NTGUI_UNICODE
7909 builds, we tell the OS we're using an old version of the
7910 structure if the OS isn't new enough to support the newer
7911 version. */
7912 if (use_unicode)
7914 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7915 if (w32_major_version > 4 && w32_major_version < 95)
7916 file_details_w->lStructSize = sizeof (new_file_details_w);
7917 else
7918 file_details_w->lStructSize = sizeof (*file_details_w);
7919 /* Set up the inout parameter for the selected file name. */
7920 file_details_w->lpstrFile = filename_buf_w;
7921 file_details_w->nMaxFile =
7922 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7923 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7924 /* Undocumented Bug in Common File Dialog:
7925 If a filter is not specified, shell links are not resolved. */
7926 file_details_w->lpstrFilter = filter_w;
7927 #ifdef NTGUI_UNICODE
7928 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7929 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7930 #else
7931 file_details_w->lpstrInitialDir = dir_w;
7932 file_details_w->lpstrTitle = prompt_w;
7933 #endif
7934 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7935 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7936 | OFN_EXPLORER | OFN_ENABLEHOOK);
7937 if (!NILP (mustmatch))
7939 /* Require that the path to the parent directory exists. */
7940 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7941 /* If we are looking for a file, require that it exists. */
7942 if (NILP (only_dir_p))
7943 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7946 #ifndef NTGUI_UNICODE
7947 else
7949 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7950 if (w32_major_version > 4 && w32_major_version < 95)
7951 file_details_a->lStructSize = sizeof (new_file_details_a);
7952 else
7953 file_details_a->lStructSize = sizeof (*file_details_a);
7954 file_details_a->lpstrFile = filename_buf_a;
7955 file_details_a->nMaxFile =
7956 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7957 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7958 file_details_a->lpstrFilter = filter_a;
7959 file_details_a->lpstrInitialDir = dir_a;
7960 file_details_a->lpstrTitle = prompt_a;
7961 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7962 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7963 | OFN_EXPLORER | OFN_ENABLEHOOK);
7964 if (!NILP (mustmatch))
7966 /* Require that the path to the parent directory exists. */
7967 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7968 /* If we are looking for a file, require that it exists. */
7969 if (NILP (only_dir_p))
7970 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7973 #endif /* !NTGUI_UNICODE */
7976 int count = SPECPDL_INDEX ();
7978 w32_dialog_in_progress (Qt);
7980 /* Prevent redisplay. */
7981 specbind (Qinhibit_redisplay, Qt);
7982 record_unwind_protect (w32_dialog_in_progress, Qnil);
7983 block_input ();
7984 if (use_unicode)
7986 file_details_w->lpfnHook = file_dialog_callback;
7988 file_opened = GetOpenFileNameW (file_details_w);
7990 #ifndef NTGUI_UNICODE
7991 else
7993 file_details_a->lpfnHook = file_dialog_callback;
7995 file_opened = GetOpenFileNameA (file_details_a);
7997 #endif /* !NTGUI_UNICODE */
7998 unblock_input ();
7999 unbind_to (count, Qnil);
8002 if (file_opened)
8004 /* Get an Emacs string from the value Windows gave us. */
8005 #ifdef NTGUI_UNICODE
8006 filename = from_unicode_buffer (filename_buf_w);
8007 #else /* !NTGUI_UNICODE */
8008 if (use_unicode)
8009 filename_from_utf16 (filename_buf_w, fname_ret);
8010 else
8011 filename_from_ansi (filename_buf_a, fname_ret);
8012 dostounix_filename (fname_ret);
8013 filename = DECODE_FILE (build_unibyte_string (fname_ret));
8014 #endif /* NTGUI_UNICODE */
8016 #ifdef CYGWIN
8017 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
8018 #endif /* CYGWIN */
8020 /* Strip the dummy filename off the end of the string if we
8021 added it to select a directory. */
8022 if ((use_unicode && file_details_w->nFilterIndex == 2)
8023 #ifndef NTGUI_UNICODE
8024 || (!use_unicode && file_details_a->nFilterIndex == 2)
8025 #endif
8027 filename = Ffile_name_directory (filename);
8029 /* User canceled the dialog without making a selection. */
8030 else if (!CommDlgExtendedError ())
8031 filename = Qnil;
8032 /* An error occurred, fallback on reading from the mini-buffer. */
8033 else
8034 filename = Fcompleting_read (
8035 orig_prompt,
8036 intern ("read-file-name-internal"),
8037 orig_dir,
8038 mustmatch,
8039 orig_dir,
8040 Qfile_name_history,
8041 default_filename,
8042 Qnil);
8045 /* Make "Cancel" equivalent to C-g. */
8046 if (NILP (filename))
8047 quit ();
8049 return filename;
8053 #ifdef WINDOWSNT
8054 /* Moving files to the system recycle bin.
8055 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
8056 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
8057 Ssystem_move_file_to_trash, 1, 1, 0,
8058 doc: /* Move file or directory named FILENAME to the recycle bin. */)
8059 (Lisp_Object filename)
8061 Lisp_Object handler;
8062 Lisp_Object encoded_file;
8063 Lisp_Object operation;
8065 operation = Qdelete_file;
8066 if (!NILP (Ffile_directory_p (filename))
8067 && NILP (Ffile_symlink_p (filename)))
8069 operation = intern ("delete-directory");
8070 filename = Fdirectory_file_name (filename);
8073 /* Must have fully qualified file names for moving files to Recycle
8074 Bin. */
8075 filename = Fexpand_file_name (filename, Qnil);
8077 handler = Ffind_file_name_handler (filename, operation);
8078 if (!NILP (handler))
8079 return call2 (handler, operation, filename);
8080 else
8082 const char * path;
8083 int result;
8085 encoded_file = ENCODE_FILE (filename);
8087 path = map_w32_filename (SSDATA (encoded_file), NULL);
8089 /* The Unicode version of SHFileOperation is not supported on
8090 Windows 9X. */
8091 if (w32_unicode_filenames && os_subtype != OS_9X)
8093 SHFILEOPSTRUCTW file_op_w;
8094 /* We need one more element beyond MAX_PATH because this is
8095 a list of file names, with the last element double-null
8096 terminated. */
8097 wchar_t tmp_path_w[MAX_PATH + 1];
8099 memset (tmp_path_w, 0, sizeof (tmp_path_w));
8100 filename_to_utf16 (path, tmp_path_w);
8102 /* On Windows, write permission is required to delete/move files. */
8103 _wchmod (tmp_path_w, 0666);
8105 memset (&file_op_w, 0, sizeof (file_op_w));
8106 file_op_w.hwnd = HWND_DESKTOP;
8107 file_op_w.wFunc = FO_DELETE;
8108 file_op_w.pFrom = tmp_path_w;
8109 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
8110 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
8111 file_op_w.fAnyOperationsAborted = FALSE;
8113 result = SHFileOperationW (&file_op_w);
8115 else
8117 SHFILEOPSTRUCTA file_op_a;
8118 char tmp_path_a[MAX_PATH + 1];
8120 memset (tmp_path_a, 0, sizeof (tmp_path_a));
8121 filename_to_ansi (path, tmp_path_a);
8123 /* If a file cannot be represented in ANSI codepage, don't
8124 let them inadvertently delete other files because some
8125 characters are interpreted as a wildcards. */
8126 if (_mbspbrk ((unsigned char *)tmp_path_a,
8127 (const unsigned char *)"?*"))
8128 result = ERROR_FILE_NOT_FOUND;
8129 else
8131 _chmod (tmp_path_a, 0666);
8133 memset (&file_op_a, 0, sizeof (file_op_a));
8134 file_op_a.hwnd = HWND_DESKTOP;
8135 file_op_a.wFunc = FO_DELETE;
8136 file_op_a.pFrom = tmp_path_a;
8137 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
8138 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
8139 file_op_a.fAnyOperationsAborted = FALSE;
8141 result = SHFileOperationA (&file_op_a);
8144 if (result != 0)
8145 report_file_error ("Removing old name", list1 (filename));
8147 return Qnil;
8150 #endif /* WINDOWSNT */
8153 /***********************************************************************
8154 w32 specialized functions
8155 ***********************************************************************/
8157 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
8158 Sw32_send_sys_command, 1, 2, 0,
8159 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
8160 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
8161 to minimize), #xf120 to restore frame to original size, and #xf100
8162 to activate the menubar for keyboard access. #xf140 activates the
8163 screen saver if defined.
8165 If optional parameter FRAME is not specified, use selected frame. */)
8166 (Lisp_Object command, Lisp_Object frame)
8168 struct frame *f = decode_window_system_frame (frame);
8170 CHECK_NUMBER (command);
8172 if (FRAME_W32_P (f))
8173 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
8175 return Qnil;
8178 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
8179 doc: /* Get Windows to perform OPERATION on DOCUMENT.
8180 This is a wrapper around the ShellExecute system function, which
8181 invokes the application registered to handle OPERATION for DOCUMENT.
8183 OPERATION is either nil or a string that names a supported operation.
8184 What operations can be used depends on the particular DOCUMENT and its
8185 handler application, but typically it is one of the following common
8186 operations:
8188 \"open\" - open DOCUMENT, which could be a file, a directory, or an
8189 executable program (application). If it is an application,
8190 that application is launched in the current buffer's default
8191 directory. Otherwise, the application associated with
8192 DOCUMENT is launched in the buffer's default directory.
8193 \"opennew\" - like \"open\", but instruct the application to open
8194 DOCUMENT in a new window.
8195 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
8196 \"print\" - print DOCUMENT, which must be a file.
8197 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
8198 The printer should be provided in PARAMETERS, see below.
8199 \"explore\" - start the Windows Explorer on DOCUMENT.
8200 \"edit\" - launch an editor and open DOCUMENT for editing; which
8201 editor is launched depends on the association for the
8202 specified DOCUMENT.
8203 \"find\" - initiate search starting from DOCUMENT, which must specify
8204 a directory.
8205 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
8206 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
8207 the clipboard.
8208 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
8209 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
8210 which must be a directory.
8211 \"pastelink\"
8212 - create a shortcut in DOCUMENT (which must be a directory)
8213 the file or directory whose name is in the clipboard.
8214 \"runas\" - run DOCUMENT, which must be an excutable file, with
8215 elevated privileges (a.k.a. \"as Administrator\").
8216 \"properties\"
8217 - open the property sheet dialog for DOCUMENT.
8218 nil - invoke the default OPERATION, or \"open\" if default is
8219 not defined or unavailable.
8221 DOCUMENT is typically the name of a document file or a URL, but can
8222 also be an executable program to run, or a directory to open in the
8223 Windows Explorer. If it is a file or a directory, it must be a local
8224 one; this function does not support remote file names.
8226 If DOCUMENT is an executable program, the optional third arg PARAMETERS
8227 can be a string containing command line parameters, separated by blanks,
8228 that will be passed to the program. Some values of OPERATION also require
8229 parameters (e.g., \"printto\" requires the printer address). Otherwise,
8230 PARAMETERS should be nil or unspecified. Note that double quote characters
8231 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
8233 Optional fourth argument SHOW-FLAG can be used to control how the
8234 application will be displayed when it is invoked. If SHOW-FLAG is nil
8235 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
8236 specified, otherwise it is an integer between 0 and 11 representing
8237 a ShowWindow flag:
8239 0 - start hidden
8240 1 - start as normal-size window
8241 3 - start in a maximized window
8242 6 - start in a minimized window
8243 10 - start as the application itself specifies; this is the default. */)
8244 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
8246 char *errstr;
8247 Lisp_Object current_dir = BVAR (current_buffer, directory);;
8248 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
8249 #ifdef CYGWIN
8250 intptr_t result;
8251 #else
8252 int use_unicode = w32_unicode_filenames;
8253 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
8254 Lisp_Object absdoc, handler;
8255 BOOL success;
8256 #endif
8258 CHECK_STRING (document);
8260 #ifdef CYGWIN
8261 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
8262 document = Fcygwin_convert_file_name_to_windows (document, Qt);
8264 /* Encode filename, current directory and parameters. */
8265 current_dir = GUI_ENCODE_FILE (current_dir);
8266 document = GUI_ENCODE_FILE (document);
8267 doc_w = GUI_SDATA (document);
8268 if (STRINGP (parameters))
8270 parameters = GUI_ENCODE_SYSTEM (parameters);
8271 params_w = GUI_SDATA (parameters);
8273 if (STRINGP (operation))
8275 operation = GUI_ENCODE_SYSTEM (operation);
8276 ops_w = GUI_SDATA (operation);
8278 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
8279 GUI_SDATA (current_dir),
8280 (INTEGERP (show_flag)
8281 ? XINT (show_flag) : SW_SHOWDEFAULT));
8283 if (result > 32)
8284 return Qt;
8286 switch (result)
8288 case SE_ERR_ACCESSDENIED:
8289 errstr = w32_strerror (ERROR_ACCESS_DENIED);
8290 break;
8291 case SE_ERR_ASSOCINCOMPLETE:
8292 case SE_ERR_NOASSOC:
8293 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
8294 break;
8295 case SE_ERR_DDEBUSY:
8296 case SE_ERR_DDEFAIL:
8297 errstr = w32_strerror (ERROR_DDE_FAIL);
8298 break;
8299 case SE_ERR_DDETIMEOUT:
8300 errstr = w32_strerror (ERROR_TIMEOUT);
8301 break;
8302 case SE_ERR_DLLNOTFOUND:
8303 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
8304 break;
8305 case SE_ERR_FNF:
8306 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
8307 break;
8308 case SE_ERR_OOM:
8309 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
8310 break;
8311 case SE_ERR_PNF:
8312 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
8313 break;
8314 case SE_ERR_SHARE:
8315 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
8316 break;
8317 default:
8318 errstr = w32_strerror (0);
8319 break;
8322 #else /* !CYGWIN */
8324 const char file_url_str[] = "file:///";
8325 const int file_url_len = sizeof (file_url_str) - 1;
8326 int doclen;
8328 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
8330 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
8331 start a thread in some rare system configurations, for
8332 unknown reasons. That thread is started in the context of
8333 the Emacs process, but out of control of our code, and seems
8334 to never exit afterwards. Each such thread reserves 8MB of
8335 stack space (because that's the value recorded in the Emacs
8336 executable at link time: Emacs needs a large stack). So a
8337 large enough number of invocations of w32-shell-execute can
8338 potentially cause the Emacs process to run out of available
8339 address space, which is nasty. To work around this, we
8340 convert such URLs to local file names, which seems to prevent
8341 those threads from starting. See bug #20220. */
8342 char *p = SSDATA (document) + file_url_len;
8344 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
8345 document = Fsubstring_no_properties (document,
8346 make_number (file_url_len), Qnil);
8348 /* We have a situation here. If DOCUMENT is a relative file name,
8349 but its name includes leading directories, i.e. it lives not in
8350 CURRENT_DIR, but in its subdirectory, then ShellExecute below
8351 will fail to find it. So we need to make the file name is
8352 absolute. But DOCUMENT does not have to be a file, it can be a
8353 URL, for example. So we make it absolute only if it is an
8354 existing file; if it is a file that does not exist, tough. */
8355 absdoc = Fexpand_file_name (document, Qnil);
8356 /* Don't call file handlers for file-exists-p, since they might
8357 attempt to access the file, which could fail or produce undesired
8358 consequences, see bug#16558 for an example. */
8359 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
8360 if (NILP (handler))
8362 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
8364 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
8366 /* ShellExecute fails if DOCUMENT is a UNC with forward
8367 slashes (expand-file-name above converts all backslashes
8368 to forward slashes). Now that we know DOCUMENT is a
8369 file, we can mirror all forward slashes into backslashes. */
8370 unixtodos_filename (SSDATA (absdoc_encoded));
8371 document = absdoc_encoded;
8373 else
8374 document = ENCODE_FILE (document);
8376 else
8377 document = ENCODE_FILE (document);
8379 current_dir = ENCODE_FILE (current_dir);
8380 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
8381 be a URL that is not limited to MAX_PATH chararcters. */
8382 doclen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
8383 SSDATA (document), -1, NULL, 0);
8384 doc_w = xmalloc (doclen * sizeof (wchar_t));
8385 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
8386 SSDATA (document), -1, doc_w, doclen);
8387 if (use_unicode)
8389 wchar_t current_dir_w[MAX_PATH];
8390 SHELLEXECUTEINFOW shexinfo_w;
8392 /* Encode the current directory and parameters, and convert
8393 operation to UTF-16. */
8394 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
8395 if (STRINGP (parameters))
8397 int len;
8399 parameters = ENCODE_SYSTEM (parameters);
8400 len = pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
8401 SSDATA (parameters), -1, NULL, 0);
8402 if (len > 32768)
8403 len = 32768;
8404 params_w = alloca (len * sizeof (wchar_t));
8405 pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
8406 SSDATA (parameters), -1, params_w, len);
8407 params_w[len - 1] = 0;
8409 if (STRINGP (operation))
8411 /* Assume OPERATION is pure ASCII. */
8412 const char *s = SSDATA (operation);
8413 wchar_t *d;
8414 int len = SBYTES (operation) + 1;
8416 if (len > 32768)
8417 len = 32768;
8418 d = ops_w = alloca (len * sizeof (wchar_t));
8419 while (d < ops_w + len - 1)
8420 *d++ = *s++;
8421 *d = 0;
8424 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
8425 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
8426 able to invoke verbs from shortcut menu extensions, not just
8427 static verbs listed in the Registry. */
8428 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
8429 shexinfo_w.cbSize = sizeof (shexinfo_w);
8430 shexinfo_w.fMask =
8431 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8432 shexinfo_w.hwnd = NULL;
8433 shexinfo_w.lpVerb = ops_w;
8434 shexinfo_w.lpFile = doc_w;
8435 shexinfo_w.lpParameters = params_w;
8436 shexinfo_w.lpDirectory = current_dir_w;
8437 shexinfo_w.nShow =
8438 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8439 success = ShellExecuteExW (&shexinfo_w);
8440 xfree (doc_w);
8442 else
8444 char current_dir_a[MAX_PATH];
8445 SHELLEXECUTEINFOA shexinfo_a;
8446 int codepage = codepage_for_filenames (NULL);
8447 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
8448 NULL, NULL);
8450 doc_a = xmalloc (ldoc_a);
8451 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
8452 filename_to_ansi (SSDATA (current_dir), current_dir_a);
8453 if (STRINGP (parameters))
8455 parameters = ENCODE_SYSTEM (parameters);
8456 params_a = SSDATA (parameters);
8458 if (STRINGP (operation))
8460 /* Assume OPERATION is pure ASCII. */
8461 ops_a = SSDATA (operation);
8463 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
8464 shexinfo_a.cbSize = sizeof (shexinfo_a);
8465 shexinfo_a.fMask =
8466 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8467 shexinfo_a.hwnd = NULL;
8468 shexinfo_a.lpVerb = ops_a;
8469 shexinfo_a.lpFile = doc_a;
8470 shexinfo_a.lpParameters = params_a;
8471 shexinfo_a.lpDirectory = current_dir_a;
8472 shexinfo_a.nShow =
8473 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8474 success = ShellExecuteExA (&shexinfo_a);
8475 xfree (doc_w);
8476 xfree (doc_a);
8479 if (success)
8480 return Qt;
8482 errstr = w32_strerror (0);
8484 #endif /* !CYGWIN */
8486 /* The error string might be encoded in the locale's encoding. */
8487 if (!NILP (Vlocale_coding_system))
8489 Lisp_Object decoded =
8490 code_convert_string_norecord (build_unibyte_string (errstr),
8491 Vlocale_coding_system, 0);
8492 errstr = SSDATA (decoded);
8494 error ("ShellExecute failed: %s", errstr);
8497 /* Lookup virtual keycode from string representing the name of a
8498 non-ascii keystroke into the corresponding virtual key, using
8499 lispy_function_keys. */
8500 static int
8501 lookup_vk_code (char *key)
8503 int i;
8505 for (i = 0; i < 256; i++)
8506 if (lispy_function_keys[i]
8507 && strcmp (lispy_function_keys[i], key) == 0)
8508 return i;
8510 if (w32_kbdhook_active)
8512 /* Alphanumerics map to themselves. */
8513 if (key[1] == 0)
8515 if ((key[0] >= 'A' && key[0] <= 'Z')
8516 || (key[0] >= '0' && key[0] <= '9'))
8517 return key[0];
8518 if (key[0] >= 'a' && key[0] <= 'z')
8519 return toupper(key[0]);
8523 return -1;
8526 /* Convert a one-element vector style key sequence to a hot key
8527 definition. */
8528 static Lisp_Object
8529 w32_parse_and_hook_hot_key (Lisp_Object key, int hook)
8531 /* Copied from Fdefine_key and store_in_keymap. */
8532 register Lisp_Object c;
8533 int vk_code = 0;
8534 int lisp_modifiers = 0;
8535 int w32_modifiers;
8536 Lisp_Object res = Qnil;
8537 char* vkname;
8539 CHECK_VECTOR (key);
8541 if (ASIZE (key) != 1)
8542 return Qnil;
8544 c = AREF (key, 0);
8546 if (CONSP (c) && lucid_event_type_list_p (c))
8547 c = Fevent_convert_list (c);
8549 if (! INTEGERP (c) && ! SYMBOLP (c))
8550 error ("Key definition is invalid");
8552 /* Work out the base key and the modifiers. */
8553 if (SYMBOLP (c))
8555 c = parse_modifiers (c);
8556 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8557 c = Fcar (c);
8558 if (!SYMBOLP (c))
8559 emacs_abort ();
8560 vkname = SSDATA (SYMBOL_NAME (c));
8561 /* [s-], [M-], [h-]: Register all keys for this modifier */
8562 if (w32_kbdhook_active && vkname[0] == 0)
8563 vk_code = VK_ANY;
8564 else
8565 vk_code = lookup_vk_code (vkname);
8567 else if (INTEGERP (c))
8569 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8570 /* Many ascii characters are their own virtual key code. */
8571 vk_code = XINT (c) & CHARACTERBITS;
8574 if (vk_code < 0 || vk_code > 255)
8575 return Qnil;
8577 if ((lisp_modifiers & meta_modifier) != 0
8578 && !NILP (Vw32_alt_is_meta))
8579 lisp_modifiers |= alt_modifier;
8581 /* Supply defs missing from mingw32. */
8582 #ifndef MOD_ALT
8583 #define MOD_ALT 0x0001
8584 #define MOD_CONTROL 0x0002
8585 #define MOD_SHIFT 0x0004
8586 #define MOD_WIN 0x0008
8587 #endif
8589 if (w32_kbdhook_active)
8591 /* Register Alt-x combinations. */
8592 if (lisp_modifiers & alt_modifier)
8594 hook_w32_key (hook, VK_MENU, vk_code);
8595 res = Qt;
8597 /* Register Win-x combinations based on modifier mappings. */
8598 if (((lisp_modifiers & hyper_modifier)
8599 && EQ (Vw32_lwindow_modifier, Qhyper))
8600 || ((lisp_modifiers & super_modifier)
8601 && EQ (Vw32_lwindow_modifier, Qsuper)))
8603 hook_w32_key (hook, VK_LWIN, vk_code);
8604 res = Qt;
8606 if (((lisp_modifiers & hyper_modifier)
8607 && EQ (Vw32_rwindow_modifier, Qhyper))
8608 || ((lisp_modifiers & super_modifier)
8609 && EQ (Vw32_rwindow_modifier, Qsuper)))
8611 hook_w32_key (hook, VK_RWIN, vk_code);
8612 res = Qt;
8614 return res;
8616 else
8618 /* Convert lisp modifiers to Windows hot-key form. */
8619 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8620 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8621 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8622 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8624 return HOTKEY (vk_code, w32_modifiers);
8628 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8629 Sw32_register_hot_key, 1, 1, 0,
8630 doc: /* Register KEY as a hot-key combination.
8631 Certain key combinations like Alt-Tab and Win-R are reserved for
8632 system use on Windows, and therefore are normally intercepted by the
8633 system. These key combinations can be received by registering them
8634 as hot-keys, except for Win-L which always locks the computer.
8636 On Windows 98 and ME, KEY must be a one element key definition in
8637 vector form that would be acceptable to `define-key' (e.g. [A-tab] for
8638 Alt-Tab). The meta modifier is interpreted as Alt if
8639 `w32-alt-is-meta' is t, and hyper is always interpreted as the Windows
8640 modifier keys. The return value is the hotkey-id if registered, otherwise nil.
8642 On Windows versions since NT, KEY can also be specified as [M-], [s-] or
8643 [h-] to indicate that all combinations of that key should be processed
8644 by Emacs instead of the operating system. The super and hyper
8645 modifiers are interpreted according to the current values of
8646 `w32-lwindow-modifier' and `w32-rwindow-modifier'. For instance,
8647 setting `w32-lwindow-modifier' to `super' and then calling
8648 `(register-hot-key [s-])' grabs all combinations of the left Windows
8649 key to Emacs, but leaves the right Windows key free for the operating
8650 system keyboard shortcuts. The return value is t if the call affected
8651 any key combinations, otherwise nil. */)
8652 (Lisp_Object key)
8654 key = w32_parse_and_hook_hot_key (key, 1);
8656 if (!w32_kbdhook_active
8657 && !NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8659 /* Reuse an empty slot if possible. */
8660 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8662 /* Safe to add new key to list, even if we have focus. */
8663 if (NILP (item))
8664 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8665 else
8666 XSETCAR (item, key);
8668 /* Notify input thread about new hot-key definition, so that it
8669 takes effect without needing to switch focus. */
8670 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8671 (WPARAM) XINT (key), 0);
8674 return key;
8677 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8678 Sw32_unregister_hot_key, 1, 1, 0,
8679 doc: /* Unregister KEY as a hot-key combination. */)
8680 (Lisp_Object key)
8682 Lisp_Object item;
8684 if (!INTEGERP (key))
8685 key = w32_parse_and_hook_hot_key (key, 0);
8687 if (w32_kbdhook_active)
8688 return key;
8690 item = Fmemq (key, w32_grabbed_keys);
8692 if (!NILP (item))
8694 LPARAM lparam;
8696 eassert (CONSP (item));
8697 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
8698 so that it works in a --with-wide-int build as well. */
8699 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
8701 /* Notify input thread about hot-key definition being removed, so
8702 that it takes effect without needing focus switch. */
8703 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8704 (WPARAM) XINT (XCAR (item)), lparam))
8706 MSG msg;
8707 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8709 return Qt;
8711 return Qnil;
8714 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8715 Sw32_registered_hot_keys, 0, 0, 0,
8716 doc: /* Return list of registered hot-key IDs. */)
8717 (void)
8719 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8722 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8723 Sw32_reconstruct_hot_key, 1, 1, 0,
8724 doc: /* Convert hot-key ID to a lisp key combination.
8725 usage: (w32-reconstruct-hot-key ID) */)
8726 (Lisp_Object hotkeyid)
8728 int vk_code, w32_modifiers;
8729 Lisp_Object key;
8731 CHECK_NUMBER (hotkeyid);
8733 vk_code = HOTKEY_VK_CODE (hotkeyid);
8734 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8736 if (vk_code < 256 && lispy_function_keys[vk_code])
8737 key = intern (lispy_function_keys[vk_code]);
8738 else
8739 key = make_number (vk_code);
8741 key = Fcons (key, Qnil);
8742 if (w32_modifiers & MOD_SHIFT)
8743 key = Fcons (Qshift, key);
8744 if (w32_modifiers & MOD_CONTROL)
8745 key = Fcons (Qctrl, key);
8746 if (w32_modifiers & MOD_ALT)
8747 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8748 if (w32_modifiers & MOD_WIN)
8749 key = Fcons (Qhyper, key);
8751 return key;
8754 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8755 Sw32_toggle_lock_key, 1, 2, 0,
8756 doc: /* Toggle the state of the lock key KEY.
8757 KEY can be `capslock', `kp-numlock', or `scroll'.
8758 If the optional parameter NEW-STATE is a number, then the state of KEY
8759 is set to off if the low bit of NEW-STATE is zero, otherwise on.
8760 If NEW-STATE is omitted or nil, the function toggles the state,
8762 Value is the new state of the key, or nil if the function failed
8763 to change the state. */)
8764 (Lisp_Object key, Lisp_Object new_state)
8766 int vk_code;
8767 LPARAM lparam;
8769 if (EQ (key, intern ("capslock")))
8770 vk_code = VK_CAPITAL;
8771 else if (EQ (key, intern ("kp-numlock")))
8772 vk_code = VK_NUMLOCK;
8773 else if (EQ (key, intern ("scroll")))
8774 vk_code = VK_SCROLL;
8775 else
8776 return Qnil;
8778 if (!dwWindowsThreadId)
8779 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8781 if (NILP (new_state))
8782 lparam = -1;
8783 else
8784 lparam = (XUINT (new_state)) & 1;
8785 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8786 (WPARAM) vk_code, lparam))
8788 MSG msg;
8789 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8790 return make_number (msg.wParam);
8792 return Qnil;
8795 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8796 2, 2, 0,
8797 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8799 This is a direct interface to the Windows API FindWindow function. */)
8800 (Lisp_Object class, Lisp_Object name)
8802 HWND hnd;
8804 if (!NILP (class))
8805 CHECK_STRING (class);
8806 if (!NILP (name))
8807 CHECK_STRING (name);
8809 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8810 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8811 if (!hnd)
8812 return Qnil;
8813 return Qt;
8816 DEFUN ("w32-frame-geometry", Fw32_frame_geometry, Sw32_frame_geometry, 0, 1, 0,
8817 doc: /* Return geometric attributes of FRAME.
8818 FRAME must be a live frame and defaults to the selected one. The return
8819 value is an association list of the attributes listed below. All height
8820 and width values are in pixels.
8822 `outer-position' is a cons of the outer left and top edges of FRAME
8823 relative to the origin - the position (0, 0) - of FRAME's display.
8825 `outer-size' is a cons of the outer width and height of FRAME. The
8826 outer size includes the title bar and the external borders as well as
8827 any menu and/or tool bar of frame.
8829 `external-border-size' is a cons of the horizontal and vertical width of
8830 FRAME's external borders as supplied by the window manager.
8832 `title-bar-size' is a cons of the width and height of the title bar of
8833 FRAME as supplied by the window manager. If both of them are zero,
8834 FRAME has no title bar. If only the width is zero, Emacs was not
8835 able to retrieve the width information.
8837 `menu-bar-external', if non-nil, means the menu bar is external (never
8838 included in the inner edges of FRAME).
8840 `menu-bar-size' is a cons of the width and height of the menu bar of
8841 FRAME.
8843 `tool-bar-external', if non-nil, means the tool bar is external (never
8844 included in the inner edges of FRAME).
8846 `tool-bar-position' tells on which side the tool bar on FRAME is and can
8847 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
8848 has no tool bar.
8850 `tool-bar-size' is a cons of the width and height of the tool bar of
8851 FRAME.
8853 `internal-border-width' is the width of the internal border of
8854 FRAME. */)
8855 (Lisp_Object frame)
8857 struct frame *f = decode_live_frame (frame);
8859 MENUBARINFO menu_bar;
8860 WINDOWINFO window;
8861 int left, top, right, bottom;
8862 unsigned int external_border_width, external_border_height;
8863 int title_bar_width = 0, title_bar_height = 0;
8864 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8865 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8866 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8868 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8869 return Qnil;
8871 block_input ();
8872 /* Outer rectangle and borders. */
8873 window.cbSize = sizeof (window);
8874 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8875 external_border_width = window.cxWindowBorders;
8876 external_border_height = window.cyWindowBorders;
8877 /* Title bar. */
8878 if (get_title_bar_info_fn)
8880 TITLEBAR_INFO title_bar;
8882 title_bar.cbSize = sizeof (title_bar);
8883 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8884 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8885 for (int i = 0; i < 6; i++)
8886 title_bar.rgstate[i] = 0;
8887 if (get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar)
8888 && !(title_bar.rgstate[0] & 0x00008001))
8890 title_bar_width
8891 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8892 title_bar_height
8893 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8896 else if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8897 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8898 /* Menu bar. */
8899 menu_bar.cbSize = sizeof (menu_bar);
8900 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8901 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8902 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8903 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8904 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8905 unblock_input ();
8907 left = window.rcWindow.left;
8908 top = window.rcWindow.top;
8909 right = window.rcWindow.right;
8910 bottom = window.rcWindow.bottom;
8912 /* Menu bar. */
8913 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8914 /* Fix menu bar height reported by GetMenuBarInfo. */
8915 if (menu_bar_height > single_menu_bar_height)
8916 /* A wrapped menu bar. */
8917 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8918 else if (menu_bar_height > 0)
8919 /* A single line menu bar. */
8920 menu_bar_height = single_menu_bar_height;
8922 return listn (CONSTYPE_HEAP, 10,
8923 Fcons (Qouter_position,
8924 Fcons (make_number (left), make_number (top))),
8925 Fcons (Qouter_size,
8926 Fcons (make_number (right - left),
8927 make_number (bottom - top))),
8928 Fcons (Qexternal_border_size,
8929 Fcons (make_number (external_border_width),
8930 make_number (external_border_height))),
8931 Fcons (Qtitle_bar_size,
8932 Fcons (make_number (title_bar_width),
8933 make_number (title_bar_height))),
8934 Fcons (Qmenu_bar_external, Qt),
8935 Fcons (Qmenu_bar_size,
8936 Fcons (make_number
8937 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8938 make_number (menu_bar_height))),
8939 Fcons (Qtool_bar_external, Qnil),
8940 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8941 Fcons (Qtool_bar_size,
8942 Fcons (make_number
8943 (tool_bar_height
8944 ? (right - left - 2 * external_border_width
8945 - 2 * internal_border_width)
8946 : 0),
8947 make_number (tool_bar_height))),
8948 Fcons (Qinternal_border_width,
8949 make_number (internal_border_width)));
8952 DEFUN ("w32-frame-edges", Fw32_frame_edges, Sw32_frame_edges, 0, 2, 0,
8953 doc: /* Return edge coordinates of FRAME.
8954 FRAME must be a live frame and defaults to the selected one. The return
8955 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8956 in pixels relative to the origin - the position (0, 0) - of FRAME's
8957 display.
8959 If optional argument TYPE is the symbol `outer-edges', return the outer
8960 edges of FRAME. The outer edges comprise the decorations of the window
8961 manager (like the title bar or external borders) as well as any external
8962 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8963 `native-edges' or nil, return the native edges of FRAME. The native
8964 edges exclude the decorations of the window manager and any external
8965 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8966 the inner edges of FRAME. These edges exclude title bar, any borders,
8967 menu bar or tool bar of FRAME. */)
8968 (Lisp_Object frame, Lisp_Object type)
8970 struct frame *f = decode_live_frame (frame);
8972 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8973 return Qnil;
8975 if (EQ (type, Qouter_edges))
8977 RECT rectangle;
8978 BOOL success = false;
8980 block_input ();
8981 /* Outer frame rectangle, including outer borders and title bar. */
8982 success = GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8983 unblock_input ();
8985 if (success)
8986 return list4 (make_number (rectangle.left),
8987 make_number (rectangle.top),
8988 make_number (rectangle.right),
8989 make_number (rectangle.bottom));
8990 else
8991 return Qnil;
8993 else
8995 RECT rectangle;
8996 POINT pt;
8997 int left, top, right, bottom;
8998 BOOL success;
9000 block_input ();
9001 /* Inner frame rectangle, excluding borders and title bar. */
9002 success = GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
9003 /* Get top-left corner of native rectangle in screen
9004 coordinates. */
9005 if (!success)
9007 unblock_input ();
9008 return Qnil;
9011 pt.x = 0;
9012 pt.y = 0;
9013 success = ClientToScreen (FRAME_W32_WINDOW (f), &pt);
9014 unblock_input ();
9016 if (!success)
9017 return Qnil;
9019 left = pt.x;
9020 top = pt.y;
9021 right = left + rectangle.right;
9022 bottom = top + rectangle.bottom;
9024 if (EQ (type, Qinner_edges))
9026 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
9028 return list4 (make_number (left + internal_border_width),
9029 make_number (top
9030 + FRAME_TOOL_BAR_HEIGHT (f)
9031 + internal_border_width),
9032 make_number (right - internal_border_width),
9033 make_number (bottom - internal_border_width));
9035 else
9036 return list4 (make_number (left), make_number (top),
9037 make_number (right), make_number (bottom));
9042 * w32_frame_list_z_order:
9044 * Recursively add list of all frames on the display specified via
9045 * DPYINFO and whose window-system window's parent is specified by
9046 * WINDOW to FRAMES and return FRAMES.
9048 static Lisp_Object
9049 w32_frame_list_z_order (struct w32_display_info *dpyinfo, HWND window)
9051 Lisp_Object frame, frames = Qnil;
9053 while (window)
9055 struct frame *f = x_window_to_frame (dpyinfo, window);
9057 if (f)
9059 XSETFRAME (frame, f);
9060 frames = Fcons (frame, frames);
9063 block_input ();
9064 window = GetNextWindow (window, GW_HWNDNEXT);
9065 unblock_input ();
9068 return Fnreverse (frames);
9071 DEFUN ("w32-frame-list-z-order", Fw32_frame_list_z_order,
9072 Sw32_frame_list_z_order, 0, 1, 0,
9073 doc: /* Return list of Emacs' frames, in Z (stacking) order.
9074 The optional argument DISPLAY specifies which display to ask about.
9075 DISPLAY should be either a frame or a display name (a string). If
9076 omitted or nil, that stands for the selected frame's display.
9078 As a special case, if DISPLAY is non-nil and specifies a live frame,
9079 return the child frames of that frame in Z (stacking) order.
9081 Frames are listed from topmost (first) to bottommost (last). */)
9082 (Lisp_Object display)
9084 struct w32_display_info *dpyinfo = check_x_display_info (display);
9085 HWND window;
9087 block_input ();
9088 if (FRAMEP (display) && FRAME_LIVE_P (XFRAME (display)))
9089 window = GetWindow (FRAME_W32_WINDOW (XFRAME (display)), GW_CHILD);
9090 else
9091 window = GetTopWindow (NULL);
9092 unblock_input ();
9094 return w32_frame_list_z_order (dpyinfo, window);
9098 * w32_frame_restack:
9100 * Restack frame F1 below frame F2, above if ABOVE_FLAG is non-nil. In
9101 * practice this is a two-step action: The first step removes F1's
9102 * window-system window from the display. The second step reinserts
9103 * F1's window below (above if ABOVE_FLAG is true) that of F2.
9105 static void
9106 w32_frame_restack (struct frame *f1, struct frame *f2, bool above_flag)
9108 HWND hwnd1 = FRAME_W32_WINDOW (f1);
9109 HWND hwnd2 = FRAME_W32_WINDOW (f2);
9111 block_input ();
9112 if (above_flag)
9113 /* Put F1 above F2 in the z-order. */
9115 if (GetNextWindow (hwnd1, GW_HWNDNEXT) != hwnd2)
9117 /* Make sure F1 is below F2 first because we must not
9118 change the relative position of F2 wrt any other
9119 window but F1. */
9120 if (GetNextWindow (hwnd2, GW_HWNDNEXT) != hwnd1)
9121 SetWindowPos (hwnd1, hwnd2, 0, 0, 0, 0,
9122 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
9123 | SWP_FRAMECHANGED);
9124 /* Now put F1 above F2. */
9125 SetWindowPos (hwnd2, hwnd1, 0, 0, 0, 0,
9126 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
9127 | SWP_FRAMECHANGED);
9130 else if (GetNextWindow (hwnd2, GW_HWNDNEXT) != hwnd1)
9131 /* Put F1 below F2 in the z-order. */
9132 SetWindowPos (hwnd1, hwnd2, 0, 0, 0, 0,
9133 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
9134 | SWP_FRAMECHANGED);
9135 unblock_input ();
9138 DEFUN ("w32-frame-restack", Fw32_frame_restack, Sw32_frame_restack, 2, 3, 0,
9139 doc: /* Restack FRAME1 below FRAME2.
9140 This means that if both frames are visible and the display areas of
9141 these frames overlap, FRAME2 (partially) obscures FRAME1. If optional
9142 third argument ABOVE is non-nil, restack FRAME1 above FRAME2. This
9143 means that if both frames are visible and the display areas of these
9144 frames overlap, FRAME1 (partially) obscures FRAME2.
9146 This may be thought of as an atomic action performed in two steps: The
9147 first step removes FRAME1's window-system window from the display. The
9148 second step reinserts FRAME1's window below (above if ABOVE is true)
9149 that of FRAME2. Hence the position of FRAME2 in its display's Z
9150 \(stacking) order relative to all other frames excluding FRAME1 remains
9151 unaltered.
9153 Some window managers may refuse to restack windows. */)
9154 (Lisp_Object frame1, Lisp_Object frame2, Lisp_Object above)
9156 struct frame *f1 = decode_live_frame (frame1);
9157 struct frame *f2 = decode_live_frame (frame2);
9159 if (FRAME_W32_P (f1) && FRAME_W32_P (f2))
9161 w32_frame_restack (f1, f2, !NILP (above));
9162 return Qt;
9164 else
9166 error ("Cannot restack frames");
9167 return Qnil;
9171 DEFUN ("w32-mouse-absolute-pixel-position", Fw32_mouse_absolute_pixel_position,
9172 Sw32_mouse_absolute_pixel_position, 0, 0, 0,
9173 doc: /* Return absolute position of mouse cursor in pixels.
9174 The position is returned as a cons cell (X . Y) of the coordinates of
9175 the mouse cursor position in pixels relative to a position (0, 0) of the
9176 selected frame's display. */)
9177 (void)
9179 POINT pt;
9181 block_input ();
9182 GetCursorPos (&pt);
9183 unblock_input ();
9185 return Fcons (make_number (pt.x), make_number (pt.y));
9188 DEFUN ("w32-set-mouse-absolute-pixel-position", Fw32_set_mouse_absolute_pixel_position,
9189 Sw32_set_mouse_absolute_pixel_position, 2, 2, 0,
9190 doc: /* Move mouse pointer to absolute pixel position (X, Y).
9191 The coordinates X and Y are interpreted in pixels relative to a position
9192 \(0, 0) of the selected frame's display. */)
9193 (Lisp_Object x, Lisp_Object y)
9195 UINT trail_num = 0;
9196 BOOL ret = false;
9198 CHECK_TYPE_RANGED_INTEGER (int, x);
9199 CHECK_TYPE_RANGED_INTEGER (int, y);
9201 block_input ();
9202 /* When "mouse trails" are in effect, moving the mouse cursor
9203 sometimes leaves behind an annoying "ghost" of the pointer.
9204 Avoid that by momentarily switching off mouse trails. */
9205 if (os_subtype == OS_NT
9206 && w32_major_version + w32_minor_version >= 6)
9207 ret = SystemParametersInfo (SPI_GETMOUSETRAILS, 0, &trail_num, 0);
9208 SetCursorPos (XINT (x), XINT (y));
9209 if (ret)
9210 SystemParametersInfo (SPI_SETMOUSETRAILS, trail_num, NULL, 0);
9211 unblock_input ();
9213 return Qnil;
9216 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
9217 doc: /* Get power status information from Windows system.
9219 The following %-sequences are provided:
9220 %L AC line status (verbose)
9221 %B Battery status (verbose)
9222 %b Battery status, empty means high, `-' means low,
9223 `!' means critical, and `+' means charging
9224 %p Battery load percentage
9225 %s Remaining time (to charge or discharge) in seconds
9226 %m Remaining time (to charge or discharge) in minutes
9227 %h Remaining time (to charge or discharge) in hours
9228 %t Remaining time (to charge or discharge) in the form `h:min' */)
9229 (void)
9231 Lisp_Object status = Qnil;
9233 SYSTEM_POWER_STATUS system_status;
9234 if (GetSystemPowerStatus (&system_status))
9236 Lisp_Object line_status, battery_status, battery_status_symbol;
9237 Lisp_Object load_percentage, seconds, minutes, hours, remain;
9239 long seconds_left = (long) system_status.BatteryLifeTime;
9241 if (system_status.ACLineStatus == 0)
9242 line_status = build_string ("off-line");
9243 else if (system_status.ACLineStatus == 1)
9244 line_status = build_string ("on-line");
9245 else
9246 line_status = build_string ("N/A");
9248 if (system_status.BatteryFlag & 128)
9250 battery_status = build_string ("N/A");
9251 battery_status_symbol = empty_unibyte_string;
9253 else if (system_status.BatteryFlag & 8)
9255 battery_status = build_string ("charging");
9256 battery_status_symbol = build_string ("+");
9257 if (system_status.BatteryFullLifeTime != -1L)
9258 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
9260 else if (system_status.BatteryFlag & 4)
9262 battery_status = build_string ("critical");
9263 battery_status_symbol = build_string ("!");
9265 else if (system_status.BatteryFlag & 2)
9267 battery_status = build_string ("low");
9268 battery_status_symbol = build_string ("-");
9270 else if (system_status.BatteryFlag & 1)
9272 battery_status = build_string ("high");
9273 battery_status_symbol = empty_unibyte_string;
9275 else
9277 battery_status = build_string ("medium");
9278 battery_status_symbol = empty_unibyte_string;
9281 if (system_status.BatteryLifePercent > 100)
9282 load_percentage = build_string ("N/A");
9283 else
9285 char buffer[16];
9286 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
9287 load_percentage = build_string (buffer);
9290 if (seconds_left < 0)
9291 seconds = minutes = hours = remain = build_string ("N/A");
9292 else
9294 long m;
9295 double h;
9296 char buffer[16];
9297 snprintf (buffer, 16, "%ld", seconds_left);
9298 seconds = build_string (buffer);
9300 m = seconds_left / 60;
9301 snprintf (buffer, 16, "%ld", m);
9302 minutes = build_string (buffer);
9304 h = seconds_left / 3600.0;
9305 snprintf (buffer, 16, "%3.1f", h);
9306 hours = build_string (buffer);
9308 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
9309 remain = build_string (buffer);
9312 status = listn (CONSTYPE_HEAP, 8,
9313 Fcons (make_number ('L'), line_status),
9314 Fcons (make_number ('B'), battery_status),
9315 Fcons (make_number ('b'), battery_status_symbol),
9316 Fcons (make_number ('p'), load_percentage),
9317 Fcons (make_number ('s'), seconds),
9318 Fcons (make_number ('m'), minutes),
9319 Fcons (make_number ('h'), hours),
9320 Fcons (make_number ('t'), remain));
9322 return status;
9326 #ifdef WINDOWSNT
9327 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
9328 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
9329 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
9330 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
9332 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
9333 doc: /* Return storage information about the file system FILENAME is on.
9334 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
9335 storage of the file system, FREE is the free storage, and AVAIL is the
9336 storage available to a non-superuser. All 3 numbers are in bytes.
9337 If the underlying system call fails, value is nil. */)
9338 (Lisp_Object filename)
9340 Lisp_Object encoded, value;
9342 CHECK_STRING (filename);
9343 filename = Fexpand_file_name (filename, Qnil);
9344 encoded = ENCODE_FILE (filename);
9346 value = Qnil;
9348 /* Determining the required information on Windows turns out, sadly,
9349 to be more involved than one would hope. The original Windows API
9350 call for this will return bogus information on some systems, but we
9351 must dynamically probe for the replacement api, since that was
9352 added rather late on. */
9354 HMODULE hKernel = GetModuleHandle ("kernel32");
9355 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
9356 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
9357 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
9358 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
9359 bool have_pfn_GetDiskFreeSpaceEx =
9360 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
9361 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
9363 /* On Windows, we may need to specify the root directory of the
9364 volume holding FILENAME. */
9365 char rootname[MAX_UTF8_PATH];
9366 wchar_t rootname_w[MAX_PATH];
9367 char rootname_a[MAX_PATH];
9368 char *name = SSDATA (encoded);
9369 BOOL result;
9371 /* find the root name of the volume if given */
9372 if (isalpha (name[0]) && name[1] == ':')
9374 rootname[0] = name[0];
9375 rootname[1] = name[1];
9376 rootname[2] = '\\';
9377 rootname[3] = 0;
9379 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
9381 char *str = rootname;
9382 int slashes = 4;
9385 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
9386 break;
9387 *str++ = *name++;
9389 while ( *name );
9391 *str++ = '\\';
9392 *str = 0;
9395 if (w32_unicode_filenames)
9396 filename_to_utf16 (rootname, rootname_w);
9397 else
9398 filename_to_ansi (rootname, rootname_a);
9400 if (have_pfn_GetDiskFreeSpaceEx)
9402 /* Unsigned large integers cannot be cast to double, so
9403 use signed ones instead. */
9404 LARGE_INTEGER availbytes;
9405 LARGE_INTEGER freebytes;
9406 LARGE_INTEGER totalbytes;
9408 if (w32_unicode_filenames)
9409 result = pfn_GetDiskFreeSpaceExW (rootname_w,
9410 (ULARGE_INTEGER *)&availbytes,
9411 (ULARGE_INTEGER *)&totalbytes,
9412 (ULARGE_INTEGER *)&freebytes);
9413 else
9414 result = pfn_GetDiskFreeSpaceExA (rootname_a,
9415 (ULARGE_INTEGER *)&availbytes,
9416 (ULARGE_INTEGER *)&totalbytes,
9417 (ULARGE_INTEGER *)&freebytes);
9418 if (result)
9419 value = list3 (make_float ((double) totalbytes.QuadPart),
9420 make_float ((double) freebytes.QuadPart),
9421 make_float ((double) availbytes.QuadPart));
9423 else
9425 DWORD sectors_per_cluster;
9426 DWORD bytes_per_sector;
9427 DWORD free_clusters;
9428 DWORD total_clusters;
9430 if (w32_unicode_filenames)
9431 result = GetDiskFreeSpaceW (rootname_w,
9432 &sectors_per_cluster,
9433 &bytes_per_sector,
9434 &free_clusters,
9435 &total_clusters);
9436 else
9437 result = GetDiskFreeSpaceA (rootname_a,
9438 &sectors_per_cluster,
9439 &bytes_per_sector,
9440 &free_clusters,
9441 &total_clusters);
9442 if (result)
9443 value = list3 (make_float ((double) total_clusters
9444 * sectors_per_cluster * bytes_per_sector),
9445 make_float ((double) free_clusters
9446 * sectors_per_cluster * bytes_per_sector),
9447 make_float ((double) free_clusters
9448 * sectors_per_cluster * bytes_per_sector));
9452 return value;
9454 #endif /* WINDOWSNT */
9457 #ifdef WINDOWSNT
9458 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
9459 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
9460 (void)
9462 static char pname_buf[256];
9463 int err;
9464 HANDLE hPrn;
9465 PRINTER_INFO_2W *ppi2w = NULL;
9466 PRINTER_INFO_2A *ppi2a = NULL;
9467 DWORD dwNeeded = 0, dwReturned = 0;
9468 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
9469 char port_name[MAX_UTF8_PATH];
9471 /* Retrieve the default string from Win.ini (the registry).
9472 * String will be in form "printername,drivername,portname".
9473 * This is the most portable way to get the default printer. */
9474 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
9475 return Qnil;
9476 /* printername precedes first "," character */
9477 strtok (pname_buf, ",");
9478 /* We want to know more than the printer name */
9479 if (!OpenPrinter (pname_buf, &hPrn, NULL))
9480 return Qnil;
9481 /* GetPrinterW is not supported by unicows.dll. */
9482 if (w32_unicode_filenames && os_subtype != OS_9X)
9483 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
9484 else
9485 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
9486 if (dwNeeded == 0)
9488 ClosePrinter (hPrn);
9489 return Qnil;
9491 /* Call GetPrinter again with big enough memory block. */
9492 if (w32_unicode_filenames && os_subtype != OS_9X)
9494 /* Allocate memory for the PRINTER_INFO_2 struct. */
9495 ppi2w = xmalloc (dwNeeded);
9496 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
9497 ClosePrinter (hPrn);
9498 if (!err)
9500 xfree (ppi2w);
9501 return Qnil;
9504 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
9505 && ppi2w->pServerName)
9507 filename_from_utf16 (ppi2w->pServerName, server_name);
9508 filename_from_utf16 (ppi2w->pShareName, share_name);
9510 else
9512 server_name[0] = '\0';
9513 filename_from_utf16 (ppi2w->pPortName, port_name);
9516 else
9518 ppi2a = xmalloc (dwNeeded);
9519 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
9520 ClosePrinter (hPrn);
9521 if (!err)
9523 xfree (ppi2a);
9524 return Qnil;
9527 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
9528 && ppi2a->pServerName)
9530 filename_from_ansi (ppi2a->pServerName, server_name);
9531 filename_from_ansi (ppi2a->pShareName, share_name);
9533 else
9535 server_name[0] = '\0';
9536 filename_from_ansi (ppi2a->pPortName, port_name);
9540 if (server_name[0])
9542 /* a remote printer */
9543 if (server_name[0] == '\\')
9544 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
9545 share_name);
9546 else
9547 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
9548 share_name);
9549 pname_buf[sizeof (pname_buf) - 1] = '\0';
9551 else
9553 /* a local printer */
9554 strncpy (pname_buf, port_name, sizeof (pname_buf));
9555 pname_buf[sizeof (pname_buf) - 1] = '\0';
9556 /* `pPortName' can include several ports, delimited by ','.
9557 * we only use the first one. */
9558 strtok (pname_buf, ",");
9561 return DECODE_FILE (build_unibyte_string (pname_buf));
9563 #endif /* WINDOWSNT */
9566 /* Equivalent of strerror for W32 error codes. */
9567 char *
9568 w32_strerror (int error_no)
9570 static char buf[500];
9571 DWORD ret;
9573 if (error_no == 0)
9574 error_no = GetLastError ();
9576 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
9577 FORMAT_MESSAGE_IGNORE_INSERTS,
9578 NULL,
9579 error_no,
9580 0, /* choose most suitable language */
9581 buf, sizeof (buf), NULL);
9583 while (ret > 0 && (buf[ret - 1] == '\n' ||
9584 buf[ret - 1] == '\r' ))
9585 --ret;
9586 buf[ret] = '\0';
9587 if (!ret)
9588 sprintf (buf, "w32 error %d", error_no);
9590 return buf;
9593 /* For convenience when debugging. (You cannot call GetLastError
9594 directly from GDB: it will crash, because it uses the __stdcall
9595 calling convention, not the _cdecl convention assumed by GDB.) */
9596 DWORD w32_last_error (void);
9598 DWORD
9599 w32_last_error (void)
9601 return GetLastError ();
9604 /* Cache information describing the NT system for later use. */
9605 void
9606 cache_system_info (void)
9608 union
9610 struct info
9612 char major;
9613 char minor;
9614 short platform;
9615 } info;
9616 DWORD data;
9617 } version;
9619 /* Cache the module handle of Emacs itself. */
9620 hinst = GetModuleHandle (NULL);
9622 /* Cache the version of the operating system. */
9623 version.data = GetVersion ();
9624 w32_major_version = version.info.major;
9625 w32_minor_version = version.info.minor;
9627 if (version.info.platform & 0x8000)
9628 os_subtype = OS_9X;
9629 else
9630 os_subtype = OS_NT;
9632 /* Cache page size, allocation unit, processor type, etc. */
9633 GetSystemInfo (&sysinfo_cache);
9634 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
9636 /* Cache os info. */
9637 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
9638 GetVersionEx (&osinfo_cache);
9640 w32_build_number = osinfo_cache.dwBuildNumber;
9641 if (os_subtype == OS_9X)
9642 w32_build_number &= 0xffff;
9644 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
9647 #ifdef EMACSDEBUG
9648 void
9649 _DebPrint (const char *fmt, ...)
9651 char buf[1024];
9652 va_list args;
9654 va_start (args, fmt);
9655 vsprintf (buf, fmt, args);
9656 va_end (args);
9657 #if CYGWIN
9658 fprintf (stderr, "%s", buf);
9659 #endif
9660 OutputDebugString (buf);
9662 #endif
9665 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
9667 int cur_state = (GetKeyState (vk_code) & 1);
9669 if (NILP (new_state)
9670 || (NUMBERP (new_state)
9671 && ((XUINT (new_state)) & 1) != cur_state))
9673 #ifdef WINDOWSNT
9674 faked_key = vk_code;
9675 #endif /* WINDOWSNT */
9677 keybd_event ((BYTE) vk_code,
9678 (BYTE) MapVirtualKey (vk_code, 0),
9679 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9680 keybd_event ((BYTE) vk_code,
9681 (BYTE) MapVirtualKey (vk_code, 0),
9682 KEYEVENTF_EXTENDEDKEY | 0, 0);
9683 keybd_event ((BYTE) vk_code,
9684 (BYTE) MapVirtualKey (vk_code, 0),
9685 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9686 cur_state = !cur_state;
9689 return cur_state;
9692 /* Translate console modifiers to emacs modifiers.
9693 German keyboard support (Kai Morgan Zeise 2/18/95). */
9695 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
9697 int retval = 0;
9699 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
9700 pressed, first remove those modifiers. */
9701 if (!NILP (Vw32_recognize_altgr)
9702 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9703 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9704 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
9706 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
9707 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
9709 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9711 retval |= ctrl_modifier;
9712 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9713 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9714 retval |= meta_modifier;
9717 if (mods & LEFT_WIN_PRESSED)
9718 retval |= w32_key_to_modifier (VK_LWIN);
9719 if (mods & RIGHT_WIN_PRESSED)
9720 retval |= w32_key_to_modifier (VK_RWIN);
9721 if (mods & APPS_PRESSED)
9722 retval |= w32_key_to_modifier (VK_APPS);
9723 if (mods & SCROLLLOCK_ON)
9724 retval |= w32_key_to_modifier (VK_SCROLL);
9726 /* Just in case someone wanted the original behavior, make it
9727 optional by setting w32-capslock-is-shiftlock to t. */
9728 if (NILP (Vw32_capslock_is_shiftlock)
9729 /* Keys that should _not_ be affected by CapsLock. */
9730 && ( (key == VK_BACK)
9731 || (key == VK_TAB)
9732 || (key == VK_CLEAR)
9733 || (key == VK_RETURN)
9734 || (key == VK_ESCAPE)
9735 || ((key >= VK_SPACE) && (key <= VK_HELP))
9736 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
9737 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
9740 /* Only consider shift state. */
9741 if ((mods & SHIFT_PRESSED) != 0)
9742 retval |= shift_modifier;
9744 else
9746 /* Ignore CapsLock state if not enabled. */
9747 if (NILP (Vw32_enable_caps_lock))
9748 mods &= ~CAPSLOCK_ON;
9749 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
9750 retval |= shift_modifier;
9753 return retval;
9756 /* The return code indicates key code size. cpID is the codepage to
9757 use for translation to Unicode; -1 means use the current console
9758 input codepage. */
9760 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
9762 unsigned int key_code = event->wVirtualKeyCode;
9763 unsigned int mods = event->dwControlKeyState;
9764 BYTE keystate[256];
9765 static BYTE ansi_code[4];
9766 static int isdead = 0;
9768 if (isdead == 2)
9770 event->uChar.AsciiChar = ansi_code[2];
9771 isdead = 0;
9772 return 1;
9774 if (event->uChar.AsciiChar != 0)
9775 return 1;
9777 memset (keystate, 0, sizeof (keystate));
9778 keystate[key_code] = 0x80;
9779 if (mods & SHIFT_PRESSED)
9780 keystate[VK_SHIFT] = 0x80;
9781 if (mods & CAPSLOCK_ON)
9782 keystate[VK_CAPITAL] = 1;
9783 /* If we recognize right-alt and left-ctrl as AltGr, set the key
9784 states accordingly before invoking ToAscii. */
9785 if (!NILP (Vw32_recognize_altgr)
9786 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
9788 keystate[VK_CONTROL] = 0x80;
9789 keystate[VK_LCONTROL] = 0x80;
9790 keystate[VK_MENU] = 0x80;
9791 keystate[VK_RMENU] = 0x80;
9794 #if 0
9795 /* Because of an OS bug, ToAscii corrupts the stack when called to
9796 convert a dead key in console mode on NT4. Unfortunately, trying
9797 to check for dead keys using MapVirtualKey doesn't work either -
9798 these functions apparently use internal information about keyboard
9799 layout which doesn't get properly updated in console programs when
9800 changing layout (though apparently it gets partly updated,
9801 otherwise ToAscii wouldn't crash). */
9802 if (is_dead_key (event->wVirtualKeyCode))
9803 return 0;
9804 #endif
9806 /* On NT, call ToUnicode instead and then convert to the current
9807 console input codepage. */
9808 if (os_subtype == OS_NT)
9810 WCHAR buf[128];
9812 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
9813 keystate, buf, 128, 0);
9814 if (isdead > 0)
9816 /* When we are called from the GUI message processing code,
9817 we are passed the current keyboard codepage, a positive
9818 number, to use below. */
9819 if (cpId == -1)
9820 cpId = GetConsoleCP ();
9822 event->uChar.UnicodeChar = buf[isdead - 1];
9823 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
9824 (LPSTR)ansi_code, 4, NULL, NULL);
9826 else
9827 isdead = 0;
9829 else
9831 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
9832 keystate, (LPWORD) ansi_code, 0);
9835 if (isdead == 0)
9836 return 0;
9837 event->uChar.AsciiChar = ansi_code[0];
9838 return isdead;
9842 void
9843 w32_sys_ring_bell (struct frame *f)
9845 if (sound_type == 0xFFFFFFFF)
9847 Beep (666, 100);
9849 else if (sound_type == MB_EMACS_SILENT)
9851 /* Do nothing. */
9853 else
9854 MessageBeep (sound_type);
9857 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
9858 0, 0, 0,
9859 doc: /* Return non-nil when a menu-bar menu is being used.
9860 Internal use only. */)
9861 (void)
9863 return menubar_in_use ? Qt : Qnil;
9866 #if defined WINDOWSNT && !defined HAVE_DBUS
9868 /***********************************************************************
9869 Tray notifications
9870 ***********************************************************************/
9871 /* A private struct declaration to avoid compile-time limits. */
9872 typedef struct MY_NOTIFYICONDATAW {
9873 DWORD cbSize;
9874 HWND hWnd;
9875 UINT uID;
9876 UINT uFlags;
9877 UINT uCallbackMessage;
9878 HICON hIcon;
9879 WCHAR szTip[128];
9880 DWORD dwState;
9881 DWORD dwStateMask;
9882 WCHAR szInfo[256];
9883 _ANONYMOUS_UNION union {
9884 UINT uTimeout;
9885 UINT uVersion;
9886 } DUMMYUNIONNAME;
9887 WCHAR szInfoTitle[64];
9888 DWORD dwInfoFlags;
9889 GUID guidItem;
9890 HICON hBalloonIcon;
9891 } MY_NOTIFYICONDATAW;
9893 #define MYNOTIFYICONDATAW_V1_SIZE offsetof (MY_NOTIFYICONDATAW, szTip[64])
9894 #define MYNOTIFYICONDATAW_V2_SIZE offsetof (MY_NOTIFYICONDATAW, guidItem)
9895 #define MYNOTIFYICONDATAW_V3_SIZE offsetof (MY_NOTIFYICONDATAW, hBalloonIcon)
9896 #ifndef NIF_INFO
9897 # define NIF_INFO 0x00000010
9898 #endif
9899 #ifndef NIIF_NONE
9900 # define NIIF_NONE 0x00000000
9901 #endif
9902 #ifndef NIIF_INFO
9903 # define NIIF_INFO 0x00000001
9904 #endif
9905 #ifndef NIIF_WARNING
9906 # define NIIF_WARNING 0x00000002
9907 #endif
9908 #ifndef NIIF_ERROR
9909 # define NIIF_ERROR 0x00000003
9910 #endif
9913 #define EMACS_TRAY_NOTIFICATION_ID 42 /* arbitrary */
9914 #define EMACS_NOTIFICATION_MSG (WM_APP + 1)
9916 enum NI_Severity {
9917 Ni_None,
9918 Ni_Info,
9919 Ni_Warn,
9920 Ni_Err
9923 /* Report the version of a DLL given by its name. The return value is
9924 constructed using MAKEDLLVERULL. */
9925 static ULONGLONG
9926 get_dll_version (const char *dll_name)
9928 ULONGLONG version = 0;
9929 HINSTANCE hdll = LoadLibrary (dll_name);
9931 if (hdll)
9933 DLLGETVERSIONPROC pDllGetVersion
9934 = (DLLGETVERSIONPROC) GetProcAddress (hdll, "DllGetVersion");
9936 if (pDllGetVersion)
9938 DLLVERSIONINFO dvi;
9939 HRESULT result;
9941 memset (&dvi, 0, sizeof(dvi));
9942 dvi.cbSize = sizeof(dvi);
9943 result = pDllGetVersion (&dvi);
9944 if (SUCCEEDED (result))
9945 version = MAKEDLLVERULL (dvi.dwMajorVersion, dvi.dwMinorVersion,
9946 0, 0);
9948 FreeLibrary (hdll);
9951 return version;
9954 /* Return the number of bytes in UTF-8 encoded string STR that
9955 corresponds to at most LIM characters. If STR ends before LIM
9956 characters, return the number of bytes in STR including the
9957 terminating null byte. */
9958 static int
9959 utf8_mbslen_lim (const char *str, int lim)
9961 const char *p = str;
9962 int mblen = 0, nchars = 0;
9964 while (*p && nchars < lim)
9966 int nbytes = CHAR_BYTES (*p);
9968 mblen += nbytes;
9969 nchars++;
9970 p += nbytes;
9973 if (!*p && nchars < lim)
9974 mblen++;
9976 return mblen;
9979 /* Low-level subroutine to show tray notifications. All strings are
9980 supposed to be unibyte UTF-8 encoded by the caller. */
9981 static EMACS_INT
9982 add_tray_notification (struct frame *f, const char *icon, const char *tip,
9983 enum NI_Severity severity, unsigned timeout,
9984 const char *title, const char *msg)
9986 EMACS_INT retval = EMACS_TRAY_NOTIFICATION_ID;
9988 if (FRAME_W32_P (f))
9990 MY_NOTIFYICONDATAW nidw;
9991 ULONGLONG shell_dll_version = get_dll_version ("Shell32.dll");
9992 wchar_t tipw[128], msgw[256], titlew[64];
9993 int tiplen;
9995 memset (&nidw, 0, sizeof(nidw));
9997 /* MSDN says the full struct is supported since Vista, whose
9998 Shell32.dll version is said to be 6.0.6. But DllGetVersion
9999 cannot report the 3rd field value, it reports "build number"
10000 instead, which is something else. So we use the Windows 7's
10001 version 6.1 as cutoff, and Vista loses. (Actually, the loss
10002 is not a real one, since we don't expose the hBalloonIcon
10003 member of the struct to Lisp.) */
10004 if (shell_dll_version >= MAKEDLLVERULL (6, 1, 0, 0)) /* >= Windows 7 */
10005 nidw.cbSize = sizeof (nidw);
10006 else if (shell_dll_version >= MAKEDLLVERULL (6, 0, 0, 0)) /* XP */
10007 nidw.cbSize = MYNOTIFYICONDATAW_V3_SIZE;
10008 else if (shell_dll_version >= MAKEDLLVERULL (5, 0, 0, 0)) /* W2K */
10009 nidw.cbSize = MYNOTIFYICONDATAW_V2_SIZE;
10010 else
10011 nidw.cbSize = MYNOTIFYICONDATAW_V1_SIZE; /* < W2K */
10012 nidw.hWnd = FRAME_W32_WINDOW (f);
10013 nidw.uID = EMACS_TRAY_NOTIFICATION_ID;
10014 nidw.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO;
10015 nidw.uCallbackMessage = EMACS_NOTIFICATION_MSG;
10016 if (!*icon)
10017 nidw.hIcon = LoadIcon (hinst, EMACS_CLASS);
10018 else
10020 if (w32_unicode_filenames)
10022 wchar_t icon_w[MAX_PATH];
10024 if (filename_to_utf16 (icon, icon_w) != 0)
10026 errno = ENOENT;
10027 return -1;
10029 nidw.hIcon = LoadImageW (NULL, icon_w, IMAGE_ICON, 0, 0,
10030 LR_DEFAULTSIZE | LR_LOADFROMFILE);
10032 else
10034 char icon_a[MAX_PATH];
10036 if (filename_to_ansi (icon, icon_a) != 0)
10038 errno = ENOENT;
10039 return -1;
10041 nidw.hIcon = LoadImageA (NULL, icon_a, IMAGE_ICON, 0, 0,
10042 LR_DEFAULTSIZE | LR_LOADFROMFILE);
10045 if (!nidw.hIcon)
10047 switch (GetLastError ())
10049 case ERROR_FILE_NOT_FOUND:
10050 errno = ENOENT;
10051 break;
10052 default:
10053 errno = ENOMEM;
10054 break;
10056 return -1;
10059 /* Windows 9X and NT4 support only 64 characters in the Tip,
10060 later versions support up to 128. */
10061 if (nidw.cbSize == MYNOTIFYICONDATAW_V1_SIZE)
10063 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10064 tip, utf8_mbslen_lim (tip, 63),
10065 tipw, 64);
10066 if (tiplen >= 63)
10067 tipw[63] = 0;
10069 else
10071 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10072 tip, utf8_mbslen_lim (tip, 127),
10073 tipw, 128);
10074 if (tiplen >= 127)
10075 tipw[127] = 0;
10077 if (tiplen == 0)
10079 errno = EINVAL;
10080 retval = -1;
10081 goto done;
10083 wcscpy (nidw.szTip, tipw);
10085 /* The rest of the structure is only supported since Windows 2000. */
10086 if (nidw.cbSize > MYNOTIFYICONDATAW_V1_SIZE)
10088 int slen;
10090 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10091 msg, utf8_mbslen_lim (msg, 255),
10092 msgw, 256);
10093 if (slen >= 255)
10094 msgw[255] = 0;
10095 else if (slen == 0)
10097 errno = EINVAL;
10098 retval = -1;
10099 goto done;
10101 wcscpy (nidw.szInfo, msgw);
10102 nidw.uTimeout = timeout;
10103 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10104 title, utf8_mbslen_lim (title, 63),
10105 titlew, 64);
10106 if (slen >= 63)
10107 titlew[63] = 0;
10108 else if (slen == 0)
10110 errno = EINVAL;
10111 retval = -1;
10112 goto done;
10114 wcscpy (nidw.szInfoTitle, titlew);
10116 switch (severity)
10118 case Ni_None:
10119 nidw.dwInfoFlags = NIIF_NONE;
10120 break;
10121 case Ni_Info:
10122 default:
10123 nidw.dwInfoFlags = NIIF_INFO;
10124 break;
10125 case Ni_Warn:
10126 nidw.dwInfoFlags = NIIF_WARNING;
10127 break;
10128 case Ni_Err:
10129 nidw.dwInfoFlags = NIIF_ERROR;
10130 break;
10134 if (!Shell_NotifyIconW (NIM_ADD, (PNOTIFYICONDATAW)&nidw))
10136 /* GetLastError returns meaningless results when
10137 Shell_NotifyIcon fails. */
10138 DebPrint (("Shell_NotifyIcon ADD failed (err=%d)\n",
10139 GetLastError ()));
10140 errno = EINVAL;
10141 retval = -1;
10143 done:
10144 if (*icon && !DestroyIcon (nidw.hIcon))
10145 DebPrint (("DestroyIcon failed (err=%d)\n", GetLastError ()));
10147 return retval;
10150 /* Low-level subroutine to remove a tray notification. Note: we only
10151 pass the minimum data about the notification: its ID and the handle
10152 of the window to which it sends messages. MSDN doesn't say this is
10153 enough, but it works in practice. This allows us to avoid keeping
10154 the notification data around after we show the notification. */
10155 static void
10156 delete_tray_notification (struct frame *f, int id)
10158 if (FRAME_W32_P (f))
10160 MY_NOTIFYICONDATAW nidw;
10162 memset (&nidw, 0, sizeof(nidw));
10163 nidw.hWnd = FRAME_W32_WINDOW (f);
10164 nidw.uID = id;
10166 if (!Shell_NotifyIconW (NIM_DELETE, (PNOTIFYICONDATAW)&nidw))
10168 /* GetLastError returns meaningless results when
10169 Shell_NotifyIcon fails. */
10170 DebPrint (("Shell_NotifyIcon DELETE failed\n"));
10171 errno = EINVAL;
10172 return;
10175 return;
10178 DEFUN ("w32-notification-notify",
10179 Fw32_notification_notify, Sw32_notification_notify,
10180 0, MANY, 0,
10181 doc: /* Display an MS-Windows tray notification as specified by PARAMS.
10183 Value is the integer unique ID of the notification that can be used
10184 to remove the notification using `w32-notification-close', which see.
10185 If the function fails, the return value is nil.
10187 Tray notifications, a.k.a. \"taskbar messages\", are messages that
10188 inform the user about events unrelated to the current user activity,
10189 such as a significant system event, by briefly displaying informative
10190 text in a balloon from an icon in the notification area of the taskbar.
10192 Parameters in PARAMS are specified as keyword/value pairs. All the
10193 parameters are optional, but if no parameters are specified, the
10194 function will do nothing and return nil.
10196 The following parameters are supported:
10198 :icon ICON -- Display ICON in the system tray. If ICON is a string,
10199 it should specify a file name from which to load the
10200 icon; the specified file should be a .ico Windows icon
10201 file. If ICON is not a string, or if this parameter
10202 is not specified, the standard Emacs icon will be used.
10204 :tip TIP -- Use TIP as the tooltip for the notification. If TIP
10205 is a string, this is the text of a tooltip that will
10206 be shown when the mouse pointer hovers over the tray
10207 icon added by the notification. If TIP is not a
10208 string, or if this parameter is not specified, the
10209 default tooltip text is \"Emacs notification\". The
10210 tooltip text can be up to 127 characters long (63
10211 on Windows versions before W2K). Longer strings
10212 will be truncated.
10214 :level LEVEL -- Notification severity level, one of `info',
10215 `warning', or `error'. If given, the value
10216 determines the icon displayed to the left of the
10217 notification title, but only if the `:title'
10218 parameter (see below) is also specified and is a
10219 string.
10221 :title TITLE -- The title of the notification. If TITLE is a string,
10222 it is displayed in a larger font immediately above
10223 the body text. The title text can be up to 63
10224 characters long; longer text will be truncated.
10226 :body BODY -- The body of the notification. If BODY is a string,
10227 it specifies the text of the notification message.
10228 Use embedded newlines to control how the text is
10229 broken into lines. The body text can be up to 255
10230 characters long, and will be truncated if it's longer.
10232 Note that versions of Windows before W2K support only `:icon' and `:tip'.
10233 You can pass the other parameters, but they will be ignored on those
10234 old systems.
10236 There can be at most one active notification at any given time. An
10237 active notification must be removed by calling `w32-notification-close'
10238 before a new one can be shown.
10240 usage: (w32-notification-notify &rest PARAMS) */)
10241 (ptrdiff_t nargs, Lisp_Object *args)
10243 struct frame *f = SELECTED_FRAME ();
10244 Lisp_Object arg_plist, lres;
10245 EMACS_INT retval;
10246 char *icon, *tip, *title, *msg;
10247 enum NI_Severity severity;
10248 unsigned timeout = 0;
10250 if (nargs == 0)
10251 return Qnil;
10253 arg_plist = Flist (nargs, args);
10255 /* Icon. */
10256 lres = Fplist_get (arg_plist, QCicon);
10257 if (STRINGP (lres))
10258 icon = SSDATA (ENCODE_FILE (Fexpand_file_name (lres, Qnil)));
10259 else
10260 icon = (char *)"";
10262 /* Tip. */
10263 lres = Fplist_get (arg_plist, QCtip);
10264 if (STRINGP (lres))
10265 tip = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10266 else
10267 tip = (char *)"Emacs notification";
10269 /* Severity. */
10270 lres = Fplist_get (arg_plist, QClevel);
10271 if (NILP (lres))
10272 severity = Ni_None;
10273 else if (EQ (lres, Qinfo))
10274 severity = Ni_Info;
10275 else if (EQ (lres, Qwarning))
10276 severity = Ni_Warn;
10277 else if (EQ (lres, Qerror))
10278 severity = Ni_Err;
10279 else
10280 severity = Ni_Info;
10282 /* Title. */
10283 lres = Fplist_get (arg_plist, QCtitle);
10284 if (STRINGP (lres))
10285 title = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10286 else
10287 title = (char *)"";
10289 /* Notification body text. */
10290 lres = Fplist_get (arg_plist, QCbody);
10291 if (STRINGP (lres))
10292 msg = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10293 else
10294 msg = (char *)"";
10296 /* Do it! */
10297 retval = add_tray_notification (f, icon, tip, severity, timeout, title, msg);
10298 return (retval < 0 ? Qnil : make_number (retval));
10301 DEFUN ("w32-notification-close",
10302 Fw32_notification_close, Sw32_notification_close,
10303 1, 1, 0,
10304 doc: /* Remove the MS-Windows tray notification specified by its ID. */)
10305 (Lisp_Object id)
10307 struct frame *f = SELECTED_FRAME ();
10309 if (INTEGERP (id))
10310 delete_tray_notification (f, XINT (id));
10312 return Qnil;
10315 #endif /* WINDOWSNT && !HAVE_DBUS */
10318 /***********************************************************************
10319 Initialization
10320 ***********************************************************************/
10322 /* Keep this list in the same order as frame_parms in frame.c.
10323 Use 0 for unsupported frame parameters. */
10325 frame_parm_handler w32_frame_parm_handlers[] =
10327 x_set_autoraise,
10328 x_set_autolower,
10329 x_set_background_color,
10330 x_set_border_color,
10331 x_set_border_width,
10332 x_set_cursor_color,
10333 x_set_cursor_type,
10334 x_set_font,
10335 x_set_foreground_color,
10336 x_set_icon_name,
10337 x_set_icon_type,
10338 x_set_internal_border_width,
10339 x_set_right_divider_width,
10340 x_set_bottom_divider_width,
10341 x_set_menu_bar_lines,
10342 x_set_mouse_color,
10343 x_explicitly_set_name,
10344 x_set_scroll_bar_width,
10345 x_set_scroll_bar_height,
10346 x_set_title,
10347 x_set_unsplittable,
10348 x_set_vertical_scroll_bars,
10349 x_set_horizontal_scroll_bars,
10350 x_set_visibility,
10351 x_set_tool_bar_lines,
10352 0, /* x_set_scroll_bar_foreground, */
10353 0, /* x_set_scroll_bar_background, */
10354 x_set_screen_gamma,
10355 x_set_line_spacing,
10356 x_set_left_fringe,
10357 x_set_right_fringe,
10358 0, /* x_set_wait_for_wm, */
10359 x_set_fullscreen,
10360 x_set_font_backend,
10361 x_set_alpha,
10362 0, /* x_set_sticky */
10363 0, /* x_set_tool_bar_position */
10364 0, /* x_set_inhibit_double_buffering */
10365 x_set_undecorated,
10366 x_set_parent_frame,
10367 x_set_skip_taskbar,
10368 x_set_no_focus_on_map,
10369 x_set_no_accept_focus,
10370 x_set_z_group,
10371 0, /* x_set_override_redirect */
10372 x_set_no_special_glyphs,
10375 void
10376 syms_of_w32fns (void)
10378 globals_of_w32fns ();
10379 track_mouse_window = NULL;
10381 w32_visible_system_caret_hwnd = NULL;
10383 DEFSYM (Qundefined_color, "undefined-color");
10384 DEFSYM (Qcancel_timer, "cancel-timer");
10385 DEFSYM (Qhyper, "hyper");
10386 DEFSYM (Qsuper, "super");
10387 DEFSYM (Qmeta, "meta");
10388 DEFSYM (Qalt, "alt");
10389 DEFSYM (Qctrl, "ctrl");
10390 DEFSYM (Qcontrol, "control");
10391 DEFSYM (Qshift, "shift");
10392 DEFSYM (Qfont_parameter, "font-parameter");
10393 DEFSYM (Qgeometry, "geometry");
10394 DEFSYM (Qworkarea, "workarea");
10395 DEFSYM (Qmm_size, "mm-size");
10396 DEFSYM (Qframes, "frames");
10397 DEFSYM (Qtip_frame, "tip-frame");
10398 DEFSYM (Qassq_delete_all, "assq-delete-all");
10399 DEFSYM (Qunicode_sip, "unicode-sip");
10400 #if defined WINDOWSNT && !defined HAVE_DBUS
10401 DEFSYM (QCicon, ":icon");
10402 DEFSYM (QCtip, ":tip");
10403 DEFSYM (QClevel, ":level");
10404 DEFSYM (Qinfo, "info");
10405 DEFSYM (Qwarning, "warning");
10406 DEFSYM (QCtitle, ":title");
10407 DEFSYM (QCbody, ":body");
10408 #endif
10410 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
10411 DEFSYM (Qgnutls, "gnutls");
10412 DEFSYM (Qlibxml2, "libxml2");
10413 DEFSYM (Qserif, "serif");
10414 DEFSYM (Qzlib, "zlib");
10415 DEFSYM (Qlcms2, "lcms2");
10417 Fput (Qundefined_color, Qerror_conditions,
10418 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
10419 Fput (Qundefined_color, Qerror_message,
10420 build_pure_c_string ("Undefined color"));
10422 staticpro (&w32_grabbed_keys);
10423 w32_grabbed_keys = Qnil;
10425 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
10426 doc: /* An array of color name mappings for Windows. */);
10427 Vw32_color_map = Qnil;
10429 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
10430 doc: /* Non-nil if Alt key presses are passed on to Windows.
10431 When non-nil, for example, Alt pressed and released and then space will
10432 open the System menu. When nil, Emacs processes the Alt key events, and
10433 then silently swallows them. */);
10434 Vw32_pass_alt_to_system = Qnil;
10436 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
10437 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
10438 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
10439 Vw32_alt_is_meta = Qt;
10441 DEFVAR_INT ("w32-quit-key", w32_quit_key,
10442 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
10443 w32_quit_key = 0;
10445 DEFVAR_LISP ("w32-pass-lwindow-to-system",
10446 Vw32_pass_lwindow_to_system,
10447 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
10449 When non-nil, the Start menu is opened by tapping the key.
10450 If you set this to nil, the left \"Windows\" key is processed by Emacs
10451 according to the value of `w32-lwindow-modifier', which see.
10453 Note that some combinations of the left \"Windows\" key with other
10454 keys are caught by Windows at low level. For example, <lwindow>-r
10455 pops up the Windows Run dialog, <lwindow>-<Pause> pops up the "System
10456 Properties" dialog, etc. On Windows 10, no \"Windows\" key
10457 combinations are normally handed to applications. To enable Emacs to
10458 process \"Windows\" key combinations, use the function
10459 `w32-register-hot-key`.
10461 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
10462 Vw32_pass_lwindow_to_system = Qt;
10464 DEFVAR_LISP ("w32-pass-rwindow-to-system",
10465 Vw32_pass_rwindow_to_system,
10466 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
10468 When non-nil, the Start menu is opened by tapping the key.
10469 If you set this to nil, the right \"Windows\" key is processed by Emacs
10470 according to the value of `w32-rwindow-modifier', which see.
10472 Note that some combinations of the right \"Windows\" key with other
10473 keys are caught by Windows at low level. For example, <rwindow>-r
10474 pops up the Windows Run dialog, <rwindow>-<Pause> pops up the "System
10475 Properties" dialog, etc. On Windows 10, no \"Windows\" key
10476 combinations are normally handed to applications. To enable Emacs to
10477 process \"Windows\" key combinations, use the function
10478 `w32-register-hot-key`.
10480 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
10481 Vw32_pass_rwindow_to_system = Qt;
10483 DEFVAR_LISP ("w32-phantom-key-code",
10484 Vw32_phantom_key_code,
10485 doc: /* Virtual key code used to generate \"phantom\" key presses.
10486 Value is a number between 0 and 255.
10488 Phantom key presses are generated in order to stop the system from
10489 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
10490 `w32-pass-rwindow-to-system' is nil.
10492 This variable is only used on Windows 98 and ME. For other Windows
10493 versions, see the documentation of the `w32-register-hot-key`
10494 function. */);
10495 /* Although 255 is technically not a valid key code, it works and
10496 means that this hack won't interfere with any real key code. */
10497 XSETINT (Vw32_phantom_key_code, 255);
10499 DEFVAR_LISP ("w32-enable-num-lock",
10500 Vw32_enable_num_lock,
10501 doc: /* If non-nil, the Num Lock key acts normally.
10502 Set to nil to handle Num Lock as the `kp-numlock' key. */);
10503 Vw32_enable_num_lock = Qt;
10505 DEFVAR_LISP ("w32-enable-caps-lock",
10506 Vw32_enable_caps_lock,
10507 doc: /* If non-nil, the Caps Lock key acts normally.
10508 Set to nil to handle Caps Lock as the `capslock' key. */);
10509 Vw32_enable_caps_lock = Qt;
10511 DEFVAR_LISP ("w32-scroll-lock-modifier",
10512 Vw32_scroll_lock_modifier,
10513 doc: /* Modifier to use for the Scroll Lock ON state.
10514 The value can be hyper, super, meta, alt, control or shift for the
10515 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
10516 Any other value will cause the Scroll Lock key to be ignored by Emacs,
10517 and it will have the same effect as in other applications. */);
10518 Vw32_scroll_lock_modifier = Qnil;
10520 DEFVAR_LISP ("w32-lwindow-modifier",
10521 Vw32_lwindow_modifier,
10522 doc: /* Modifier to use for the left \"Windows\" key.
10523 The value can be hyper, super, meta, alt, control or shift for the
10524 respective modifier, or nil to appear as the `lwindow' key.
10525 Any other value will cause the key to be ignored.
10527 Also see the documentation of the `w32-register-hot-key` function. */);
10528 Vw32_lwindow_modifier = Qnil;
10530 DEFVAR_LISP ("w32-rwindow-modifier",
10531 Vw32_rwindow_modifier,
10532 doc: /* Modifier to use for the right \"Windows\" key.
10533 The value can be hyper, super, meta, alt, control or shift for the
10534 respective modifier, or nil to appear as the `rwindow' key.
10535 Any other value will cause the key to be ignored.
10537 Also see the documentation of the `w32-register-hot-key` function. */);
10538 Vw32_rwindow_modifier = Qnil;
10540 DEFVAR_LISP ("w32-apps-modifier",
10541 Vw32_apps_modifier,
10542 doc: /* Modifier to use for the \"Apps\" key.
10543 The value can be hyper, super, meta, alt, control or shift for the
10544 respective modifier, or nil to appear as the `apps' key.
10545 Any other value will cause the key to be ignored. */);
10546 Vw32_apps_modifier = Qnil;
10548 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
10549 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
10550 w32_enable_synthesized_fonts = 0;
10552 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
10553 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
10554 Vw32_enable_palette = Qt;
10556 DEFVAR_INT ("w32-mouse-button-tolerance",
10557 w32_mouse_button_tolerance,
10558 doc: /* Analogue of double click interval for faking middle mouse events.
10559 The value is the minimum time in milliseconds that must elapse between
10560 left and right button down events before they are considered distinct events.
10561 If both mouse buttons are depressed within this interval, a middle mouse
10562 button down event is generated instead. */);
10563 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
10565 DEFVAR_INT ("w32-mouse-move-interval",
10566 w32_mouse_move_interval,
10567 doc: /* Minimum interval between mouse move events.
10568 The value is the minimum time in milliseconds that must elapse between
10569 successive mouse move (or scroll bar drag) events before they are
10570 reported as lisp events. */);
10571 w32_mouse_move_interval = 0;
10573 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
10574 w32_pass_extra_mouse_buttons_to_system,
10575 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
10576 Recent versions of Windows support mice with up to five buttons.
10577 Since most applications don't support these extra buttons, most mouse
10578 drivers will allow you to map them to functions at the system level.
10579 If this variable is non-nil, Emacs will pass them on, allowing the
10580 system to handle them. */);
10581 w32_pass_extra_mouse_buttons_to_system = 0;
10583 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
10584 w32_pass_multimedia_buttons_to_system,
10585 doc: /* If non-nil, media buttons are passed to Windows.
10586 Some modern keyboards contain buttons for controlling media players, web
10587 browsers and other applications. Generally these buttons are handled on a
10588 system wide basis, but by setting this to nil they are made available
10589 to Emacs for binding. Depending on your keyboard, additional keys that
10590 may be available are:
10592 browser-back, browser-forward, browser-refresh, browser-stop,
10593 browser-search, browser-favorites, browser-home,
10594 mail, mail-reply, mail-forward, mail-send,
10595 app-1, app-2,
10596 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
10597 spell-check, correction-list, toggle-dictate-command,
10598 media-next, media-previous, media-stop, media-play-pause, media-select,
10599 media-play, media-pause, media-record, media-fast-forward, media-rewind,
10600 media-channel-up, media-channel-down,
10601 volume-mute, volume-up, volume-down,
10602 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
10603 bass-down, bass-boost, bass-up, treble-down, treble-up */);
10604 w32_pass_multimedia_buttons_to_system = 1;
10606 #if 0 /* TODO: Mouse cursor customization. */
10607 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
10608 doc: /* The shape of the pointer when over text.
10609 Changing the value does not affect existing frames
10610 unless you set the mouse color. */);
10611 Vx_pointer_shape = Qnil;
10613 Vx_nontext_pointer_shape = Qnil;
10615 Vx_mode_pointer_shape = Qnil;
10617 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
10618 doc: /* The shape of the pointer when Emacs is busy.
10619 This variable takes effect when you create a new frame
10620 or when you set the mouse color. */);
10621 Vx_hourglass_pointer_shape = Qnil;
10623 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
10624 Vx_sensitive_text_pointer_shape,
10625 doc: /* The shape of the pointer when over mouse-sensitive text.
10626 This variable takes effect when you create a new frame
10627 or when you set the mouse color. */);
10628 Vx_sensitive_text_pointer_shape = Qnil;
10630 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
10631 Vx_window_horizontal_drag_shape,
10632 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
10633 This variable takes effect when you create a new frame
10634 or when you set the mouse color. */);
10635 Vx_window_horizontal_drag_shape = Qnil;
10637 DEFVAR_LISP ("x-window-vertical-drag-cursor",
10638 Vx_window_vertical_drag_shape,
10639 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
10640 This variable takes effect when you create a new frame
10641 or when you set the mouse color. */);
10642 Vx_window_vertical_drag_shape = Qnil;
10643 #endif
10645 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
10646 doc: /* A string indicating the foreground color of the cursor box. */);
10647 Vx_cursor_fore_pixel = Qnil;
10649 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
10650 doc: /* Maximum size for tooltips.
10651 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
10652 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
10654 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
10655 doc: /* Non-nil if no window manager is in use.
10656 Emacs doesn't try to figure this out; this is always nil
10657 unless you set it to something else. */);
10658 /* We don't have any way to find this out, so set it to nil
10659 and maybe the user would like to set it to t. */
10660 Vx_no_window_manager = Qnil;
10662 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
10663 Vx_pixel_size_width_font_regexp,
10664 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
10666 Since Emacs gets width of a font matching with this regexp from
10667 PIXEL_SIZE field of the name, font finding mechanism gets faster for
10668 such a font. This is especially effective for such large fonts as
10669 Chinese, Japanese, and Korean. */);
10670 Vx_pixel_size_width_font_regexp = Qnil;
10672 DEFVAR_LISP ("w32-bdf-filename-alist",
10673 Vw32_bdf_filename_alist,
10674 doc: /* List of bdf fonts and their corresponding filenames. */);
10675 Vw32_bdf_filename_alist = Qnil;
10677 DEFVAR_BOOL ("w32-strict-fontnames",
10678 w32_strict_fontnames,
10679 doc: /* Non-nil means only use fonts that are exact matches for those requested.
10680 Default is nil, which allows old fontnames that are not XLFD compliant,
10681 and allows third-party CJK display to work by specifying false charset
10682 fields to trick Emacs into translating to Big5, SJIS etc.
10683 Setting this to t will prevent wrong fonts being selected when
10684 fontsets are automatically created. */);
10685 w32_strict_fontnames = 0;
10687 DEFVAR_BOOL ("w32-strict-painting",
10688 w32_strict_painting,
10689 doc: /* Non-nil means use strict rules for repainting frames.
10690 Set this to nil to get the old behavior for repainting; this should
10691 only be necessary if the default setting causes problems. */);
10692 w32_strict_painting = 1;
10694 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
10695 w32_use_fallback_wm_chars_method,
10696 doc: /* Non-nil means use old method of processing character keys.
10697 This is intended only for debugging of the new processing method.
10698 Default is nil.
10700 This variable has effect only on NT family of systems, not on Windows 9X. */);
10701 w32_use_fallback_wm_chars_method = 0;
10703 DEFVAR_BOOL ("w32-disable-new-uniscribe-apis",
10704 w32_disable_new_uniscribe_apis,
10705 doc: /* Non-nil means don't use new Uniscribe APIs.
10706 The new APIs are used to access OTF features supported by fonts.
10707 This is intended only for debugging of the new Uniscribe-related code.
10708 Default is nil.
10710 This variable has effect only on Windows Vista and later. */);
10711 w32_disable_new_uniscribe_apis = 0;
10713 DEFVAR_LISP ("w32-tooltip-extra-pixels",
10714 Vw32_tooltip_extra_pixels,
10715 doc: /* Number of pixels added after tooltip text.
10716 On Windows some fonts may cause the last character of a tooltip be
10717 truncated or wrapped around to the next line. Adding some extra space
10718 at the end of the toooltip works around this problem.
10720 This variable specifies the number of pixels that shall be added. The
10721 default value t means to add the width of one canonical character of the
10722 tip frame. */);
10723 Vw32_tooltip_extra_pixels = Qt;
10725 DEFVAR_BOOL ("w32-disable-abort-dialog",
10726 w32_disable_abort_dialog,
10727 doc: /* Non-nil means don't display the abort dialog when aborting. */);
10728 w32_disable_abort_dialog = 0;
10730 #if 0 /* TODO: Port to W32 */
10731 defsubr (&Sx_change_window_property);
10732 defsubr (&Sx_delete_window_property);
10733 defsubr (&Sx_window_property);
10734 #endif
10735 defsubr (&Sxw_display_color_p);
10736 defsubr (&Sx_display_grayscale_p);
10737 defsubr (&Sxw_color_defined_p);
10738 defsubr (&Sxw_color_values);
10739 defsubr (&Sx_server_max_request_size);
10740 defsubr (&Sx_server_vendor);
10741 defsubr (&Sx_server_version);
10742 defsubr (&Sx_display_pixel_width);
10743 defsubr (&Sx_display_pixel_height);
10744 defsubr (&Sx_display_mm_width);
10745 defsubr (&Sx_display_mm_height);
10746 defsubr (&Sx_display_screens);
10747 defsubr (&Sx_display_planes);
10748 defsubr (&Sx_display_color_cells);
10749 defsubr (&Sx_display_visual_class);
10750 defsubr (&Sx_display_backing_store);
10751 defsubr (&Sx_display_save_under);
10752 defsubr (&Sx_create_frame);
10753 defsubr (&Sx_open_connection);
10754 defsubr (&Sx_close_connection);
10755 defsubr (&Sx_display_list);
10756 defsubr (&Sw32_frame_geometry);
10757 defsubr (&Sw32_frame_edges);
10758 defsubr (&Sw32_frame_list_z_order);
10759 defsubr (&Sw32_frame_restack);
10760 defsubr (&Sw32_mouse_absolute_pixel_position);
10761 defsubr (&Sw32_set_mouse_absolute_pixel_position);
10762 defsubr (&Sx_synchronize);
10764 /* W32 specific functions */
10766 defsubr (&Sw32_define_rgb_color);
10767 defsubr (&Sw32_default_color_map);
10768 defsubr (&Sw32_display_monitor_attributes_list);
10769 defsubr (&Sw32_send_sys_command);
10770 defsubr (&Sw32_shell_execute);
10771 defsubr (&Sw32_register_hot_key);
10772 defsubr (&Sw32_unregister_hot_key);
10773 defsubr (&Sw32_registered_hot_keys);
10774 defsubr (&Sw32_reconstruct_hot_key);
10775 defsubr (&Sw32_toggle_lock_key);
10776 defsubr (&Sw32_window_exists_p);
10777 defsubr (&Sw32_battery_status);
10778 defsubr (&Sw32__menu_bar_in_use);
10779 #if defined WINDOWSNT && !defined HAVE_DBUS
10780 defsubr (&Sw32_notification_notify);
10781 defsubr (&Sw32_notification_close);
10782 #endif
10784 #ifdef WINDOWSNT
10785 defsubr (&Sfile_system_info);
10786 defsubr (&Sdefault_printer_name);
10787 #endif
10789 defsubr (&Sset_message_beep);
10790 defsubr (&Sx_show_tip);
10791 defsubr (&Sx_hide_tip);
10792 tip_timer = Qnil;
10793 staticpro (&tip_timer);
10794 tip_frame = Qnil;
10795 staticpro (&tip_frame);
10797 last_show_tip_args = Qnil;
10798 staticpro (&last_show_tip_args);
10800 defsubr (&Sx_file_dialog);
10801 #ifdef WINDOWSNT
10802 defsubr (&Ssystem_move_file_to_trash);
10803 #endif
10808 /* Crashing and reporting backtrace. */
10810 #ifndef CYGWIN
10811 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
10812 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
10813 #endif
10814 static DWORD except_code;
10815 static PVOID except_addr;
10817 #ifndef CYGWIN
10819 /* Stack overflow recovery. */
10821 /* MinGW headers don't declare this (should be in malloc.h). Also,
10822 the function is not present pre-W2K, so make the call through
10823 a function pointer. */
10824 typedef int (__cdecl *_resetstkoflw_proc) (void);
10825 static _resetstkoflw_proc resetstkoflw;
10827 /* Re-establish the guard page at stack limit. This is needed because
10828 when a stack overflow is detected, Windows removes the guard bit
10829 from the guard page, so if we don't re-establish that protection,
10830 the next stack overflow will cause a crash. */
10831 void
10832 w32_reset_stack_overflow_guard (void)
10834 if (resetstkoflw == NULL)
10835 resetstkoflw =
10836 (_resetstkoflw_proc)GetProcAddress (GetModuleHandle ("msvcrt.dll"),
10837 "_resetstkoflw");
10838 /* We ignore the return value. If _resetstkoflw fails, the next
10839 stack overflow will crash the program. */
10840 if (resetstkoflw != NULL)
10841 (void)resetstkoflw ();
10844 static void
10845 stack_overflow_handler (void)
10847 /* Hard GC error may lead to stack overflow caused by
10848 too nested calls to mark_object. No way to survive. */
10849 if (gc_in_progress)
10850 terminate_due_to_signal (SIGSEGV, 40);
10851 #ifdef _WIN64
10852 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
10853 __builtin_longjmp (return_to_command_loop, 1);
10854 #else
10855 sys_longjmp (return_to_command_loop, 1);
10856 #endif
10859 /* This handler records the exception code and the address where it
10860 was triggered so that this info could be included in the backtrace.
10861 Without that, the backtrace in some cases has no information
10862 whatsoever about the offending code, and looks as if the top-level
10863 exception handler in the MinGW startup code was the one that
10864 crashed. We also recover from stack overflow, by calling our stack
10865 overflow handler that jumps back to top level. */
10866 static LONG CALLBACK
10867 my_exception_handler (EXCEPTION_POINTERS * exception_data)
10869 except_code = exception_data->ExceptionRecord->ExceptionCode;
10870 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
10872 /* If this is a stack overflow exception, attempt to recover. */
10873 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
10874 && exception_data->ExceptionRecord->NumberParameters == 2
10875 /* We can only longjmp to top level from the main thread. */
10876 && GetCurrentThreadId () == dwMainThreadId)
10878 /* Call stack_overflow_handler (). */
10879 #ifdef _WIN64
10880 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
10881 #else
10882 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
10883 #endif
10884 /* Zero this out, so the stale address of the stack overflow
10885 exception we handled is not displayed in some future
10886 unrelated crash. */
10887 except_addr = 0;
10888 return EXCEPTION_CONTINUE_EXECUTION;
10891 if (prev_exception_handler)
10892 return prev_exception_handler (exception_data);
10893 return EXCEPTION_EXECUTE_HANDLER;
10895 #endif
10897 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
10898 PULONG);
10900 #define BACKTRACE_LIMIT_MAX 62
10902 static int
10903 w32_backtrace (void **buffer, int limit)
10905 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
10906 HMODULE hm_kernel32 = NULL;
10908 if (!s_pfn_CaptureStackBackTrace)
10910 hm_kernel32 = LoadLibrary ("Kernel32.dll");
10911 s_pfn_CaptureStackBackTrace =
10912 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
10913 "RtlCaptureStackBackTrace");
10915 if (s_pfn_CaptureStackBackTrace)
10916 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
10917 buffer, NULL);
10918 return 0;
10921 void
10922 emacs_abort (void)
10924 if (w32_disable_abort_dialog)
10925 abort ();
10927 int button;
10928 button = MessageBox (NULL,
10929 "A fatal error has occurred!\n\n"
10930 "Would you like to attach a debugger?\n\n"
10931 "Select:\n"
10932 "YES -- to debug Emacs, or\n"
10933 "NO -- to abort Emacs and produce a backtrace\n"
10934 " (emacs_backtrace.txt in current directory)."
10935 #if __GNUC__
10936 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
10937 "\"continue\" inside GDB before clicking YES.)"
10938 #endif
10939 , "Emacs Abort Dialog",
10940 MB_ICONEXCLAMATION | MB_TASKMODAL
10941 | MB_SETFOREGROUND | MB_YESNO);
10942 switch (button)
10944 case IDYES:
10945 DebugBreak ();
10946 exit (2); /* tell the compiler we will never return */
10947 case IDNO:
10948 default:
10950 void *stack[BACKTRACE_LIMIT_MAX + 1];
10951 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
10953 if (i)
10955 int errfile_fd = -1;
10956 int j;
10957 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
10958 /* The type below should really be 'void *', but
10959 INT_BUFSIZE_BOUND cannot handle that without
10960 triggering compiler warnings (under certain
10961 pedantic warning switches), it wants an
10962 integer type. */
10963 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
10964 #ifdef CYGWIN
10965 int stderr_fd = 2;
10966 #else
10967 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
10968 int stderr_fd = -1;
10970 if (errout && errout != INVALID_HANDLE_VALUE)
10971 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
10972 #endif
10974 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
10975 but not on Windows 7. addr2line doesn't mind a missing
10976 "0x", but will be confused by an extra one. */
10977 if (except_addr)
10978 sprintf (buf, "\r\nException 0x%x at this address:\r\n%p\r\n",
10979 (unsigned int) except_code, except_addr);
10980 if (stderr_fd >= 0)
10982 if (except_addr)
10983 write (stderr_fd, buf, strlen (buf));
10984 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
10986 #ifdef CYGWIN
10987 #define _open open
10988 #endif
10989 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
10990 if (errfile_fd >= 0)
10992 lseek (errfile_fd, 0L, SEEK_END);
10993 if (except_addr)
10994 write (errfile_fd, buf, strlen (buf));
10995 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
10998 for (j = 0; j < i; j++)
11000 /* stack[] gives the return addresses, whereas we want
11001 the address of the call, so decrease each address
11002 by approximate size of 1 CALL instruction. */
11003 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
11004 if (stderr_fd >= 0)
11005 write (stderr_fd, buf, strlen (buf));
11006 if (errfile_fd >= 0)
11007 write (errfile_fd, buf, strlen (buf));
11009 if (i == BACKTRACE_LIMIT_MAX)
11011 if (stderr_fd >= 0)
11012 write (stderr_fd, "...\r\n", 5);
11013 if (errfile_fd >= 0)
11014 write (errfile_fd, "...\r\n", 5);
11016 if (errfile_fd >= 0)
11017 close (errfile_fd);
11019 abort ();
11020 break;
11027 /* Initialization. */
11030 globals_of_w32fns is used to initialize those global variables that
11031 must always be initialized on startup even when the global variable
11032 initialized is non zero (see the function main in emacs.c).
11033 globals_of_w32fns is called from syms_of_w32fns when the global
11034 variable initialized is 0 and directly from main when initialized
11035 is non zero.
11037 void
11038 globals_of_w32fns (void)
11040 HMODULE user32_lib = GetModuleHandle ("user32.dll");
11042 TrackMouseEvent not available in all versions of Windows, so must load
11043 it dynamically. Do it once, here, instead of every time it is used.
11045 track_mouse_event_fn = (TrackMouseEvent_Proc)
11046 GetProcAddress (user32_lib, "TrackMouseEvent");
11048 monitor_from_point_fn = (MonitorFromPoint_Proc)
11049 GetProcAddress (user32_lib, "MonitorFromPoint");
11050 get_monitor_info_fn = (GetMonitorInfo_Proc)
11051 GetProcAddress (user32_lib, "GetMonitorInfoA");
11052 monitor_from_window_fn = (MonitorFromWindow_Proc)
11053 GetProcAddress (user32_lib, "MonitorFromWindow");
11054 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
11055 GetProcAddress (user32_lib, "EnumDisplayMonitors");
11056 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
11057 GetProcAddress (user32_lib, "GetTitleBarInfo");
11060 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
11061 get_composition_string_fn = (ImmGetCompositionString_Proc)
11062 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
11063 get_ime_context_fn = (ImmGetContext_Proc)
11064 GetProcAddress (imm32_lib, "ImmGetContext");
11065 release_ime_context_fn = (ImmReleaseContext_Proc)
11066 GetProcAddress (imm32_lib, "ImmReleaseContext");
11067 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
11068 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
11071 except_code = 0;
11072 except_addr = 0;
11073 #ifndef CYGWIN
11074 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
11075 resetstkoflw = NULL;
11076 #endif
11078 DEFVAR_INT ("w32-ansi-code-page",
11079 w32_ansi_code_page,
11080 doc: /* The ANSI code page used by the system. */);
11081 w32_ansi_code_page = GetACP ();
11083 if (os_subtype == OS_NT)
11084 w32_unicode_gui = 1;
11085 else
11086 w32_unicode_gui = 0;
11088 after_deadkey = -1;
11090 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
11091 InitCommonControls ();
11093 syms_of_w32uniscribe ();
11096 #ifdef NTGUI_UNICODE
11098 Lisp_Object
11099 ntgui_encode_system (Lisp_Object str)
11101 Lisp_Object encoded;
11102 to_unicode (str, &encoded);
11103 return encoded;
11106 #endif /* NTGUI_UNICODE */