Require cl-lib at runtime in vc-hg
[emacs.git] / src / w32fns.c
blobe490588d01b2f250cc71e108d271940e5e51859d
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2017 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 <http://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);
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;
4417 /* Fall through */
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 case WM_MBUTTONDOWN:
4681 case WM_MBUTTONUP:
4682 handle_plain_button:
4684 BOOL up;
4685 int button;
4687 /* Ignore middle and extra buttons as long as the menu is active. */
4688 f = x_window_to_frame (dpyinfo, hwnd);
4689 if (f && f->output_data.w32->menubar_active)
4690 return 0;
4692 if (parse_button (msg, HIWORD (wParam), &button, &up))
4694 if (up) ReleaseCapture ();
4695 else SetCapture (hwnd);
4696 button = (button == 0) ? LMOUSE :
4697 ((button == 1) ? MMOUSE : RMOUSE);
4698 if (up)
4699 button_state &= ~button;
4700 else
4701 button_state |= button;
4705 if (f && (msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN
4706 || msg == WM_MBUTTONDOWN ||msg == WM_XBUTTONDOWN)
4707 && !FRAME_NO_ACCEPT_FOCUS (f))
4708 /* When clicking into a child frame or when clicking into a
4709 parent frame with the child frame selected and
4710 `no-accept-focus' is not set, select the clicked frame. */
4712 struct frame *p = FRAME_PARENT_FRAME (XFRAME (selected_frame));
4714 if (FRAME_PARENT_FRAME (f) || f == p)
4716 SetFocus (hwnd);
4717 SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
4721 wmsg.dwModifiers = w32_get_modifiers ();
4722 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4723 signal_user_input ();
4725 /* Need to return true for XBUTTON messages, false for others,
4726 to indicate that we processed the message. */
4727 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4729 case WM_MOUSEMOVE:
4730 f = x_window_to_frame (dpyinfo, hwnd);
4731 if (f)
4733 /* Ignore mouse movements as long as the menu is active.
4734 These movements are processed by the window manager
4735 anyway, and it's wrong to handle them as if they happened
4736 on the underlying frame. */
4737 if (f->output_data.w32->menubar_active)
4738 return 0;
4740 /* If the mouse moved, and the mouse pointer is invisible,
4741 make it visible again. We do this here so as to be able
4742 to show the mouse pointer even when the main
4743 (a.k.a. "Lisp") thread is busy doing something. */
4744 static int last_x, last_y;
4745 int x = GET_X_LPARAM (lParam);
4746 int y = GET_Y_LPARAM (lParam);
4748 if (f->pointer_invisible
4749 && (x != last_x || y != last_y))
4750 f->pointer_invisible = false;
4752 last_x = x;
4753 last_y = y;
4756 /* If the mouse has just moved into the frame, start tracking
4757 it, so we will be notified when it leaves the frame. Mouse
4758 tracking only works under W98 and NT4 and later. On earlier
4759 versions, there is no way of telling when the mouse leaves the
4760 frame, so we just have to put up with help-echo and mouse
4761 highlighting remaining while the frame is not active. */
4762 if (track_mouse_event_fn && !track_mouse_window
4763 /* If the menu bar is active, turning on tracking of mouse
4764 movement events might send these events to the tooltip
4765 frame, if the user happens to move the mouse pointer over
4766 the tooltip. But since we don't process events for
4767 tooltip frames, this causes Windows to present a
4768 hourglass cursor, which is ugly and unexpected. So don't
4769 enable tracking mouse events in this case; they will be
4770 restarted when the menu pops down. (Confusingly, the
4771 menubar_active member of f->output_data.w32, tested
4772 above, is only set when a menu was popped up _not_ from
4773 the frame's menu bar, but via x-popup-menu.) */
4774 && !menubar_in_use)
4776 TRACKMOUSEEVENT tme;
4777 tme.cbSize = sizeof (tme);
4778 tme.dwFlags = TME_LEAVE;
4779 tme.hwndTrack = hwnd;
4780 tme.dwHoverTime = HOVER_DEFAULT;
4782 track_mouse_event_fn (&tme);
4783 track_mouse_window = hwnd;
4785 case WM_HSCROLL:
4786 case WM_VSCROLL:
4787 if (w32_mouse_move_interval <= 0
4788 || (msg == WM_MOUSEMOVE && button_state == 0))
4790 wmsg.dwModifiers = w32_get_modifiers ();
4791 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4792 return 0;
4795 /* Hang onto mouse move and scroll messages for a bit, to avoid
4796 sending such events to Emacs faster than it can process them.
4797 If we get more events before the timer from the first message
4798 expires, we just replace the first message. */
4800 if (saved_mouse_move_msg.msg.hwnd == 0)
4801 mouse_move_timer =
4802 SetTimer (hwnd, MOUSE_MOVE_ID,
4803 w32_mouse_move_interval, NULL);
4805 /* Hold onto message for now. */
4806 saved_mouse_move_msg.msg.hwnd = hwnd;
4807 saved_mouse_move_msg.msg.message = msg;
4808 saved_mouse_move_msg.msg.wParam = wParam;
4809 saved_mouse_move_msg.msg.lParam = lParam;
4810 saved_mouse_move_msg.msg.time = GetMessageTime ();
4811 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4813 return 0;
4815 case WM_MOUSEWHEEL:
4816 case WM_DROPFILES:
4817 wmsg.dwModifiers = w32_get_modifiers ();
4818 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4819 signal_user_input ();
4820 return 0;
4822 case WM_APPCOMMAND:
4823 if (w32_pass_multimedia_buttons_to_system)
4824 goto dflt;
4825 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
4827 /* FIXME!!! This is never reached so what's the purpose? If the
4828 non-zero return remark below is right we're doing it wrong all
4829 the time. */
4830 case WM_MOUSEHWHEEL:
4831 wmsg.dwModifiers = w32_get_modifiers ();
4832 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4833 signal_user_input ();
4834 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
4835 handled, to prevent the system trying to handle it by faking
4836 scroll bar events. */
4837 return 1;
4839 case WM_TIMER:
4840 /* Flush out saved messages if necessary. */
4841 if (wParam == mouse_button_timer)
4843 if (saved_mouse_button_msg.msg.hwnd)
4845 post_msg (&saved_mouse_button_msg);
4846 signal_user_input ();
4847 saved_mouse_button_msg.msg.hwnd = 0;
4849 KillTimer (hwnd, mouse_button_timer);
4850 mouse_button_timer = 0;
4852 else if (wParam == mouse_move_timer)
4854 if (saved_mouse_move_msg.msg.hwnd)
4856 post_msg (&saved_mouse_move_msg);
4857 saved_mouse_move_msg.msg.hwnd = 0;
4859 KillTimer (hwnd, mouse_move_timer);
4860 mouse_move_timer = 0;
4862 else if (wParam == menu_free_timer)
4864 KillTimer (hwnd, menu_free_timer);
4865 menu_free_timer = 0;
4866 f = x_window_to_frame (dpyinfo, hwnd);
4867 /* If a popup menu is active, don't wipe its strings. */
4868 if (menubar_in_use
4869 && current_popup_menu == NULL)
4871 /* Free memory used by owner-drawn and help-echo strings. */
4872 w32_free_menu_strings (hwnd);
4873 if (f)
4874 f->output_data.w32->menubar_active = 0;
4875 menubar_in_use = 0;
4878 return 0;
4880 case WM_NCACTIVATE:
4881 /* Windows doesn't send us focus messages when putting up and
4882 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4883 The only indication we get that something happened is receiving
4884 this message afterwards. So this is a good time to reset our
4885 keyboard modifiers' state. */
4886 reset_modifiers ();
4887 goto dflt;
4889 case WM_INITMENU:
4890 button_state = 0;
4891 ReleaseCapture ();
4892 /* We must ensure menu bar is fully constructed and up to date
4893 before allowing user interaction with it. To achieve this
4894 we send this message to the lisp thread and wait for a
4895 reply (whose value is not actually needed) to indicate that
4896 the menu bar is now ready for use, so we can now return.
4898 To remain responsive in the meantime, we enter a nested message
4899 loop that can process all other messages.
4901 However, we skip all this if the message results from calling
4902 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4903 thread a message because it is blocked on us at this point. We
4904 set menubar_active before calling TrackPopupMenu to indicate
4905 this (there is no possibility of confusion with real menubar
4906 being active). */
4908 f = x_window_to_frame (dpyinfo, hwnd);
4909 if (f
4910 && (f->output_data.w32->menubar_active
4911 /* We can receive this message even in the absence of a
4912 menubar (ie. when the system menu is activated) - in this
4913 case we do NOT want to forward the message, otherwise it
4914 will cause the menubar to suddenly appear when the user
4915 had requested it to be turned off! */
4916 || f->output_data.w32->menubar_widget == NULL))
4917 return 0;
4920 deferred_msg msg_buf;
4922 /* Detect if message has already been deferred; in this case
4923 we cannot return any sensible value to ignore this. */
4924 if (find_deferred_msg (hwnd, msg) != NULL)
4925 emacs_abort ();
4927 menubar_in_use = 1;
4929 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4932 case WM_EXITMENULOOP:
4933 f = x_window_to_frame (dpyinfo, hwnd);
4935 /* If a menu is still active, check again after a short delay,
4936 since Windows often (always?) sends the WM_EXITMENULOOP
4937 before the corresponding WM_COMMAND message.
4938 Don't do this if a popup menu is active, since it is only
4939 menubar menus that require cleaning up in this way.
4941 if (f && menubar_in_use && current_popup_menu == NULL)
4942 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4944 /* If hourglass cursor should be displayed, display it now. */
4945 if (f && f->output_data.w32->hourglass_p)
4946 SetCursor (f->output_data.w32->hourglass_cursor);
4948 goto dflt;
4950 case WM_MENUSELECT:
4951 /* Direct handling of help_echo in menus. Should be safe now
4952 that we generate the help_echo by placing a help event in the
4953 keyboard buffer. */
4955 HMENU menu = (HMENU) lParam;
4956 UINT menu_item = (UINT) LOWORD (wParam);
4957 UINT flags = (UINT) HIWORD (wParam);
4959 w32_menu_display_help (hwnd, menu, menu_item, flags);
4961 return 0;
4963 case WM_MEASUREITEM:
4964 f = x_window_to_frame (dpyinfo, hwnd);
4965 if (f)
4967 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4969 if (pMis->CtlType == ODT_MENU)
4971 /* Work out dimensions for popup menu titles. */
4972 char * title = (char *) pMis->itemData;
4973 HDC hdc = GetDC (hwnd);
4974 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4975 LOGFONT menu_logfont;
4976 HFONT old_font;
4977 SIZE size;
4979 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4980 menu_logfont.lfWeight = FW_BOLD;
4981 menu_font = CreateFontIndirect (&menu_logfont);
4982 old_font = SelectObject (hdc, menu_font);
4984 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4985 if (title)
4987 if (unicode_append_menu)
4988 GetTextExtentPoint32W (hdc, (WCHAR *) title,
4989 wcslen ((WCHAR *) title),
4990 &size);
4991 else
4992 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4994 pMis->itemWidth = size.cx;
4995 if (pMis->itemHeight < size.cy)
4996 pMis->itemHeight = size.cy;
4998 else
4999 pMis->itemWidth = 0;
5001 SelectObject (hdc, old_font);
5002 DeleteObject (menu_font);
5003 ReleaseDC (hwnd, hdc);
5004 return TRUE;
5007 return 0;
5009 case WM_DRAWITEM:
5010 f = x_window_to_frame (dpyinfo, hwnd);
5011 if (f)
5013 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
5015 if (pDis->CtlType == ODT_MENU)
5017 /* Draw popup menu title. */
5018 char * title = (char *) pDis->itemData;
5019 if (title)
5021 HDC hdc = pDis->hDC;
5022 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
5023 LOGFONT menu_logfont;
5024 HFONT old_font;
5026 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
5027 menu_logfont.lfWeight = FW_BOLD;
5028 menu_font = CreateFontIndirect (&menu_logfont);
5029 old_font = SelectObject (hdc, menu_font);
5031 /* Always draw title as if not selected. */
5032 if (unicode_append_menu)
5033 ExtTextOutW (hdc,
5034 pDis->rcItem.left
5035 + GetSystemMetrics (SM_CXMENUCHECK),
5036 pDis->rcItem.top,
5037 ETO_OPAQUE, &pDis->rcItem,
5038 (WCHAR *) title,
5039 wcslen ((WCHAR *) title), NULL);
5040 else
5041 ExtTextOut (hdc,
5042 pDis->rcItem.left
5043 + GetSystemMetrics (SM_CXMENUCHECK),
5044 pDis->rcItem.top,
5045 ETO_OPAQUE, &pDis->rcItem,
5046 title, strlen (title), NULL);
5048 SelectObject (hdc, old_font);
5049 DeleteObject (menu_font);
5051 return TRUE;
5054 return 0;
5056 case WM_MOUSEACTIVATE:
5057 /* WM_MOUSEACTIVATE is the only way on Windows to implement the
5058 `no-accept-focus' frame parameter. This means that one can't
5059 use the mouse to scroll a window on a non-selected frame. */
5061 /* Still not right - can't distinguish between clicks in the
5062 client area of the frame from clicks forwarded from the scroll
5063 bars - may have to hook WM_NCHITTEST to remember the mouse
5064 position and then check if it is in the client area
5065 ourselves. */
5067 /* Discard the mouse click that activates a frame, allowing the
5068 user to click anywhere without changing point (or worse!).
5069 Don't eat mouse clicks on scrollbars though!! */
5071 if ((f = x_window_to_frame (dpyinfo, hwnd))
5072 && FRAME_NO_ACCEPT_FOCUS (f)
5073 /* Ignore child frames, they don't accept focus anyway. */
5074 && !FRAME_PARENT_FRAME (f))
5076 Lisp_Object frame;
5078 XSETFRAME (frame, f);
5079 if (!EQ (selected_frame, frame))
5080 /* Don't discard the message, GTK doesn't either. */
5081 return MA_NOACTIVATE; /* ANDEAT; */
5083 goto dflt;
5085 case WM_MOUSELEAVE:
5086 /* No longer tracking mouse. */
5087 track_mouse_window = NULL;
5089 case WM_ACTIVATEAPP:
5090 case WM_ACTIVATE:
5091 case WM_WINDOWPOSCHANGED:
5092 case WM_SHOWWINDOW:
5093 /* Inform lisp thread that a frame might have just been obscured
5094 or exposed, so should recheck visibility of all frames. */
5095 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5096 goto dflt;
5098 case WM_SETFOCUS:
5099 dpyinfo->faked_key = 0;
5100 reset_modifiers ();
5101 if (!w32_kbdhook_active)
5102 register_hot_keys (hwnd);
5103 goto command;
5104 case WM_KILLFOCUS:
5105 if (!w32_kbdhook_active)
5106 unregister_hot_keys (hwnd);
5107 button_state = 0;
5108 ReleaseCapture ();
5109 /* Relinquish the system caret. */
5110 if (w32_system_caret_hwnd)
5112 w32_visible_system_caret_hwnd = NULL;
5113 w32_system_caret_hwnd = NULL;
5114 DestroyCaret ();
5116 goto command;
5117 case WM_COMMAND:
5118 menubar_in_use = 0;
5119 f = x_window_to_frame (dpyinfo, hwnd);
5120 if (f && HIWORD (wParam) == 0)
5122 if (menu_free_timer)
5124 KillTimer (hwnd, menu_free_timer);
5125 menu_free_timer = 0;
5128 case WM_MOVE:
5129 case WM_SIZE:
5130 command:
5131 wmsg.dwModifiers = w32_get_modifiers ();
5132 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5133 goto dflt;
5135 #ifdef WINDOWSNT
5136 case WM_CREATE:
5137 setup_w32_kbdhook ();
5138 goto dflt;
5139 #endif
5141 case WM_DESTROY:
5142 #ifdef WINDOWSNT
5143 remove_w32_kbdhook ();
5144 #endif
5145 CoUninitialize ();
5146 return 0;
5148 case WM_WTSSESSION_CHANGE:
5149 if (wParam == WTS_SESSION_LOCK)
5150 reset_w32_kbdhook_state ();
5151 goto dflt;
5153 case WM_CLOSE:
5154 wmsg.dwModifiers = w32_get_modifiers ();
5155 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5156 return 0;
5158 case WM_ENDSESSION:
5159 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5160 /* Allow time for Emacs to attempt an orderly shutdown. If we
5161 return, the process will be terminated immediately. FIXME:
5162 1000 seconds is too long to sleep if the shutdown attempt
5163 fails (see bug#25875). But if it fails, we want to find out
5164 about it, so let's leave 1000 for now. */
5165 sleep (1000);
5167 case WM_WINDOWPOSCHANGING:
5168 /* Don't restrict the sizing of any kind of frames. If the window
5169 manager doesn't, there's no reason to do it ourselves. */
5170 return 0;
5172 case WM_GETMINMAXINFO:
5173 /* Hack to allow resizing the Emacs frame above the screen size.
5174 Note that Windows 9x limits coordinates to 16-bits. */
5175 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
5176 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
5177 return 0;
5179 case WM_SETCURSOR:
5180 if (LOWORD (lParam) == HTCLIENT)
5182 f = x_window_to_frame (dpyinfo, hwnd);
5183 if (f)
5185 if (f->output_data.w32->hourglass_p
5186 && !menubar_in_use && !current_popup_menu)
5187 SetCursor (f->output_data.w32->hourglass_cursor);
5188 else if (f->pointer_invisible)
5189 SetCursor (NULL);
5190 else
5191 SetCursor (f->output_data.w32->current_cursor);
5194 return 0;
5196 goto dflt;
5198 case WM_EMACS_SETCURSOR:
5200 Cursor cursor = (Cursor) wParam;
5201 f = x_window_to_frame (dpyinfo, hwnd);
5202 if (f && cursor)
5204 f->output_data.w32->current_cursor = cursor;
5205 /* Don't change the cursor while menu-bar menu is in use. */
5206 if (!f->output_data.w32->menubar_active
5207 && !f->output_data.w32->hourglass_p)
5209 if (f->pointer_invisible)
5210 SetCursor (NULL);
5211 else
5212 SetCursor (cursor);
5215 return 0;
5218 case WM_EMACS_SHOWCURSOR:
5220 ShowCursor ((BOOL) wParam);
5222 return 0;
5225 case WM_EMACS_CREATEVSCROLLBAR:
5226 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
5227 (struct scroll_bar *) lParam);
5229 case WM_EMACS_CREATEHSCROLLBAR:
5230 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
5231 (struct scroll_bar *) lParam);
5233 case WM_EMACS_SHOWWINDOW:
5234 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
5236 case WM_EMACS_BRINGTOTOP:
5237 case WM_EMACS_SETFOREGROUND:
5239 HWND foreground_window;
5240 DWORD foreground_thread, retval;
5242 /* On NT 5.0, and apparently Windows 98, it is necessary to
5243 attach to the thread that currently has focus in order to
5244 pull the focus away from it. */
5245 foreground_window = GetForegroundWindow ();
5246 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
5247 if (!foreground_window
5248 || foreground_thread == GetCurrentThreadId ()
5249 || !AttachThreadInput (GetCurrentThreadId (),
5250 foreground_thread, TRUE))
5251 foreground_thread = 0;
5253 retval = SetForegroundWindow ((HWND) wParam);
5254 if (msg == WM_EMACS_BRINGTOTOP)
5255 retval = BringWindowToTop ((HWND) wParam);
5257 /* Detach from the previous foreground thread. */
5258 if (foreground_thread)
5259 AttachThreadInput (GetCurrentThreadId (),
5260 foreground_thread, FALSE);
5262 /* SetFocus to give/remove focus to/from a child window. */
5263 if (msg == WM_EMACS_SETFOREGROUND)
5264 SetFocus ((HWND) wParam);
5266 return retval;
5269 case WM_EMACS_SETWINDOWPOS:
5271 WINDOWPOS * pos = (WINDOWPOS *) wParam;
5272 return SetWindowPos (hwnd, pos->hwndInsertAfter,
5273 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
5276 case WM_EMACS_DESTROYWINDOW:
5277 DragAcceptFiles ((HWND) wParam, FALSE);
5278 return DestroyWindow ((HWND) wParam);
5280 case WM_EMACS_HIDE_CARET:
5281 return HideCaret (hwnd);
5283 case WM_EMACS_SHOW_CARET:
5284 return ShowCaret (hwnd);
5286 case WM_EMACS_DESTROY_CARET:
5287 w32_system_caret_hwnd = NULL;
5288 w32_visible_system_caret_hwnd = NULL;
5289 return DestroyCaret ();
5291 case WM_EMACS_TRACK_CARET:
5292 /* If there is currently no system caret, create one. */
5293 if (w32_system_caret_hwnd == NULL)
5295 /* Use the default caret width, and avoid changing it
5296 unnecessarily, as it confuses screen reader software. */
5297 w32_system_caret_hwnd = hwnd;
5298 CreateCaret (hwnd, NULL, 0,
5299 w32_system_caret_height);
5302 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
5303 return 0;
5304 /* Ensure visible caret gets turned on when requested. */
5305 else if (w32_use_visible_system_caret
5306 && w32_visible_system_caret_hwnd != hwnd)
5308 w32_visible_system_caret_hwnd = hwnd;
5309 return ShowCaret (hwnd);
5311 /* Ensure visible caret gets turned off when requested. */
5312 else if (!w32_use_visible_system_caret
5313 && w32_visible_system_caret_hwnd)
5315 w32_visible_system_caret_hwnd = NULL;
5316 return HideCaret (hwnd);
5318 else
5319 return 1;
5321 case WM_EMACS_TRACKPOPUPMENU:
5323 UINT flags;
5324 POINT *pos;
5325 int retval;
5326 pos = (POINT *)lParam;
5327 flags = TPM_CENTERALIGN;
5328 if (button_state & LMOUSE)
5329 flags |= TPM_LEFTBUTTON;
5330 else if (button_state & RMOUSE)
5331 flags |= TPM_RIGHTBUTTON;
5333 /* Remember we did a SetCapture on the initial mouse down event,
5334 so for safety, we make sure the capture is canceled now. */
5335 ReleaseCapture ();
5336 button_state = 0;
5338 /* Use menubar_active to indicate that WM_INITMENU is from
5339 TrackPopupMenu below, and should be ignored. */
5340 f = x_window_to_frame (dpyinfo, hwnd);
5341 if (f)
5342 f->output_data.w32->menubar_active = 1;
5344 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
5345 0, hwnd, NULL))
5347 MSG amsg;
5348 /* Eat any mouse messages during popupmenu */
5349 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
5350 PM_REMOVE));
5351 /* Get the menu selection, if any */
5352 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
5354 retval = LOWORD (amsg.wParam);
5356 else
5358 retval = 0;
5361 else
5363 retval = -1;
5366 return retval;
5368 case WM_EMACS_FILENOTIFY:
5369 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5370 return 1;
5372 default:
5373 /* Check for messages registered at runtime. */
5374 if (msg == msh_mousewheel)
5376 wmsg.dwModifiers = w32_get_modifiers ();
5377 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5378 signal_user_input ();
5379 return 0;
5382 dflt:
5383 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
5386 /* The most common default return code for handled messages is 0. */
5387 return 0;
5390 static void
5391 my_create_window (struct frame * f)
5393 MSG msg;
5394 static int coords[2];
5395 Lisp_Object left, top;
5396 struct w32_display_info *dpyinfo = &one_w32_display_info;
5398 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
5399 anything that is not a number and is not Qunbound. */
5400 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
5401 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
5402 if (EQ (left, Qunbound))
5403 coords[0] = CW_USEDEFAULT;
5404 else
5405 coords[0] = XINT (left);
5406 if (EQ (top, Qunbound))
5407 coords[1] = CW_USEDEFAULT;
5408 else
5409 coords[1] = XINT (top);
5411 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
5412 (WPARAM)f, (LPARAM)coords))
5413 emacs_abort ();
5414 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5418 /* Create a tooltip window. Unlike my_create_window, we do not do this
5419 indirectly via the Window thread, as we do not need to process Window
5420 messages for the tooltip. Creating tooltips indirectly also creates
5421 deadlocks when tooltips are created for menu items. */
5422 static void
5423 my_create_tip_window (struct frame *f)
5425 RECT rect;
5427 rect.left = rect.top = 0;
5428 rect.right = FRAME_PIXEL_WIDTH (f);
5429 rect.bottom = FRAME_PIXEL_HEIGHT (f);
5431 AdjustWindowRect (&rect, f->output_data.w32->dwStyle, false);
5433 tip_window = FRAME_W32_WINDOW (f)
5434 = CreateWindow (EMACS_CLASS,
5435 f->namebuf,
5436 f->output_data.w32->dwStyle,
5437 f->left_pos,
5438 f->top_pos,
5439 rect.right - rect.left,
5440 rect.bottom - rect.top,
5441 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5442 NULL,
5443 hinst,
5444 NULL);
5446 if (tip_window)
5448 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
5449 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
5450 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
5451 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5453 /* Tip frames have no scrollbars. */
5454 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
5455 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
5457 /* Do this to discard the default setting specified by our parent. */
5458 ShowWindow (tip_window, SW_HIDE);
5463 /* Create and set up the w32 window for frame F. */
5465 static void
5466 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
5468 block_input ();
5470 /* Use the resource name as the top-level window name
5471 for looking up resources. Make a non-Lisp copy
5472 for the window manager, so GC relocation won't bother it.
5474 Elsewhere we specify the window name for the window manager. */
5475 f->namebuf = xlispstrdup (Vx_resource_name);
5477 my_create_window (f);
5479 validate_x_resource_name ();
5481 /* x_set_name normally ignores requests to set the name if the
5482 requested name is the same as the current name. This is the one
5483 place where that assumption isn't correct; f->name is set, but
5484 the server hasn't been told. */
5486 Lisp_Object name;
5487 int explicit = f->explicit_name;
5489 f->explicit_name = 0;
5490 name = f->name;
5491 fset_name (f, Qnil);
5492 x_set_name (f, name, explicit);
5495 unblock_input ();
5497 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f)
5498 && !FRAME_PARENT_FRAME (f))
5499 initialize_frame_menubar (f);
5501 if (FRAME_W32_WINDOW (f) == 0)
5502 error ("Unable to create window");
5505 /* Handle the icon stuff for this window. Perhaps later we might
5506 want an x_set_icon_position which can be called interactively as
5507 well. */
5509 static void
5510 x_icon (struct frame *f, Lisp_Object parms)
5512 Lisp_Object icon_x, icon_y;
5513 struct w32_display_info *dpyinfo = &one_w32_display_info;
5515 /* Set the position of the icon. Note that Windows 95 groups all
5516 icons in the tray. */
5517 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5518 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5519 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5521 CHECK_NUMBER (icon_x);
5522 CHECK_NUMBER (icon_y);
5524 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5525 error ("Both left and top icon corners of icon must be specified");
5527 block_input ();
5529 #if 0 /* TODO */
5530 /* Start up iconic or window? */
5531 x_wm_set_window_state
5532 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5533 ? IconicState
5534 : NormalState));
5536 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
5537 ? f->icon_name
5538 : f->name)));
5539 #endif
5541 unblock_input ();
5545 static void
5546 x_make_gc (struct frame *f)
5548 XGCValues gc_values;
5550 block_input ();
5552 /* Create the GC's of this frame.
5553 Note that many default values are used. */
5555 /* Normal video */
5556 gc_values.font = FRAME_FONT (f);
5558 /* Cursor has cursor-color background, background-color foreground. */
5559 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5560 gc_values.background = f->output_data.w32->cursor_pixel;
5561 f->output_data.w32->cursor_gc
5562 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5563 (GCFont | GCForeground | GCBackground),
5564 &gc_values);
5566 /* Reliefs. */
5567 f->output_data.w32->white_relief.gc = 0;
5568 f->output_data.w32->black_relief.gc = 0;
5570 unblock_input ();
5574 /* Handler for signals raised during x_create_frame and
5575 x_create_tip_frame. FRAME is the frame which is partially
5576 constructed. */
5578 static Lisp_Object
5579 unwind_create_frame (Lisp_Object frame)
5581 struct frame *f = XFRAME (frame);
5583 /* If frame is ``official'', nothing to do. */
5584 if (NILP (Fmemq (frame, Vframe_list)))
5586 #ifdef GLYPH_DEBUG
5587 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5589 /* If the frame's image cache refcount is still the same as our
5590 private shadow variable, it means we are unwinding a frame
5591 for which we didn't yet call init_frame_faces, where the
5592 refcount is incremented. Therefore, we increment it here, so
5593 that free_frame_faces, called in x_free_frame_resources
5594 below, will not mistakenly decrement the counter that was not
5595 incremented yet to account for this new frame. */
5596 if (FRAME_IMAGE_CACHE (f) != NULL
5597 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
5598 FRAME_IMAGE_CACHE (f)->refcount++;
5599 #endif
5601 x_free_frame_resources (f);
5602 free_glyphs (f);
5604 #ifdef GLYPH_DEBUG
5605 /* Check that reference counts are indeed correct. */
5606 eassert (dpyinfo->reference_count == dpyinfo_refcount);
5607 eassert ((dpyinfo->terminal->image_cache == NULL
5608 && image_cache_refcount == 0)
5609 || (dpyinfo->terminal->image_cache != NULL
5610 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
5611 #endif
5612 return Qt;
5615 return Qnil;
5618 static void
5619 do_unwind_create_frame (Lisp_Object frame)
5621 unwind_create_frame (frame);
5624 static void
5625 x_default_font_parameter (struct frame *f, Lisp_Object parms)
5627 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5628 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
5629 RES_TYPE_STRING);
5630 Lisp_Object font;
5631 if (EQ (font_param, Qunbound))
5632 font_param = Qnil;
5633 font = !NILP (font_param) ? font_param
5634 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
5636 if (!STRINGP (font))
5638 int i;
5639 static const char *names[]
5640 = { "Courier New-10",
5641 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
5642 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
5643 "Fixedsys",
5644 NULL };
5646 for (i = 0; names[i]; i++)
5648 font = font_open_by_name (f, build_unibyte_string (names[i]));
5649 if (! NILP (font))
5650 break;
5652 if (NILP (font))
5653 error ("No suitable font was found");
5655 else if (!NILP (font_param))
5657 /* Remember the explicit font parameter, so we can re-apply it after
5658 we've applied the `default' face settings. */
5659 x_set_frame_parameters (f, Fcons (Fcons (Qfont_parameter, font_param),
5660 Qnil));
5662 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
5665 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5666 1, 1, 0,
5667 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5668 Return an Emacs frame object.
5669 PARAMETERS is an alist of frame parameters.
5670 If the parameters specify that the frame should not have a minibuffer,
5671 and do not specify a specific minibuffer window to use,
5672 then `default-minibuffer-frame' must be a frame whose minibuffer can
5673 be shared by the new frame.
5675 This function is an internal primitive--use `make-frame' instead. */)
5676 (Lisp_Object parameters)
5678 struct frame *f;
5679 Lisp_Object frame, tem;
5680 Lisp_Object name;
5681 bool minibuffer_only = false;
5682 long window_prompting = 0;
5683 ptrdiff_t count = SPECPDL_INDEX ();
5684 Lisp_Object display;
5685 struct w32_display_info *dpyinfo = NULL;
5686 Lisp_Object parent, parent_frame;
5687 struct kboard *kb;
5688 int x_width = 0, x_height = 0;
5690 if (!FRAME_W32_P (SELECTED_FRAME ())
5691 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
5692 error ("Cannot create a GUI frame in a -nw session");
5694 /* Make copy of frame parameters because the original is in pure
5695 storage now. */
5696 parameters = Fcopy_alist (parameters);
5698 /* Use this general default value to start with
5699 until we know if this frame has a specified name. */
5700 Vx_resource_name = Vinvocation_name;
5702 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
5703 if (EQ (display, Qunbound))
5704 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
5705 if (EQ (display, Qunbound))
5706 display = Qnil;
5707 dpyinfo = check_x_display_info (display);
5708 kb = dpyinfo->terminal->kboard;
5710 if (!dpyinfo->terminal->name)
5711 error ("Terminal is not live, can't create new frames on it");
5713 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5714 if (!STRINGP (name)
5715 && ! EQ (name, Qunbound)
5716 && ! NILP (name))
5717 error ("Invalid frame name--not a string or nil");
5719 if (STRINGP (name))
5720 Vx_resource_name = name;
5722 /* See if parent window is specified. */
5723 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL,
5724 RES_TYPE_NUMBER);
5725 if (EQ (parent, Qunbound))
5726 parent = Qnil;
5727 else if (!NILP (parent))
5728 CHECK_NUMBER (parent);
5730 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5731 /* No need to protect DISPLAY because that's not used after passing
5732 it to make_frame_without_minibuffer. */
5733 frame = Qnil;
5734 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5735 RES_TYPE_SYMBOL);
5736 if (EQ (tem, Qnone) || NILP (tem))
5737 f = make_frame_without_minibuffer (Qnil, kb, display);
5738 else if (EQ (tem, Qonly))
5740 f = make_minibuffer_frame ();
5741 minibuffer_only = true;
5743 else if (WINDOWP (tem))
5744 f = make_frame_without_minibuffer (tem, kb, display);
5745 else
5746 f = make_frame (true);
5748 XSETFRAME (frame, f);
5750 parent_frame = x_get_arg (dpyinfo, parameters, Qparent_frame, NULL, NULL,
5751 RES_TYPE_SYMBOL);
5752 /* Apply `parent-frame' parameter only when no `parent-id' was
5753 specified. */
5754 if (!NILP (parent_frame)
5755 && (!NILP (parent)
5756 || !FRAMEP (parent_frame)
5757 || !FRAME_LIVE_P (XFRAME (parent_frame))
5758 || !FRAME_W32_P (XFRAME (parent_frame))))
5759 parent_frame = Qnil;
5761 fset_parent_frame (f, parent_frame);
5762 store_frame_param (f, Qparent_frame, parent_frame);
5764 tem = x_get_arg (dpyinfo, parameters, Qundecorated, NULL, NULL,
5765 RES_TYPE_BOOLEAN);
5766 FRAME_UNDECORATED (f) = !NILP (tem) && !EQ (tem, Qunbound);
5767 store_frame_param (f, Qundecorated, FRAME_UNDECORATED (f) ? Qt : Qnil);
5769 tem = x_get_arg (dpyinfo, parameters, Qskip_taskbar, NULL, NULL,
5770 RES_TYPE_BOOLEAN);
5771 FRAME_SKIP_TASKBAR (f) = !NILP (tem) && !EQ (tem, Qunbound);
5772 store_frame_param (f, Qskip_taskbar,
5773 (NILP (tem) || EQ (tem, Qunbound)) ? Qnil : Qt);
5775 /* By default, make scrollbars the system standard width and height. */
5776 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5777 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5779 f->terminal = dpyinfo->terminal;
5781 f->output_method = output_w32;
5782 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5783 FRAME_FONTSET (f) = -1;
5785 fset_icon_name
5786 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5787 RES_TYPE_STRING));
5788 if (! STRINGP (f->icon_name))
5789 fset_icon_name (f, Qnil);
5791 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5793 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5794 record_unwind_protect (do_unwind_create_frame, frame);
5796 #ifdef GLYPH_DEBUG
5797 image_cache_refcount =
5798 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5799 dpyinfo_refcount = dpyinfo->reference_count;
5800 #endif /* GLYPH_DEBUG */
5802 /* Specify the parent under which to make this window - this seems to
5803 have no effect on Windows because parent_desc is explicitly reset
5804 below. */
5805 if (!NILP (parent))
5807 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5808 pointer from integer of different size. */
5809 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5810 f->output_data.w32->explicit_parent = true;
5812 else
5814 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5815 f->output_data.w32->explicit_parent = false;
5818 /* Set the name; the functions to which we pass f expect the name to
5819 be set. */
5820 if (EQ (name, Qunbound) || NILP (name))
5822 fset_name (f, build_string (dpyinfo->w32_id_name));
5823 f->explicit_name = false;
5825 else
5827 fset_name (f, name);
5828 f->explicit_name = true;
5829 /* Use the frame's title when getting resources for this frame. */
5830 specbind (Qx_resource_name, name);
5833 if (uniscribe_available)
5834 register_font_driver (&uniscribe_font_driver, f);
5835 register_font_driver (&w32font_driver, f);
5837 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5838 "fontBackend", "FontBackend", RES_TYPE_STRING);
5840 /* Extract the window parameters from the supplied values
5841 that are needed to determine window geometry. */
5842 x_default_font_parameter (f, parameters);
5844 x_default_parameter (f, parameters, Qborder_width, make_number (2),
5845 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5847 /* We recognize either internalBorderWidth or internalBorder
5848 (which is what xterm calls it). */
5849 if (NILP (Fassq (Qinternal_border_width, parameters)))
5851 Lisp_Object value;
5853 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5854 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5855 if (! EQ (value, Qunbound))
5856 parameters = Fcons (Fcons (Qinternal_border_width, value),
5857 parameters);
5859 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5860 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5861 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5862 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5863 NULL, NULL, RES_TYPE_NUMBER);
5864 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5865 NULL, NULL, RES_TYPE_NUMBER);
5866 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5867 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5868 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5869 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5871 /* Also do the stuff which must be set before the window exists. */
5872 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5873 "foreground", "Foreground", RES_TYPE_STRING);
5874 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5875 "background", "Background", RES_TYPE_STRING);
5876 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5877 "pointerColor", "Foreground", RES_TYPE_STRING);
5878 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5879 "borderColor", "BorderColor", RES_TYPE_STRING);
5880 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5881 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5882 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5883 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5884 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5885 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5886 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5887 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5888 x_default_parameter (f, parameters, Qno_focus_on_map, Qnil,
5889 NULL, NULL, RES_TYPE_BOOLEAN);
5890 x_default_parameter (f, parameters, Qno_accept_focus, Qnil,
5891 NULL, NULL, RES_TYPE_BOOLEAN);
5893 /* Process alpha here (Bug#16619). On XP this fails with child
5894 frames. For `no-focus-on-map' frames delay processing of alpha
5895 until the frame becomes visible. */
5896 if (!FRAME_NO_FOCUS_ON_MAP (f))
5897 x_default_parameter (f, parameters, Qalpha, Qnil,
5898 "alpha", "Alpha", RES_TYPE_NUMBER);
5900 /* Init faces first since we need the frame's column width/line
5901 height in various occasions. */
5902 init_frame_faces (f);
5904 /* We have to call adjust_frame_size here since otherwise
5905 x_set_tool_bar_lines will already work with the character sizes
5906 installed by init_frame_faces while the frame's pixel size is still
5907 calculated from a character size of 1 and we subsequently hit the
5908 (height >= 0) assertion in window_box_height.
5910 The non-pixelwise code apparently worked around this because it
5911 had one frame line vs one toolbar line which left us with a zero
5912 root window height which was obviously wrong as well ...
5914 Also process `min-width' and `min-height' parameters right here
5915 because `frame-windows-min-size' needs them. */
5916 tem = x_get_arg (dpyinfo, parameters, Qmin_width, NULL, NULL,
5917 RES_TYPE_NUMBER);
5918 if (NUMBERP (tem))
5919 store_frame_param (f, Qmin_width, tem);
5920 tem = x_get_arg (dpyinfo, parameters, Qmin_height, NULL, NULL,
5921 RES_TYPE_NUMBER);
5922 if (NUMBERP (tem))
5923 store_frame_param (f, Qmin_height, tem);
5924 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5925 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5926 Qx_create_frame_1);
5928 /* The X resources controlling the menu-bar and tool-bar are
5929 processed specially at startup, and reflected in the mode
5930 variables; ignore them here. */
5931 if (NILP (parent_frame))
5933 x_default_parameter (f, parameters, Qmenu_bar_lines,
5934 NILP (Vmenu_bar_mode)
5935 ? make_number (0) : make_number (1),
5936 NULL, NULL, RES_TYPE_NUMBER);
5938 else
5939 /* No menu bar for child frames. */
5940 store_frame_param (f, Qmenu_bar_lines, make_number (0));
5942 x_default_parameter (f, parameters, Qtool_bar_lines,
5943 NILP (Vtool_bar_mode)
5944 ? make_number (0) : make_number (1),
5945 NULL, NULL, RES_TYPE_NUMBER);
5947 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5948 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5949 x_default_parameter (f, parameters, Qtitle, Qnil,
5950 "title", "Title", RES_TYPE_STRING);
5952 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5953 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5954 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5955 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5956 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5957 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5958 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5959 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5961 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5963 window_prompting = x_figure_window_size (f, parameters, true, &x_width, &x_height);
5965 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5966 f->no_split = minibuffer_only || EQ (tem, Qt);
5968 w32_window (f, window_prompting, minibuffer_only);
5969 x_icon (f, parameters);
5971 x_make_gc (f);
5973 /* Now consider the frame official. */
5974 f->terminal->reference_count++;
5975 FRAME_DISPLAY_INFO (f)->reference_count++;
5976 Vframe_list = Fcons (frame, Vframe_list);
5978 /* We need to do this after creating the window, so that the
5979 icon-creation functions can say whose icon they're describing. */
5980 x_default_parameter (f, parameters, Qicon_type, Qnil,
5981 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5983 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5984 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5985 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5986 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5987 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5988 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5989 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5990 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5991 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
5992 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
5994 /* Allow x_set_window_size, now. */
5995 f->can_x_set_window_size = true;
5997 if (x_width > 0)
5998 SET_FRAME_WIDTH (f, x_width);
5999 if (x_height > 0)
6000 SET_FRAME_HEIGHT (f, x_height);
6002 /* Tell the server what size and position, etc, we want, and how
6003 badly we want them. This should be done after we have the menu
6004 bar so that its size can be taken into account. */
6005 block_input ();
6006 x_wm_set_size_hint (f, window_prompting, false);
6007 unblock_input ();
6009 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
6010 Qx_create_frame_2);
6012 /* Process fullscreen parameter here in the hope that normalizing a
6013 fullheight/fullwidth frame will produce the size set by the last
6014 adjust_frame_size call. */
6015 x_default_parameter (f, parameters, Qfullscreen, Qnil,
6016 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
6017 x_default_parameter (f, parameters, Qz_group, Qnil,
6018 NULL, NULL, RES_TYPE_SYMBOL);
6020 /* Make the window appear on the frame and enable display, unless
6021 the caller says not to. However, with explicit parent, Emacs
6022 cannot control visibility, so don't try. */
6023 if (!f->output_data.w32->explicit_parent)
6025 Lisp_Object visibility
6026 = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
6028 if (EQ (visibility, Qicon))
6029 x_iconify_frame (f);
6030 else
6032 if (EQ (visibility, Qunbound))
6033 visibility = Qt;
6035 if (!NILP (visibility))
6036 x_make_frame_visible (f);
6039 store_frame_param (f, Qvisibility, visibility);
6042 /* For `no-focus-on-map' frames set alpha here. */
6043 if (FRAME_NO_FOCUS_ON_MAP (f))
6044 x_default_parameter (f, parameters, Qalpha, Qnil,
6045 "alpha", "Alpha", RES_TYPE_NUMBER);
6047 /* Initialize `default-minibuffer-frame' in case this is the first
6048 frame on this terminal. */
6049 if (FRAME_HAS_MINIBUF_P (f)
6050 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
6051 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
6052 kset_default_minibuffer_frame (kb, frame);
6054 /* All remaining specified parameters, which have not been "used"
6055 by x_get_arg and friends, now go in the misc. alist of the frame. */
6056 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
6057 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
6058 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
6060 /* Make sure windows on this frame appear in calls to next-window
6061 and similar functions. */
6062 Vwindow_list = Qnil;
6064 return unbind_to (count, frame);
6067 /* FRAME is used only to get a handle on the X display. We don't pass the
6068 display info directly because we're called from frame.c, which doesn't
6069 know about that structure. */
6070 Lisp_Object
6071 x_get_focus_frame (struct frame *frame)
6073 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
6074 Lisp_Object xfocus;
6075 if (! dpyinfo->w32_focus_frame)
6076 return Qnil;
6078 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
6079 return xfocus;
6082 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
6083 doc: /* Internal function called by `color-defined-p', which see.
6084 \(Note that the Nextstep version of this function ignores FRAME.) */)
6085 (Lisp_Object color, Lisp_Object frame)
6087 XColor foo;
6088 struct frame *f = decode_window_system_frame (frame);
6090 CHECK_STRING (color);
6092 if (w32_defined_color (f, SSDATA (color), &foo, false))
6093 return Qt;
6094 else
6095 return Qnil;
6098 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
6099 doc: /* Internal function called by `color-values', which see. */)
6100 (Lisp_Object color, Lisp_Object frame)
6102 XColor foo;
6103 struct frame *f = decode_window_system_frame (frame);
6105 CHECK_STRING (color);
6107 if (w32_defined_color (f, SSDATA (color), &foo, false))
6108 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
6109 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
6110 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
6111 else
6112 return Qnil;
6115 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
6116 doc: /* Internal function called by `display-color-p', which see. */)
6117 (Lisp_Object display)
6119 struct w32_display_info *dpyinfo = check_x_display_info (display);
6121 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
6122 return Qnil;
6124 return Qt;
6127 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
6128 Sx_display_grayscale_p, 0, 1, 0,
6129 doc: /* Return t if DISPLAY supports shades of gray.
6130 Note that color displays do support shades of gray.
6131 The optional argument DISPLAY specifies which display to ask about.
6132 DISPLAY should be either a frame or a display name (a string).
6133 If omitted or nil, that stands for the selected frame's display. */)
6134 (Lisp_Object display)
6136 struct w32_display_info *dpyinfo = check_x_display_info (display);
6138 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
6139 return Qnil;
6141 return Qt;
6144 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
6145 Sx_display_pixel_width, 0, 1, 0,
6146 doc: /* Return the width in pixels of DISPLAY.
6147 The optional argument DISPLAY specifies which display to ask about.
6148 DISPLAY should be either a frame or a display name (a string).
6149 If omitted or nil, that stands for the selected frame's display.
6151 On \"multi-monitor\" setups this refers to the pixel width for all
6152 physical monitors associated with DISPLAY. To get information for
6153 each physical monitor, use `display-monitor-attributes-list'. */)
6154 (Lisp_Object display)
6156 struct w32_display_info *dpyinfo = check_x_display_info (display);
6158 return make_number (x_display_pixel_width (dpyinfo));
6161 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
6162 Sx_display_pixel_height, 0, 1, 0,
6163 doc: /* Return the height 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 height 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_height (dpyinfo));
6178 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
6179 0, 1, 0,
6180 doc: /* Return the number of bitplanes 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. */)
6184 (Lisp_Object display)
6186 struct w32_display_info *dpyinfo = check_x_display_info (display);
6188 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
6191 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
6192 0, 1, 0,
6193 doc: /* Return the number of color cells of DISPLAY.
6194 The optional argument DISPLAY specifies which display to ask about.
6195 DISPLAY should be either a frame or a display name (a string).
6196 If omitted or nil, that stands for the selected frame's display. */)
6197 (Lisp_Object display)
6199 struct w32_display_info *dpyinfo = check_x_display_info (display);
6200 int cap;
6202 /* Don't use NCOLORS: it returns incorrect results under remote
6203 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
6204 * overflow and because probably is more meaningful on Windows
6205 * anyway. */
6207 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
6208 return make_number (cap);
6211 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
6212 Sx_server_max_request_size,
6213 0, 1, 0,
6214 doc: /* Return the maximum request size of the server of DISPLAY.
6215 The optional argument DISPLAY specifies which display to ask about.
6216 DISPLAY should be either a frame or a display name (a string).
6217 If omitted or nil, that stands for the selected frame's display. */)
6218 (Lisp_Object display)
6220 return make_number (1);
6223 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
6224 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
6226 \(Labeling every distributor as a "vendor" embodies the false assumption
6227 that operating systems cannot be developed and distributed noncommercially.)
6229 For GNU and Unix systems, this queries the X server software; for
6230 MS-Windows, this queries the OS.
6232 The optional argument TERMINAL specifies which display to ask about.
6233 TERMINAL should be a terminal object, a frame or a display name (a string).
6234 If omitted or nil, that stands for the selected frame's display. */)
6235 (Lisp_Object terminal)
6237 return build_string ("Microsoft Corp.");
6240 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
6241 doc: /* Return the version numbers of the GUI software on TERMINAL.
6242 The value is a list of three integers specifying the version of the GUI
6243 software in use.
6245 For GNU and Unix system, the first 2 numbers are the version of the X
6246 Protocol used on TERMINAL and the 3rd number is the distributor-specific
6247 release number. For MS-Windows, the 3 numbers report the version and
6248 the build number of the OS.
6250 See also the function `x-server-vendor'.
6252 The optional argument TERMINAL specifies which display to ask about.
6253 TERMINAL should be a terminal object, a frame or a display name (a string).
6254 If omitted or nil, that stands for the selected frame's display. */)
6255 (Lisp_Object terminal)
6257 return list3i (w32_major_version, w32_minor_version, w32_build_number);
6260 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
6261 doc: /* Return the number of screens on the server of DISPLAY.
6262 The optional argument DISPLAY specifies which display to ask about.
6263 DISPLAY should be either a frame or a display name (a string).
6264 If omitted or nil, that stands for the selected frame's display. */)
6265 (Lisp_Object display)
6267 return make_number (1);
6270 DEFUN ("x-display-mm-height", Fx_display_mm_height,
6271 Sx_display_mm_height, 0, 1, 0,
6272 doc: /* Return the height in millimeters of DISPLAY.
6273 The optional argument DISPLAY specifies which display to ask about.
6274 DISPLAY should be either a frame or a display name (a string).
6275 If omitted or nil, that stands for the selected frame's display.
6277 On \"multi-monitor\" setups this refers to the height in millimeters for
6278 all physical monitors associated with DISPLAY. To get information
6279 for each physical monitor, use `display-monitor-attributes-list'. */)
6280 (Lisp_Object display)
6282 struct w32_display_info *dpyinfo = check_x_display_info (display);
6283 HDC hdc;
6284 double mm_per_pixel;
6286 hdc = GetDC (NULL);
6287 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6288 / GetDeviceCaps (hdc, VERTRES));
6289 ReleaseDC (NULL, hdc);
6291 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
6294 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
6295 doc: /* Return the width in millimeters of DISPLAY.
6296 The optional argument DISPLAY specifies which display to ask about.
6297 DISPLAY should be either a frame or a display name (a string).
6298 If omitted or nil, that stands for the selected frame's display.
6300 On \"multi-monitor\" setups this refers to the width in millimeters for
6301 all physical monitors associated with TERMINAL. To get information
6302 for each physical monitor, use `display-monitor-attributes-list'. */)
6303 (Lisp_Object display)
6305 struct w32_display_info *dpyinfo = check_x_display_info (display);
6306 HDC hdc;
6307 double mm_per_pixel;
6309 hdc = GetDC (NULL);
6310 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6311 / GetDeviceCaps (hdc, HORZRES));
6312 ReleaseDC (NULL, hdc);
6314 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
6317 DEFUN ("x-display-backing-store", Fx_display_backing_store,
6318 Sx_display_backing_store, 0, 1, 0,
6319 doc: /* Return an indication of whether DISPLAY does backing store.
6320 The value may be `always', `when-mapped', or `not-useful'.
6321 The optional argument DISPLAY specifies which display to ask about.
6322 DISPLAY should be either a frame or a display name (a string).
6323 If omitted or nil, that stands for the selected frame's display. */)
6324 (Lisp_Object display)
6326 return intern ("not-useful");
6329 DEFUN ("x-display-visual-class", Fx_display_visual_class,
6330 Sx_display_visual_class, 0, 1, 0,
6331 doc: /* Return the visual class of DISPLAY.
6332 The value is one of the symbols `static-gray', `gray-scale',
6333 `static-color', `pseudo-color', `true-color', or `direct-color'.
6335 The optional argument DISPLAY specifies which display to ask about.
6336 DISPLAY should be either a frame or a display name (a string).
6337 If omitted or nil, that stands for the selected frame's display. */)
6338 (Lisp_Object display)
6340 struct w32_display_info *dpyinfo = check_x_display_info (display);
6341 Lisp_Object result = Qnil;
6343 if (dpyinfo->has_palette)
6344 result = intern ("pseudo-color");
6345 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
6346 result = intern ("static-grey");
6347 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
6348 result = intern ("static-color");
6349 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
6350 result = intern ("true-color");
6352 return result;
6355 DEFUN ("x-display-save-under", Fx_display_save_under,
6356 Sx_display_save_under, 0, 1, 0,
6357 doc: /* Return t if DISPLAY supports the save-under feature.
6358 The optional argument DISPLAY specifies which display to ask about.
6359 DISPLAY should be either a frame or a display name (a string).
6360 If omitted or nil, that stands for the selected frame's display. */)
6361 (Lisp_Object display)
6363 return Qnil;
6366 static BOOL CALLBACK ALIGN_STACK
6367 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
6369 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
6371 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
6373 return TRUE;
6376 static Lisp_Object
6377 w32_display_monitor_attributes_list (void)
6379 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
6380 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
6381 int i, n_monitors;
6382 HMONITOR *monitors;
6384 if (!(enum_display_monitors_fn && get_monitor_info_fn
6385 && monitor_from_window_fn))
6386 return Qnil;
6388 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
6389 (LPARAM) &monitor_list)
6390 || NILP (monitor_list))
6391 return Qnil;
6393 n_monitors = 0;
6394 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
6395 n_monitors++;
6397 monitors = xmalloc (n_monitors * sizeof (*monitors));
6398 for (i = 0; i < n_monitors; i++)
6400 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
6401 monitor_list = XCDR (monitor_list);
6404 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
6405 FOR_EACH_FRAME (rest, frame)
6407 struct frame *f = XFRAME (frame);
6409 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
6411 HMONITOR monitor =
6412 monitor_from_window_fn (FRAME_W32_WINDOW (f),
6413 MONITOR_DEFAULT_TO_NEAREST);
6415 for (i = 0; i < n_monitors; i++)
6416 if (monitors[i] == monitor)
6417 break;
6419 if (i < n_monitors)
6420 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
6424 for (i = 0; i < n_monitors; i++)
6426 Lisp_Object geometry, workarea, name, attributes = Qnil;
6427 HDC hdc;
6428 int width_mm, height_mm;
6429 struct MONITOR_INFO_EX mi;
6431 mi.cbSize = sizeof (mi);
6432 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
6433 continue;
6435 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
6436 if (hdc == NULL)
6437 continue;
6438 width_mm = GetDeviceCaps (hdc, HORZSIZE);
6439 height_mm = GetDeviceCaps (hdc, VERTSIZE);
6440 DeleteDC (hdc);
6442 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
6443 attributes);
6445 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
6447 attributes = Fcons (Fcons (Qname, name), attributes);
6449 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6450 attributes);
6452 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
6453 mi.rcWork.right - mi.rcWork.left,
6454 mi.rcWork.bottom - mi.rcWork.top);
6455 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6457 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
6458 mi.rcMonitor.right - mi.rcMonitor.left,
6459 mi.rcMonitor.bottom - mi.rcMonitor.top);
6460 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6462 if (mi.dwFlags & MONITORINFOF_PRIMARY)
6463 primary_monitor_attributes = attributes;
6464 else
6465 attributes_list = Fcons (attributes, attributes_list);
6468 if (!NILP (primary_monitor_attributes))
6469 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
6471 xfree (monitors);
6473 return attributes_list;
6476 static Lisp_Object
6477 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
6479 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
6480 HDC hdc;
6481 double mm_per_pixel;
6482 int pixel_width, pixel_height, width_mm, height_mm;
6483 RECT workarea_rect;
6485 /* Fallback: treat (possibly) multiple physical monitors as if they
6486 formed a single monitor as a whole. This should provide a
6487 consistent result at least on single monitor environments. */
6488 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
6489 attributes);
6491 frames = Qnil;
6492 FOR_EACH_FRAME (rest, frame)
6494 struct frame *f = XFRAME (frame);
6496 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
6497 frames = Fcons (frame, frames);
6499 attributes = Fcons (Fcons (Qframes, frames), attributes);
6501 pixel_width = x_display_pixel_width (dpyinfo);
6502 pixel_height = x_display_pixel_height (dpyinfo);
6504 hdc = GetDC (NULL);
6505 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6506 / GetDeviceCaps (hdc, HORZRES));
6507 width_mm = pixel_width * mm_per_pixel + 0.5;
6508 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6509 / GetDeviceCaps (hdc, VERTRES));
6510 height_mm = pixel_height * mm_per_pixel + 0.5;
6511 ReleaseDC (NULL, hdc);
6512 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6513 attributes);
6515 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
6516 we don't care. */
6517 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
6518 GetSystemMetrics (SM_YVIRTUALSCREEN),
6519 pixel_width, pixel_height);
6520 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
6521 workarea = list4i (workarea_rect.left, workarea_rect.top,
6522 workarea_rect.right - workarea_rect.left,
6523 workarea_rect.bottom - workarea_rect.top);
6524 else
6525 workarea = geometry;
6526 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6528 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6530 return list1 (attributes);
6533 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
6534 Sw32_display_monitor_attributes_list,
6535 0, 1, 0,
6536 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
6538 The optional argument DISPLAY specifies which display to ask about.
6539 DISPLAY should be either a frame or a display name (a string).
6540 If omitted or nil, that stands for the selected frame's display.
6542 Internal use only, use `display-monitor-attributes-list' instead. */)
6543 (Lisp_Object display)
6545 struct w32_display_info *dpyinfo = check_x_display_info (display);
6546 Lisp_Object attributes_list;
6548 block_input ();
6549 attributes_list = w32_display_monitor_attributes_list ();
6550 if (NILP (attributes_list))
6551 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
6552 unblock_input ();
6554 return attributes_list;
6557 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
6558 doc: /* Set the sound generated when the bell is rung.
6559 SOUND is `asterisk', `exclamation', `hand', `question', `ok', or `silent'
6560 to use the corresponding system sound for the bell. The `silent' sound
6561 prevents Emacs from making any sound at all.
6562 SOUND is nil to use the normal beep. */)
6563 (Lisp_Object sound)
6565 CHECK_SYMBOL (sound);
6567 if (NILP (sound))
6568 sound_type = 0xFFFFFFFF;
6569 else if (EQ (sound, intern ("asterisk")))
6570 sound_type = MB_ICONASTERISK;
6571 else if (EQ (sound, intern ("exclamation")))
6572 sound_type = MB_ICONEXCLAMATION;
6573 else if (EQ (sound, intern ("hand")))
6574 sound_type = MB_ICONHAND;
6575 else if (EQ (sound, intern ("question")))
6576 sound_type = MB_ICONQUESTION;
6577 else if (EQ (sound, intern ("ok")))
6578 sound_type = MB_OK;
6579 else if (EQ (sound, intern ("silent")))
6580 sound_type = MB_EMACS_SILENT;
6581 else
6582 sound_type = 0xFFFFFFFF;
6584 return sound;
6587 #if 0 /* unused */
6589 x_screen_planes (register struct frame *f)
6591 return FRAME_DISPLAY_INFO (f)->n_planes;
6593 #endif
6595 /* Return the display structure for the display named NAME.
6596 Open a new connection if necessary. */
6598 struct w32_display_info *
6599 x_display_info_for_name (Lisp_Object name)
6601 struct w32_display_info *dpyinfo;
6603 CHECK_STRING (name);
6605 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
6606 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
6607 return dpyinfo;
6609 /* Use this general default value to start with. */
6610 Vx_resource_name = Vinvocation_name;
6612 validate_x_resource_name ();
6614 dpyinfo = w32_term_init (name, NULL, SSDATA (Vx_resource_name));
6616 if (dpyinfo == 0)
6617 error ("Cannot connect to server %s", SDATA (name));
6619 XSETFASTINT (Vwindow_system_version, w32_major_version);
6621 return dpyinfo;
6624 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6625 1, 3, 0, doc: /* Open a connection to a display server.
6626 DISPLAY is the name of the display to connect to.
6627 Optional second arg XRM-STRING is a string of resources in xrdb format.
6628 If the optional third arg MUST-SUCCEED is non-nil,
6629 terminate Emacs if we can't open the connection.
6630 \(In the Nextstep version, the last two arguments are currently ignored.) */)
6631 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
6633 char *xrm_option;
6634 struct w32_display_info *dpyinfo;
6636 CHECK_STRING (display);
6638 /* Signal an error in order to encourage correct use from callers.
6639 * If we ever support multiple window systems in the same Emacs,
6640 * we'll need callers to be precise about what window system they
6641 * want. */
6643 if (strcmp (SSDATA (display), "w32") != 0)
6644 error ("The name of the display in this Emacs must be \"w32\"");
6646 /* If initialization has already been done, return now to avoid
6647 overwriting critical parts of one_w32_display_info. */
6648 if (window_system_available (NULL))
6649 return Qnil;
6651 if (! NILP (xrm_string))
6652 CHECK_STRING (xrm_string);
6654 /* Allow color mapping to be defined externally; first look in user's
6655 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6657 Lisp_Object color_file;
6659 color_file = build_string ("~/rgb.txt");
6661 if (NILP (Ffile_readable_p (color_file)))
6662 color_file =
6663 Fexpand_file_name (build_string ("rgb.txt"),
6664 Fsymbol_value (intern ("data-directory")));
6666 Vw32_color_map = Fx_load_color_file (color_file);
6668 if (NILP (Vw32_color_map))
6669 Vw32_color_map = w32_default_color_map ();
6671 /* Merge in system logical colors. */
6672 add_system_logical_colors_to_map (&Vw32_color_map);
6674 if (! NILP (xrm_string))
6675 xrm_option = SSDATA (xrm_string);
6676 else
6677 xrm_option = NULL;
6679 /* Use this general default value to start with. */
6680 /* First remove .exe suffix from invocation-name - it looks ugly. */
6682 char basename[ MAX_PATH ], *str;
6684 lispstpcpy (basename, Vinvocation_name);
6685 str = strrchr (basename, '.');
6686 if (str) *str = 0;
6687 Vinvocation_name = build_string (basename);
6689 Vx_resource_name = Vinvocation_name;
6691 validate_x_resource_name ();
6693 /* This is what opens the connection and sets x_current_display.
6694 This also initializes many symbols, such as those used for input. */
6695 dpyinfo = w32_term_init (display, xrm_option, SSDATA (Vx_resource_name));
6697 if (dpyinfo == 0)
6699 if (!NILP (must_succeed))
6700 fatal ("Cannot connect to server %s.\n",
6701 SDATA (display));
6702 else
6703 error ("Cannot connect to server %s", SDATA (display));
6706 XSETFASTINT (Vwindow_system_version, w32_major_version);
6707 return Qnil;
6710 DEFUN ("x-close-connection", Fx_close_connection,
6711 Sx_close_connection, 1, 1, 0,
6712 doc: /* Close the connection to DISPLAY's server.
6713 For DISPLAY, specify either a frame or a display name (a string).
6714 If DISPLAY is nil, that stands for the selected frame's display. */)
6715 (Lisp_Object display)
6717 struct w32_display_info *dpyinfo = check_x_display_info (display);
6719 if (dpyinfo->reference_count > 0)
6720 error ("Display still has frames on it");
6722 block_input ();
6723 x_destroy_all_bitmaps (dpyinfo);
6725 x_delete_display (dpyinfo);
6726 unblock_input ();
6728 return Qnil;
6731 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6732 doc: /* Return the list of display names that Emacs has connections to. */)
6733 (void)
6735 Lisp_Object result = Qnil;
6736 struct w32_display_info *wdi;
6738 for (wdi = x_display_list; wdi; wdi = wdi->next)
6739 result = Fcons (XCAR (wdi->name_list_element), result);
6741 return result;
6744 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6745 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
6746 This function only has an effect on X Windows. With MS Windows, it is
6747 defined but does nothing.
6749 If ON is nil, allow buffering of requests.
6750 Turning on synchronization prohibits the Xlib routines from buffering
6751 requests and seriously degrades performance, but makes debugging much
6752 easier.
6753 The optional second argument TERMINAL specifies which display to act on.
6754 TERMINAL should be a terminal object, a frame or a display name (a string).
6755 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
6756 (Lisp_Object on, Lisp_Object display)
6758 return Qnil;
6763 /***********************************************************************
6764 Window properties
6765 ***********************************************************************/
6767 #if 0 /* TODO : port window properties to W32 */
6769 DEFUN ("x-change-window-property", Fx_change_window_property,
6770 Sx_change_window_property, 2, 6, 0,
6771 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6772 PROP must be a string. VALUE may be a string or a list of conses,
6773 numbers and/or strings. If an element in the list is a string, it is
6774 converted to an atom and the value of the Atom is used. If an element
6775 is a cons, it is converted to a 32 bit number where the car is the 16
6776 top bits and the cdr is the lower 16 bits.
6778 FRAME nil or omitted means use the selected frame.
6779 If TYPE is given and non-nil, it is the name of the type of VALUE.
6780 If TYPE is not given or nil, the type is STRING.
6781 FORMAT gives the size in bits of each element if VALUE is a list.
6782 It must be one of 8, 16 or 32.
6783 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6784 If OUTER-P is non-nil, the property is changed for the outer X window of
6785 FRAME. Default is to change on the edit X window. */)
6786 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6787 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6789 struct frame *f = decode_window_system_frame (frame);
6790 Atom prop_atom;
6792 CHECK_STRING (prop);
6793 CHECK_STRING (value);
6795 block_input ();
6796 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6797 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6798 prop_atom, XA_STRING, 8, PropModeReplace,
6799 SDATA (value), SCHARS (value));
6801 /* Make sure the property is set when we return. */
6802 XFlush (FRAME_W32_DISPLAY (f));
6803 unblock_input ();
6805 return value;
6809 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6810 Sx_delete_window_property, 1, 2, 0,
6811 doc: /* Remove window property PROP from X window of FRAME.
6812 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6813 (Lisp_Object prop, Lisp_Object frame)
6815 struct frame *f = decode_window_system_frame (frame);
6816 Atom prop_atom;
6818 CHECK_STRING (prop);
6819 block_input ();
6820 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6821 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6823 /* Make sure the property is removed when we return. */
6824 XFlush (FRAME_W32_DISPLAY (f));
6825 unblock_input ();
6827 return prop;
6831 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6832 1, 6, 0,
6833 doc: /* Value is the value of window property PROP on FRAME.
6834 If FRAME is nil or omitted, use the selected frame.
6836 On X Windows, the following optional arguments are also accepted:
6837 If TYPE is nil or omitted, get the property as a string.
6838 Otherwise TYPE is the name of the atom that denotes the type expected.
6839 If SOURCE is non-nil, get the property on that window instead of from
6840 FRAME. The number 0 denotes the root window.
6841 If DELETE-P is non-nil, delete the property after retrieving it.
6842 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6844 On MS Windows, this function accepts but ignores those optional arguments.
6846 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6847 no value of TYPE (always string in the MS Windows case). */)
6848 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6849 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6851 struct frame *f = decode_window_system_frame (frame);
6852 Atom prop_atom;
6853 int rc;
6854 Lisp_Object prop_value = Qnil;
6855 char *tmp_data = NULL;
6856 Atom actual_type;
6857 int actual_format;
6858 unsigned long actual_size, bytes_remaining;
6860 CHECK_STRING (prop);
6861 block_input ();
6862 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6863 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6864 prop_atom, 0, 0, False, XA_STRING,
6865 &actual_type, &actual_format, &actual_size,
6866 &bytes_remaining, (unsigned char **) &tmp_data);
6867 if (rc == Success)
6869 int size = bytes_remaining;
6871 XFree (tmp_data);
6872 tmp_data = NULL;
6874 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6875 prop_atom, 0, bytes_remaining,
6876 False, XA_STRING,
6877 &actual_type, &actual_format,
6878 &actual_size, &bytes_remaining,
6879 (unsigned char **) &tmp_data);
6880 if (rc == Success)
6881 prop_value = make_string (tmp_data, size);
6883 XFree (tmp_data);
6886 unblock_input ();
6888 return prop_value;
6890 return Qnil;
6893 #endif /* TODO */
6895 /***********************************************************************
6896 Tool tips
6897 ***********************************************************************/
6899 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6900 Lisp_Object, int, int, int *, int *);
6902 /* The frame of a currently visible tooltip. */
6904 Lisp_Object tip_frame;
6906 /* If non-nil, a timer started that hides the last tooltip when it
6907 fires. */
6909 Lisp_Object tip_timer;
6910 Window tip_window;
6912 /* If non-nil, a vector of 3 elements containing the last args
6913 with which x-show-tip was called. See there. */
6915 Lisp_Object last_show_tip_args;
6918 static void
6919 unwind_create_tip_frame (Lisp_Object frame)
6921 Lisp_Object deleted;
6923 deleted = unwind_create_frame (frame);
6924 if (EQ (deleted, Qt))
6926 tip_window = NULL;
6927 tip_frame = Qnil;
6932 /* Create a frame for a tooltip on the display described by DPYINFO.
6933 PARMS is a list of frame parameters. Value is the frame.
6935 Note that functions called here, esp. x_default_parameter can
6936 signal errors, for instance when a specified color name is
6937 undefined. We have to make sure that we're in a consistent state
6938 when this happens. */
6940 static Lisp_Object
6941 x_create_tip_frame (struct w32_display_info *dpyinfo, Lisp_Object parms)
6943 struct frame *f;
6944 Lisp_Object frame;
6945 Lisp_Object name;
6946 int width, height;
6947 ptrdiff_t count = SPECPDL_INDEX ();
6948 struct kboard *kb;
6949 bool face_change_before = face_change;
6950 int x_width = 0, x_height = 0;
6952 /* Use this general default value to start with until we know if
6953 this frame has a specified name. */
6954 Vx_resource_name = Vinvocation_name;
6956 kb = dpyinfo->terminal->kboard;
6958 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6959 avoid destructive changes behind our caller's back. */
6960 parms = Fcopy_alist (parms);
6962 /* Get the name of the frame to use for resource lookup. */
6963 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6964 if (!STRINGP (name)
6965 && !EQ (name, Qunbound)
6966 && !NILP (name))
6967 error ("Invalid frame name--not a string or nil");
6968 Vx_resource_name = name;
6970 frame = Qnil;
6971 /* Make a frame without minibuffer nor mode-line. */
6972 f = make_frame (false);
6973 f->wants_modeline = false;
6974 XSETFRAME (frame, f);
6976 record_unwind_protect (unwind_create_tip_frame, frame);
6978 /* By setting the output method, we're essentially saying that
6979 the frame is live, as per FRAME_LIVE_P. If we get a signal
6980 from this point on, x_destroy_window might screw up reference
6981 counts etc. */
6982 f->terminal = dpyinfo->terminal;
6983 f->output_method = output_w32;
6984 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6986 FRAME_FONTSET (f) = -1;
6987 fset_icon_name (f, Qnil);
6989 #ifdef GLYPH_DEBUG
6990 image_cache_refcount =
6991 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6992 dpyinfo_refcount = dpyinfo->reference_count;
6993 #endif /* GLYPH_DEBUG */
6994 FRAME_KBOARD (f) = kb;
6996 /* Set the name; the functions to which we pass f expect the name to
6997 be set. */
6998 if (EQ (name, Qunbound) || NILP (name))
7000 fset_name (f, build_string (dpyinfo->w32_id_name));
7001 f->explicit_name = false;
7003 else
7005 fset_name (f, name);
7006 f->explicit_name = true;
7007 /* Use the frame's title when getting resources for this frame. */
7008 specbind (Qx_resource_name, name);
7011 if (uniscribe_available)
7012 register_font_driver (&uniscribe_font_driver, f);
7013 register_font_driver (&w32font_driver, f);
7015 x_default_parameter (f, parms, Qfont_backend, Qnil,
7016 "fontBackend", "FontBackend", RES_TYPE_STRING);
7018 /* Extract the window parameters from the supplied values
7019 that are needed to determine window geometry. */
7020 x_default_font_parameter (f, parms);
7022 x_default_parameter (f, parms, Qborder_width, make_number (2),
7023 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
7024 /* This defaults to 2 in order to match xterm. We recognize either
7025 internalBorderWidth or internalBorder (which is what xterm calls
7026 it). */
7027 if (NILP (Fassq (Qinternal_border_width, parms)))
7029 Lisp_Object value;
7031 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
7032 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
7033 if (! EQ (value, Qunbound))
7034 parms = Fcons (Fcons (Qinternal_border_width, value),
7035 parms);
7038 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
7039 "internalBorderWidth", "internalBorderWidth",
7040 RES_TYPE_NUMBER);
7041 /* Also do the stuff which must be set before the window exists. */
7042 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
7043 "foreground", "Foreground", RES_TYPE_STRING);
7044 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
7045 "background", "Background", RES_TYPE_STRING);
7046 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
7047 "pointerColor", "Foreground", RES_TYPE_STRING);
7048 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
7049 "cursorColor", "Foreground", RES_TYPE_STRING);
7050 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
7051 "borderColor", "BorderColor", RES_TYPE_STRING);
7053 /* Init faces before x_default_parameter is called for the
7054 scroll-bar-width parameter because otherwise we end up in
7055 init_iterator with a null face cache, which should not happen. */
7056 init_frame_faces (f);
7058 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
7059 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
7060 f->output_data.w32->explicit_parent = false;
7062 x_figure_window_size (f, parms, true, &x_width, &x_height);
7064 /* No fringes on tip frame. */
7065 f->fringe_cols = 0;
7066 f->left_fringe_width = 0;
7067 f->right_fringe_width = 0;
7068 /* No dividers on tip frame. */
7069 f->right_divider_width = 0;
7070 f->bottom_divider_width = 0;
7072 block_input ();
7073 my_create_tip_window (f);
7074 unblock_input ();
7076 x_make_gc (f);
7078 x_default_parameter (f, parms, Qauto_raise, Qnil,
7079 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7080 x_default_parameter (f, parms, Qauto_lower, Qnil,
7081 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
7082 x_default_parameter (f, parms, Qcursor_type, Qbox,
7083 "cursorType", "CursorType", RES_TYPE_SYMBOL);
7084 /* Process alpha here (Bug#17344). */
7085 x_default_parameter (f, parms, Qalpha, Qnil,
7086 "alpha", "Alpha", RES_TYPE_NUMBER);
7088 /* Dimensions, especially FRAME_LINES (f), must be done via
7089 change_frame_size. Change will not be effected unless different
7090 from the current FRAME_LINES (f). */
7091 width = FRAME_COLS (f);
7092 height = FRAME_LINES (f);
7093 SET_FRAME_COLS (f, 0);
7094 SET_FRAME_LINES (f, 0);
7095 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
7096 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
7097 /* Add `tooltip' frame parameter's default value. */
7098 if (NILP (Fframe_parameter (frame, Qtooltip)))
7099 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
7101 /* Set up faces after all frame parameters are known. This call
7102 also merges in face attributes specified for new frames.
7104 Frame parameters may be changed if .Xdefaults contains
7105 specifications for the default font. For example, if there is an
7106 `Emacs.default.attributeBackground: pink', the `background-color'
7107 attribute of the frame get's set, which let's the internal border
7108 of the tooltip frame appear in pink. Prevent this. */
7110 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
7111 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
7112 Lisp_Object colors = Qnil;
7114 call2 (Qface_set_after_frame_default, frame, Qnil);
7116 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
7117 colors = Fcons (Fcons (Qbackground_color, bg), colors);
7118 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
7119 colors = Fcons (Fcons (Qforeground_color, fg), colors);
7121 if (!NILP (colors))
7122 Fmodify_frame_parameters (frame, colors);
7125 f->no_split = true;
7127 /* Now that the frame is official, it counts as a reference to
7128 its display. */
7129 FRAME_DISPLAY_INFO (f)->reference_count++;
7130 f->terminal->reference_count++;
7132 /* It is now ok to make the frame official even if we get an error
7133 below. And the frame needs to be on Vframe_list or making it
7134 visible won't work. */
7135 Vframe_list = Fcons (frame, Vframe_list);
7136 f->can_x_set_window_size = true;
7138 /* Setting attributes of faces of the tooltip frame from resources
7139 and similar will set face_change, which leads to the
7140 clearing of all current matrices. Since this isn't necessary
7141 here, avoid it by resetting face_change to the value it
7142 had before we created the tip frame. */
7143 face_change = face_change_before;
7145 /* Discard the unwind_protect. */
7146 return unbind_to (count, frame);
7150 /* Compute where to display tip frame F. PARMS is the list of frame
7151 parameters for F. DX and DY are specified offsets from the current
7152 location of the mouse. WIDTH and HEIGHT are the width and height
7153 of the tooltip. Return coordinates relative to the root window of
7154 the display in *ROOT_X and *ROOT_Y. */
7156 static void
7157 compute_tip_xy (struct frame *f,
7158 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
7159 int width, int height, int *root_x, int *root_y)
7161 Lisp_Object left, top, right, bottom;
7162 int min_x = 0, min_y, max_x = 0, max_y;
7164 /* User-specified position? */
7165 left = Fcdr (Fassq (Qleft, parms));
7166 top = Fcdr (Fassq (Qtop, parms));
7167 right = Fcdr (Fassq (Qright, parms));
7168 bottom = Fcdr (Fassq (Qbottom, parms));
7170 /* Move the tooltip window where the mouse pointer is. Resize and
7171 show it. */
7172 if ((!INTEGERP (left) && !INTEGERP (right))
7173 || (!INTEGERP (top) && !INTEGERP (bottom)))
7175 POINT pt;
7177 /* Default min and max values. */
7178 min_x = 0;
7179 min_y = 0;
7180 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
7181 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
7183 block_input ();
7184 GetCursorPos (&pt);
7185 *root_x = pt.x;
7186 *root_y = pt.y;
7187 unblock_input ();
7189 /* If multiple monitor support is available, constrain the tip onto
7190 the current monitor. This improves the above by allowing negative
7191 co-ordinates if monitor positions are such that they are valid, and
7192 snaps a tooltip onto a single monitor if we are close to the edge
7193 where it would otherwise flow onto the other monitor (or into
7194 nothingness if there is a gap in the overlap). */
7195 if (monitor_from_point_fn && get_monitor_info_fn)
7197 struct MONITOR_INFO info;
7198 HMONITOR monitor
7199 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
7200 info.cbSize = sizeof (info);
7202 if (get_monitor_info_fn (monitor, &info))
7204 min_x = info.rcWork.left;
7205 min_y = info.rcWork.top;
7206 max_x = info.rcWork.right;
7207 max_y = info.rcWork.bottom;
7212 if (INTEGERP (top))
7213 *root_y = XINT (top);
7214 else if (INTEGERP (bottom))
7215 *root_y = XINT (bottom) - height;
7216 else if (*root_y + XINT (dy) <= min_y)
7217 *root_y = min_y; /* Can happen for negative dy */
7218 else if (*root_y + XINT (dy) + height <= max_y)
7219 /* It fits below the pointer */
7220 *root_y += XINT (dy);
7221 else if (height + XINT (dy) + min_y <= *root_y)
7222 /* It fits above the pointer. */
7223 *root_y -= height + XINT (dy);
7224 else
7225 /* Put it on the top. */
7226 *root_y = min_y;
7228 if (INTEGERP (left))
7229 *root_x = XINT (left);
7230 else if (INTEGERP (right))
7231 *root_x = XINT (right) - width;
7232 else if (*root_x + XINT (dx) <= min_x)
7233 *root_x = 0; /* Can happen for negative dx */
7234 else if (*root_x + XINT (dx) + width <= max_x)
7235 /* It fits to the right of the pointer. */
7236 *root_x += XINT (dx);
7237 else if (width + XINT (dx) + min_x <= *root_x)
7238 /* It fits to the left of the pointer. */
7239 *root_x -= width + XINT (dx);
7240 else
7241 /* Put it left justified on the screen -- it ought to fit that way. */
7242 *root_x = min_x;
7245 /* Hide tooltip. Delete its frame if DELETE is true. */
7246 static Lisp_Object
7247 x_hide_tip (bool delete)
7249 if (!NILP (tip_timer))
7251 call1 (Qcancel_timer, tip_timer);
7252 tip_timer = Qnil;
7255 if (NILP (tip_frame)
7256 || (!delete && FRAMEP (tip_frame)
7257 && !FRAME_VISIBLE_P (XFRAME (tip_frame))))
7258 return Qnil;
7259 else
7261 ptrdiff_t count;
7262 Lisp_Object was_open = Qnil;
7264 count = SPECPDL_INDEX ();
7265 specbind (Qinhibit_redisplay, Qt);
7266 specbind (Qinhibit_quit, Qt);
7268 if (FRAMEP (tip_frame))
7270 if (delete)
7272 delete_frame (tip_frame, Qnil);
7273 tip_frame = Qnil;
7275 else
7276 x_make_frame_invisible (XFRAME (tip_frame));
7278 was_open = Qt;
7280 else
7281 tip_frame = Qnil;
7283 return unbind_to (count, was_open);
7288 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
7289 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
7290 A tooltip window is a small window displaying a string.
7292 This is an internal function; Lisp code should call `tooltip-show'.
7294 FRAME nil or omitted means use the selected frame.
7296 PARMS is an optional list of frame parameters which can be
7297 used to change the tooltip's appearance.
7299 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
7300 means use the default timeout of 5 seconds.
7302 If the list of frame parameters PARMS contains a `left' parameter,
7303 display the tooltip at that x-position. If the list of frame parameters
7304 PARMS contains no `left' but a `right' parameter, display the tooltip
7305 right-adjusted at that x-position. Otherwise display it at the
7306 x-position of the mouse, with offset DX added (default is 5 if DX isn't
7307 specified).
7309 Likewise for the y-position: If a `top' frame parameter is specified, it
7310 determines the position of the upper edge of the tooltip window. If a
7311 `bottom' parameter but no `top' frame parameter is specified, it
7312 determines the position of the lower edge of the tooltip window.
7313 Otherwise display the tooltip window at the y-position of the mouse,
7314 with offset DY added (default is -10).
7316 A tooltip's maximum size is specified by `x-max-tooltip-size'.
7317 Text larger than the specified size is clipped. */)
7318 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
7320 struct frame *tip_f;
7321 struct window *w;
7322 int root_x, root_y;
7323 struct buffer *old_buffer;
7324 struct text_pos pos;
7325 int width, height;
7326 int old_windows_or_buffers_changed = windows_or_buffers_changed;
7327 ptrdiff_t count = SPECPDL_INDEX ();
7328 ptrdiff_t count_1;
7329 Lisp_Object window, size;
7330 AUTO_STRING (tip, " *tip*");
7332 specbind (Qinhibit_redisplay, Qt);
7334 CHECK_STRING (string);
7335 decode_window_system_frame (frame);
7336 if (NILP (timeout))
7337 timeout = make_number (5);
7338 else
7339 CHECK_NATNUM (timeout);
7341 if (NILP (dx))
7342 dx = make_number (5);
7343 else
7344 CHECK_NUMBER (dx);
7346 if (NILP (dy))
7347 dy = make_number (-10);
7348 else
7349 CHECK_NUMBER (dy);
7351 if (NILP (last_show_tip_args))
7352 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
7354 if (FRAMEP (tip_frame) && FRAME_LIVE_P (XFRAME (tip_frame)))
7356 Lisp_Object last_string = AREF (last_show_tip_args, 0);
7357 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
7358 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
7360 if (FRAME_VISIBLE_P (XFRAME (tip_frame))
7361 && EQ (frame, last_frame)
7362 && !NILP (Fequal_including_properties (last_string, string))
7363 && !NILP (Fequal (last_parms, parms)))
7365 /* Only DX and DY have changed. */
7366 tip_f = XFRAME (tip_frame);
7367 if (!NILP (tip_timer))
7369 Lisp_Object timer = tip_timer;
7371 tip_timer = Qnil;
7372 call1 (Qcancel_timer, timer);
7375 block_input ();
7376 compute_tip_xy (tip_f, parms, dx, dy, FRAME_PIXEL_WIDTH (tip_f),
7377 FRAME_PIXEL_HEIGHT (tip_f), &root_x, &root_y);
7379 /* Put tooltip in topmost group and in position. */
7380 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7381 root_x, root_y, 0, 0,
7382 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7384 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7385 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7386 0, 0, 0, 0,
7387 SWP_NOMOVE | SWP_NOSIZE
7388 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7390 /* Let redisplay know that we have made the frame visible already. */
7391 SET_FRAME_VISIBLE (tip_f, 1);
7392 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7393 unblock_input ();
7395 goto start_timer;
7397 else if (tooltip_reuse_hidden_frame && EQ (frame, last_frame))
7399 bool delete = false;
7400 Lisp_Object tail, elt, parm, last;
7402 /* Check if every parameter in PARMS has the same value in
7403 last_parms. This may destruct last_parms which, however,
7404 will be recreated below. */
7405 for (tail = parms; CONSP (tail); tail = XCDR (tail))
7407 elt = XCAR (tail);
7408 parm = Fcar (elt);
7409 /* The left, top, right and bottom parameters are handled
7410 by compute_tip_xy so they can be ignored here. */
7411 if (!EQ (parm, Qleft) && !EQ (parm, Qtop)
7412 && !EQ (parm, Qright) && !EQ (parm, Qbottom))
7414 last = Fassq (parm, last_parms);
7415 if (NILP (Fequal (Fcdr (elt), Fcdr (last))))
7417 /* We lost, delete the old tooltip. */
7418 delete = true;
7419 break;
7421 else
7422 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7424 else
7425 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7428 /* Now check if there's a parameter left in last_parms with a
7429 non-nil value. */
7430 for (tail = last_parms; CONSP (tail); tail = XCDR (tail))
7432 elt = XCAR (tail);
7433 parm = Fcar (elt);
7434 if (!EQ (parm, Qleft) && !EQ (parm, Qtop) && !EQ (parm, Qright)
7435 && !EQ (parm, Qbottom) && !NILP (Fcdr (elt)))
7437 /* We lost, delete the old tooltip. */
7438 delete = true;
7439 break;
7443 x_hide_tip (delete);
7445 else
7446 x_hide_tip (true);
7448 else
7449 x_hide_tip (true);
7451 ASET (last_show_tip_args, 0, string);
7452 ASET (last_show_tip_args, 1, frame);
7453 ASET (last_show_tip_args, 2, parms);
7455 /* Block input until the tip has been fully drawn, to avoid crashes
7456 when drawing tips in menus. */
7457 block_input ();
7459 if (!FRAMEP (tip_frame) || !FRAME_LIVE_P (XFRAME (tip_frame)))
7461 /* Add default values to frame parameters. */
7462 if (NILP (Fassq (Qname, parms)))
7463 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7464 if (NILP (Fassq (Qinternal_border_width, parms)))
7465 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7466 if (NILP (Fassq (Qborder_width, parms)))
7467 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7468 if (NILP (Fassq (Qborder_color, parms)))
7469 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7470 if (NILP (Fassq (Qbackground_color, parms)))
7471 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7472 parms);
7474 /* Create a frame for the tooltip, and record it in the global
7475 variable tip_frame. */
7476 struct frame *f; /* The value is unused. */
7477 if (NILP (tip_frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms)))
7479 /* Creating the tip frame failed. */
7480 unblock_input ();
7481 return unbind_to (count, Qnil);
7485 tip_f = XFRAME (tip_frame);
7486 window = FRAME_ROOT_WINDOW (tip_f);
7487 set_window_buffer (window, Fget_buffer_create (tip), false, false);
7488 w = XWINDOW (window);
7489 w->pseudo_window_p = true;
7491 /* Set up the frame's root window. Note: The following code does not
7492 try to size the window or its frame correctly. Its only purpose is
7493 to make the subsequent text size calculations work. The right
7494 sizes should get installed when the toolkit gets back to us. */
7495 w->left_col = 0;
7496 w->top_line = 0;
7497 w->pixel_left = 0;
7498 w->pixel_top = 0;
7500 if (CONSP (Vx_max_tooltip_size)
7501 && RANGED_INTEGERP (1, XCAR (Vx_max_tooltip_size), INT_MAX)
7502 && RANGED_INTEGERP (1, XCDR (Vx_max_tooltip_size), INT_MAX))
7504 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
7505 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
7507 else
7509 w->total_cols = 80;
7510 w->total_lines = 40;
7513 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (tip_f);
7514 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (tip_f);
7515 FRAME_TOTAL_COLS (tip_f) = WINDOW_TOTAL_COLS (w);
7516 adjust_frame_glyphs (tip_f);
7518 /* Insert STRING into the root window's buffer and fit the frame to
7519 the buffer. */
7520 count_1 = SPECPDL_INDEX ();
7521 old_buffer = current_buffer;
7522 set_buffer_internal_1 (XBUFFER (w->contents));
7523 bset_truncate_lines (current_buffer, Qnil);
7524 specbind (Qinhibit_read_only, Qt);
7525 specbind (Qinhibit_modification_hooks, Qt);
7526 specbind (Qinhibit_point_motion_hooks, Qt);
7527 Ferase_buffer ();
7528 Finsert (1, &string);
7529 clear_glyph_matrix (w->desired_matrix);
7530 clear_glyph_matrix (w->current_matrix);
7531 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7532 try_window (window, pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
7533 /* Calculate size of tooltip window. */
7534 size = Fwindow_text_pixel_size (window, Qnil, Qnil, Qnil,
7535 make_number (w->pixel_height), Qnil);
7536 /* Add the frame's internal border to calculated size. */
7537 width = XINT (Fcar (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7538 height = XINT (Fcdr (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7539 /* Calculate position of tooltip frame. */
7540 compute_tip_xy (tip_f, parms, dx, dy, width, height, &root_x, &root_y);
7542 /* Show tooltip frame. */
7544 RECT rect;
7545 int pad = (NUMBERP (Vw32_tooltip_extra_pixels)
7546 ? max (0, XINT (Vw32_tooltip_extra_pixels))
7547 : FRAME_COLUMN_WIDTH (tip_f));
7549 rect.left = rect.top = 0;
7550 rect.right = width;
7551 rect.bottom = height;
7552 AdjustWindowRect (&rect, tip_f->output_data.w32->dwStyle,
7553 FRAME_EXTERNAL_MENU_BAR (tip_f));
7555 /* Position and size tooltip and put it in the topmost group. */
7556 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7557 root_x, root_y,
7558 rect.right - rect.left + pad,
7559 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7561 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7562 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7563 0, 0, 0, 0,
7564 SWP_NOMOVE | SWP_NOSIZE
7565 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7567 /* Let redisplay know that we have made the frame visible already. */
7568 SET_FRAME_VISIBLE (tip_f, 1);
7570 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7573 w->must_be_updated_p = true;
7574 update_single_window (w);
7575 set_buffer_internal_1 (old_buffer);
7576 unbind_to (count_1, Qnil);
7577 unblock_input ();
7578 windows_or_buffers_changed = old_windows_or_buffers_changed;
7580 start_timer:
7581 /* Let the tip disappear after timeout seconds. */
7582 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7583 intern ("x-hide-tip"));
7585 return unbind_to (count, Qnil);
7589 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7590 doc: /* Hide the current tooltip window, if there is any.
7591 Value is t if tooltip was open, nil otherwise. */)
7592 (void)
7594 return x_hide_tip (!tooltip_reuse_hidden_frame);
7597 /***********************************************************************
7598 File selection dialog
7599 ***********************************************************************/
7601 #define FILE_NAME_TEXT_FIELD edt1
7602 #define FILE_NAME_COMBO_BOX cmb13
7603 #define FILE_NAME_LIST lst1
7605 /* Callback for altering the behavior of the Open File dialog.
7606 Makes the Filename text field contain "Current Directory" and be
7607 read-only when "Directories" is selected in the filter. This
7608 allows us to work around the fact that the standard Open File
7609 dialog does not support directories. */
7610 static UINT_PTR CALLBACK
7611 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
7613 if (msg == WM_NOTIFY)
7615 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
7616 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
7617 int dropdown_changed;
7618 int dir_index;
7619 #ifdef NTGUI_UNICODE
7620 const int use_unicode = 1;
7621 #else /* !NTGUI_UNICODE */
7622 int use_unicode = w32_unicode_filenames;
7623 #endif /* NTGUI_UNICODE */
7625 /* Detect when the Filter dropdown is changed. */
7626 if (use_unicode)
7627 dropdown_changed =
7628 notify_w->hdr.code == CDN_TYPECHANGE
7629 || notify_w->hdr.code == CDN_INITDONE;
7630 else
7631 dropdown_changed =
7632 notify_a->hdr.code == CDN_TYPECHANGE
7633 || notify_a->hdr.code == CDN_INITDONE;
7634 if (dropdown_changed)
7636 HWND dialog = GetParent (hwnd);
7637 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7638 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
7639 int hdr_code;
7641 /* At least on Windows 7, the above attempt to get the window handle
7642 to the File Name Text Field fails. The following code does the
7643 job though. Note that this code is based on my examination of the
7644 window hierarchy using Microsoft Spy++. bk */
7645 if (edit_control == NULL)
7647 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
7648 if (tmp)
7650 tmp = GetWindow (tmp, GW_CHILD);
7651 if (tmp)
7652 edit_control = GetWindow (tmp, GW_CHILD);
7656 /* Directories is in index 2. */
7657 if (use_unicode)
7659 dir_index = notify_w->lpOFN->nFilterIndex;
7660 hdr_code = notify_w->hdr.code;
7662 else
7664 dir_index = notify_a->lpOFN->nFilterIndex;
7665 hdr_code = notify_a->hdr.code;
7667 if (dir_index == 2)
7669 if (use_unicode)
7670 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7671 (LPARAM)L"Current Directory");
7672 else
7673 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7674 (LPARAM)"Current Directory");
7675 EnableWindow (edit_control, FALSE);
7676 /* Note that at least on Windows 7, the above call to EnableWindow
7677 disables the window that would ordinarily have focus. If we
7678 do not set focus to some other window here, focus will land in
7679 no man's land and the user will be unable to tab through the
7680 dialog box (pressing tab will only result in a beep).
7681 Avoid that problem by setting focus to the list here. */
7682 if (hdr_code == CDN_INITDONE)
7683 SetFocus (list);
7685 else
7687 /* Don't override default filename on init done. */
7688 if (hdr_code == CDN_TYPECHANGE)
7690 if (use_unicode)
7691 SendMessageW (dialog, CDM_SETCONTROLTEXT,
7692 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
7693 else
7694 SendMessageA (dialog, CDM_SETCONTROLTEXT,
7695 FILE_NAME_TEXT_FIELD, (LPARAM)"");
7697 EnableWindow (edit_control, TRUE);
7701 return 0;
7704 void
7705 w32_dialog_in_progress (Lisp_Object in_progress)
7707 Lisp_Object frames, frame;
7709 /* Don't let frames in `above' z-group obscure popups. */
7710 FOR_EACH_FRAME (frames, frame)
7712 struct frame *f = XFRAME (frame);
7714 if (!NILP (in_progress) && FRAME_Z_GROUP_ABOVE (f))
7715 x_set_z_group (f, Qabove_suspended, Qabove);
7716 else if (NILP (in_progress) && FRAME_Z_GROUP_ABOVE_SUSPENDED (f))
7717 x_set_z_group (f, Qabove, Qabove_suspended);
7721 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7722 doc: /* Read file name, prompting with PROMPT in directory DIR.
7723 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
7724 selection box, if specified. If MUSTMATCH is non-nil, the returned file
7725 or directory must exist.
7727 This function is only defined on NS, MS Windows, and X Windows with the
7728 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
7729 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
7730 On Windows 7 and later, the file selection dialog "remembers" the last
7731 directory where the user selected a file, and will open that directory
7732 instead of DIR on subsequent invocations of this function with the same
7733 value of DIR as in previous invocations; this is standard Windows behavior. */)
7734 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
7736 /* Filter index: 1: All Files, 2: Directories only */
7737 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
7738 #ifndef NTGUI_UNICODE
7739 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
7740 #endif
7742 Lisp_Object filename = default_filename;
7743 struct frame *f = SELECTED_FRAME ();
7744 BOOL file_opened = FALSE;
7745 Lisp_Object orig_dir = dir;
7746 Lisp_Object orig_prompt = prompt;
7748 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
7749 compatibility) we end up with the old file dialogs. Define a big
7750 enough struct for the new dialog to trick GetOpenFileName into
7751 giving us the new dialogs on newer versions of Windows. */
7752 struct {
7753 OPENFILENAMEW details;
7754 #if _WIN32_WINNT < 0x500 /* < win2k */
7755 PVOID pvReserved;
7756 DWORD dwReserved;
7757 DWORD FlagsEx;
7758 #endif /* < win2k */
7759 } new_file_details_w;
7761 #ifdef NTGUI_UNICODE
7762 wchar_t filename_buf_w[32*1024 + 1]; /* NT kernel maximum */
7763 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7764 const int use_unicode = 1;
7765 #else /* not NTGUI_UNICODE */
7766 struct {
7767 OPENFILENAMEA details;
7768 #if _WIN32_WINNT < 0x500 /* < win2k */
7769 PVOID pvReserved;
7770 DWORD dwReserved;
7771 DWORD FlagsEx;
7772 #endif /* < win2k */
7773 } new_file_details_a;
7774 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7775 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7776 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7777 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7778 int use_unicode = w32_unicode_filenames;
7779 wchar_t *prompt_w;
7780 char *prompt_a UNINIT;
7781 int len;
7782 char fname_ret[MAX_UTF8_PATH];
7783 #endif /* NTGUI_UNICODE */
7786 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7787 system file encoding expected by the platform APIs (e.g. Cygwin's
7788 POSIX implementation) may not be the same as the encoding expected
7789 by the Windows "ANSI" APIs! */
7791 CHECK_STRING (prompt);
7792 CHECK_STRING (dir);
7794 dir = Fexpand_file_name (dir, Qnil);
7796 if (STRINGP (filename))
7797 filename = Ffile_name_nondirectory (filename);
7798 else
7799 filename = empty_unibyte_string;
7801 #ifdef CYGWIN
7802 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7803 if (SCHARS (filename) > 0)
7804 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7805 #endif
7807 CHECK_STRING (dir);
7808 CHECK_STRING (filename);
7810 /* The code in file_dialog_callback that attempts to set the text
7811 of the file name edit window when handling the CDN_INITDONE
7812 WM_NOTIFY message does not work. Setting filename to "Current
7813 Directory" in the only_dir_p case here does work however. */
7814 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7815 filename = build_string ("Current Directory");
7817 /* Convert the values we've computed so far to system form. */
7818 #ifdef NTGUI_UNICODE
7819 to_unicode (prompt, &prompt);
7820 to_unicode (dir, &dir);
7821 to_unicode (filename, &filename);
7822 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7823 report_file_error ("filename too long", default_filename);
7825 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7826 #else /* !NTGUI_UNICODE */
7827 prompt = ENCODE_FILE (prompt);
7828 dir = ENCODE_FILE (dir);
7829 filename = ENCODE_FILE (filename);
7831 /* We modify these in-place, so make copies for safety. */
7832 dir = Fcopy_sequence (dir);
7833 unixtodos_filename (SSDATA (dir));
7834 filename = Fcopy_sequence (filename);
7835 unixtodos_filename (SSDATA (filename));
7836 if (SBYTES (filename) >= MAX_UTF8_PATH)
7837 report_file_error ("filename too long", default_filename);
7838 if (w32_unicode_filenames)
7840 filename_to_utf16 (SSDATA (dir), dir_w);
7841 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7843 /* filename_to_utf16 sets errno to ENOENT when the file
7844 name is too long or cannot be converted to UTF-16. */
7845 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7846 report_file_error ("filename too long", default_filename);
7848 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7849 SSDATA (prompt), -1, NULL, 0);
7850 if (len > 32768)
7851 len = 32768;
7852 prompt_w = alloca (len * sizeof (wchar_t));
7853 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7854 SSDATA (prompt), -1, prompt_w, len);
7856 else
7858 filename_to_ansi (SSDATA (dir), dir_a);
7859 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7861 /* filename_to_ansi sets errno to ENOENT when the file
7862 name is too long or cannot be converted to UTF-16. */
7863 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7864 report_file_error ("filename too long", default_filename);
7866 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7867 SSDATA (prompt), -1, NULL, 0);
7868 if (len > 32768)
7869 len = 32768;
7870 prompt_w = alloca (len * sizeof (wchar_t));
7871 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7872 SSDATA (prompt), -1, prompt_w, len);
7873 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7874 if (len > 32768)
7875 len = 32768;
7876 prompt_a = alloca (len);
7877 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7879 #endif /* NTGUI_UNICODE */
7881 /* Fill in the structure for the call to GetOpenFileName below.
7882 For NTGUI_UNICODE builds (which run only on NT), we just use
7883 the actual size of the structure. For non-NTGUI_UNICODE
7884 builds, we tell the OS we're using an old version of the
7885 structure if the OS isn't new enough to support the newer
7886 version. */
7887 if (use_unicode)
7889 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7890 if (w32_major_version > 4 && w32_major_version < 95)
7891 file_details_w->lStructSize = sizeof (new_file_details_w);
7892 else
7893 file_details_w->lStructSize = sizeof (*file_details_w);
7894 /* Set up the inout parameter for the selected file name. */
7895 file_details_w->lpstrFile = filename_buf_w;
7896 file_details_w->nMaxFile =
7897 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7898 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7899 /* Undocumented Bug in Common File Dialog:
7900 If a filter is not specified, shell links are not resolved. */
7901 file_details_w->lpstrFilter = filter_w;
7902 #ifdef NTGUI_UNICODE
7903 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7904 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7905 #else
7906 file_details_w->lpstrInitialDir = dir_w;
7907 file_details_w->lpstrTitle = prompt_w;
7908 #endif
7909 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7910 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7911 | OFN_EXPLORER | OFN_ENABLEHOOK);
7912 if (!NILP (mustmatch))
7914 /* Require that the path to the parent directory exists. */
7915 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7916 /* If we are looking for a file, require that it exists. */
7917 if (NILP (only_dir_p))
7918 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7921 #ifndef NTGUI_UNICODE
7922 else
7924 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7925 if (w32_major_version > 4 && w32_major_version < 95)
7926 file_details_a->lStructSize = sizeof (new_file_details_a);
7927 else
7928 file_details_a->lStructSize = sizeof (*file_details_a);
7929 file_details_a->lpstrFile = filename_buf_a;
7930 file_details_a->nMaxFile =
7931 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7932 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7933 file_details_a->lpstrFilter = filter_a;
7934 file_details_a->lpstrInitialDir = dir_a;
7935 file_details_a->lpstrTitle = prompt_a;
7936 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7937 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7938 | OFN_EXPLORER | OFN_ENABLEHOOK);
7939 if (!NILP (mustmatch))
7941 /* Require that the path to the parent directory exists. */
7942 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7943 /* If we are looking for a file, require that it exists. */
7944 if (NILP (only_dir_p))
7945 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7948 #endif /* !NTGUI_UNICODE */
7951 int count = SPECPDL_INDEX ();
7953 w32_dialog_in_progress (Qt);
7955 /* Prevent redisplay. */
7956 specbind (Qinhibit_redisplay, Qt);
7957 record_unwind_protect (w32_dialog_in_progress, Qnil);
7958 block_input ();
7959 if (use_unicode)
7961 file_details_w->lpfnHook = file_dialog_callback;
7963 file_opened = GetOpenFileNameW (file_details_w);
7965 #ifndef NTGUI_UNICODE
7966 else
7968 file_details_a->lpfnHook = file_dialog_callback;
7970 file_opened = GetOpenFileNameA (file_details_a);
7972 #endif /* !NTGUI_UNICODE */
7973 unblock_input ();
7974 unbind_to (count, Qnil);
7977 if (file_opened)
7979 /* Get an Emacs string from the value Windows gave us. */
7980 #ifdef NTGUI_UNICODE
7981 filename = from_unicode_buffer (filename_buf_w);
7982 #else /* !NTGUI_UNICODE */
7983 if (use_unicode)
7984 filename_from_utf16 (filename_buf_w, fname_ret);
7985 else
7986 filename_from_ansi (filename_buf_a, fname_ret);
7987 dostounix_filename (fname_ret);
7988 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7989 #endif /* NTGUI_UNICODE */
7991 #ifdef CYGWIN
7992 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7993 #endif /* CYGWIN */
7995 /* Strip the dummy filename off the end of the string if we
7996 added it to select a directory. */
7997 if ((use_unicode && file_details_w->nFilterIndex == 2)
7998 #ifndef NTGUI_UNICODE
7999 || (!use_unicode && file_details_a->nFilterIndex == 2)
8000 #endif
8002 filename = Ffile_name_directory (filename);
8004 /* User canceled the dialog without making a selection. */
8005 else if (!CommDlgExtendedError ())
8006 filename = Qnil;
8007 /* An error occurred, fallback on reading from the mini-buffer. */
8008 else
8009 filename = Fcompleting_read (
8010 orig_prompt,
8011 intern ("read-file-name-internal"),
8012 orig_dir,
8013 mustmatch,
8014 orig_dir,
8015 Qfile_name_history,
8016 default_filename,
8017 Qnil);
8020 /* Make "Cancel" equivalent to C-g. */
8021 if (NILP (filename))
8022 quit ();
8024 return filename;
8028 #ifdef WINDOWSNT
8029 /* Moving files to the system recycle bin.
8030 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
8031 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
8032 Ssystem_move_file_to_trash, 1, 1, 0,
8033 doc: /* Move file or directory named FILENAME to the recycle bin. */)
8034 (Lisp_Object filename)
8036 Lisp_Object handler;
8037 Lisp_Object encoded_file;
8038 Lisp_Object operation;
8040 operation = Qdelete_file;
8041 if (!NILP (Ffile_directory_p (filename))
8042 && NILP (Ffile_symlink_p (filename)))
8044 operation = intern ("delete-directory");
8045 filename = Fdirectory_file_name (filename);
8048 /* Must have fully qualified file names for moving files to Recycle
8049 Bin. */
8050 filename = Fexpand_file_name (filename, Qnil);
8052 handler = Ffind_file_name_handler (filename, operation);
8053 if (!NILP (handler))
8054 return call2 (handler, operation, filename);
8055 else
8057 const char * path;
8058 int result;
8060 encoded_file = ENCODE_FILE (filename);
8062 path = map_w32_filename (SSDATA (encoded_file), NULL);
8064 /* The Unicode version of SHFileOperation is not supported on
8065 Windows 9X. */
8066 if (w32_unicode_filenames && os_subtype != OS_9X)
8068 SHFILEOPSTRUCTW file_op_w;
8069 /* We need one more element beyond MAX_PATH because this is
8070 a list of file names, with the last element double-null
8071 terminated. */
8072 wchar_t tmp_path_w[MAX_PATH + 1];
8074 memset (tmp_path_w, 0, sizeof (tmp_path_w));
8075 filename_to_utf16 (path, tmp_path_w);
8077 /* On Windows, write permission is required to delete/move files. */
8078 _wchmod (tmp_path_w, 0666);
8080 memset (&file_op_w, 0, sizeof (file_op_w));
8081 file_op_w.hwnd = HWND_DESKTOP;
8082 file_op_w.wFunc = FO_DELETE;
8083 file_op_w.pFrom = tmp_path_w;
8084 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
8085 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
8086 file_op_w.fAnyOperationsAborted = FALSE;
8088 result = SHFileOperationW (&file_op_w);
8090 else
8092 SHFILEOPSTRUCTA file_op_a;
8093 char tmp_path_a[MAX_PATH + 1];
8095 memset (tmp_path_a, 0, sizeof (tmp_path_a));
8096 filename_to_ansi (path, tmp_path_a);
8098 /* If a file cannot be represented in ANSI codepage, don't
8099 let them inadvertently delete other files because some
8100 characters are interpreted as a wildcards. */
8101 if (_mbspbrk ((unsigned char *)tmp_path_a,
8102 (const unsigned char *)"?*"))
8103 result = ERROR_FILE_NOT_FOUND;
8104 else
8106 _chmod (tmp_path_a, 0666);
8108 memset (&file_op_a, 0, sizeof (file_op_a));
8109 file_op_a.hwnd = HWND_DESKTOP;
8110 file_op_a.wFunc = FO_DELETE;
8111 file_op_a.pFrom = tmp_path_a;
8112 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
8113 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
8114 file_op_a.fAnyOperationsAborted = FALSE;
8116 result = SHFileOperationA (&file_op_a);
8119 if (result != 0)
8120 report_file_error ("Removing old name", list1 (filename));
8122 return Qnil;
8125 #endif /* WINDOWSNT */
8128 /***********************************************************************
8129 w32 specialized functions
8130 ***********************************************************************/
8132 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
8133 Sw32_send_sys_command, 1, 2, 0,
8134 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
8135 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
8136 to minimize), #xf120 to restore frame to original size, and #xf100
8137 to activate the menubar for keyboard access. #xf140 activates the
8138 screen saver if defined.
8140 If optional parameter FRAME is not specified, use selected frame. */)
8141 (Lisp_Object command, Lisp_Object frame)
8143 struct frame *f = decode_window_system_frame (frame);
8145 CHECK_NUMBER (command);
8147 if (FRAME_W32_P (f))
8148 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
8150 return Qnil;
8153 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
8154 doc: /* Get Windows to perform OPERATION on DOCUMENT.
8155 This is a wrapper around the ShellExecute system function, which
8156 invokes the application registered to handle OPERATION for DOCUMENT.
8158 OPERATION is either nil or a string that names a supported operation.
8159 What operations can be used depends on the particular DOCUMENT and its
8160 handler application, but typically it is one of the following common
8161 operations:
8163 \"open\" - open DOCUMENT, which could be a file, a directory, or an
8164 executable program (application). If it is an application,
8165 that application is launched in the current buffer's default
8166 directory. Otherwise, the application associated with
8167 DOCUMENT is launched in the buffer's default directory.
8168 \"opennew\" - like \"open\", but instruct the application to open
8169 DOCUMENT in a new window.
8170 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
8171 \"print\" - print DOCUMENT, which must be a file.
8172 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
8173 The printer should be provided in PARAMETERS, see below.
8174 \"explore\" - start the Windows Explorer on DOCUMENT.
8175 \"edit\" - launch an editor and open DOCUMENT for editing; which
8176 editor is launched depends on the association for the
8177 specified DOCUMENT.
8178 \"find\" - initiate search starting from DOCUMENT, which must specify
8179 a directory.
8180 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
8181 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
8182 the clipboard.
8183 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
8184 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
8185 which must be a directory.
8186 \"pastelink\"
8187 - create a shortcut in DOCUMENT (which must be a directory)
8188 the file or directory whose name is in the clipboard.
8189 \"runas\" - run DOCUMENT, which must be an excutable file, with
8190 elevated privileges (a.k.a. \"as Administrator\").
8191 \"properties\"
8192 - open the property sheet dialog for DOCUMENT.
8193 nil - invoke the default OPERATION, or \"open\" if default is
8194 not defined or unavailable.
8196 DOCUMENT is typically the name of a document file or a URL, but can
8197 also be an executable program to run, or a directory to open in the
8198 Windows Explorer. If it is a file or a directory, it must be a local
8199 one; this function does not support remote file names.
8201 If DOCUMENT is an executable program, the optional third arg PARAMETERS
8202 can be a string containing command line parameters, separated by blanks,
8203 that will be passed to the program. Some values of OPERATION also require
8204 parameters (e.g., \"printto\" requires the printer address). Otherwise,
8205 PARAMETERS should be nil or unspecified. Note that double quote characters
8206 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
8208 Optional fourth argument SHOW-FLAG can be used to control how the
8209 application will be displayed when it is invoked. If SHOW-FLAG is nil
8210 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
8211 specified, otherwise it is an integer between 0 and 11 representing
8212 a ShowWindow flag:
8214 0 - start hidden
8215 1 - start as normal-size window
8216 3 - start in a maximized window
8217 6 - start in a minimized window
8218 10 - start as the application itself specifies; this is the default. */)
8219 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
8221 char *errstr;
8222 Lisp_Object current_dir = BVAR (current_buffer, directory);;
8223 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
8224 #ifdef CYGWIN
8225 intptr_t result;
8226 #else
8227 int use_unicode = w32_unicode_filenames;
8228 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
8229 Lisp_Object absdoc, handler;
8230 BOOL success;
8231 #endif
8233 CHECK_STRING (document);
8235 #ifdef CYGWIN
8236 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
8237 document = Fcygwin_convert_file_name_to_windows (document, Qt);
8239 /* Encode filename, current directory and parameters. */
8240 current_dir = GUI_ENCODE_FILE (current_dir);
8241 document = GUI_ENCODE_FILE (document);
8242 doc_w = GUI_SDATA (document);
8243 if (STRINGP (parameters))
8245 parameters = GUI_ENCODE_SYSTEM (parameters);
8246 params_w = GUI_SDATA (parameters);
8248 if (STRINGP (operation))
8250 operation = GUI_ENCODE_SYSTEM (operation);
8251 ops_w = GUI_SDATA (operation);
8253 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
8254 GUI_SDATA (current_dir),
8255 (INTEGERP (show_flag)
8256 ? XINT (show_flag) : SW_SHOWDEFAULT));
8258 if (result > 32)
8259 return Qt;
8261 switch (result)
8263 case SE_ERR_ACCESSDENIED:
8264 errstr = w32_strerror (ERROR_ACCESS_DENIED);
8265 break;
8266 case SE_ERR_ASSOCINCOMPLETE:
8267 case SE_ERR_NOASSOC:
8268 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
8269 break;
8270 case SE_ERR_DDEBUSY:
8271 case SE_ERR_DDEFAIL:
8272 errstr = w32_strerror (ERROR_DDE_FAIL);
8273 break;
8274 case SE_ERR_DDETIMEOUT:
8275 errstr = w32_strerror (ERROR_TIMEOUT);
8276 break;
8277 case SE_ERR_DLLNOTFOUND:
8278 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
8279 break;
8280 case SE_ERR_FNF:
8281 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
8282 break;
8283 case SE_ERR_OOM:
8284 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
8285 break;
8286 case SE_ERR_PNF:
8287 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
8288 break;
8289 case SE_ERR_SHARE:
8290 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
8291 break;
8292 default:
8293 errstr = w32_strerror (0);
8294 break;
8297 #else /* !CYGWIN */
8299 const char file_url_str[] = "file:///";
8300 const int file_url_len = sizeof (file_url_str) - 1;
8301 int doclen;
8303 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
8305 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
8306 start a thread in some rare system configurations, for
8307 unknown reasons. That thread is started in the context of
8308 the Emacs process, but out of control of our code, and seems
8309 to never exit afterwards. Each such thread reserves 8MB of
8310 stack space (because that's the value recorded in the Emacs
8311 executable at link time: Emacs needs a large stack). So a
8312 large enough number of invocations of w32-shell-execute can
8313 potentially cause the Emacs process to run out of available
8314 address space, which is nasty. To work around this, we
8315 convert such URLs to local file names, which seems to prevent
8316 those threads from starting. See bug #20220. */
8317 char *p = SSDATA (document) + file_url_len;
8319 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
8320 document = Fsubstring_no_properties (document,
8321 make_number (file_url_len), Qnil);
8323 /* We have a situation here. If DOCUMENT is a relative file name,
8324 but its name includes leading directories, i.e. it lives not in
8325 CURRENT_DIR, but in its subdirectory, then ShellExecute below
8326 will fail to find it. So we need to make the file name is
8327 absolute. But DOCUMENT does not have to be a file, it can be a
8328 URL, for example. So we make it absolute only if it is an
8329 existing file; if it is a file that does not exist, tough. */
8330 absdoc = Fexpand_file_name (document, Qnil);
8331 /* Don't call file handlers for file-exists-p, since they might
8332 attempt to access the file, which could fail or produce undesired
8333 consequences, see bug#16558 for an example. */
8334 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
8335 if (NILP (handler))
8337 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
8339 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
8341 /* ShellExecute fails if DOCUMENT is a UNC with forward
8342 slashes (expand-file-name above converts all backslashes
8343 to forward slashes). Now that we know DOCUMENT is a
8344 file, we can mirror all forward slashes into backslashes. */
8345 unixtodos_filename (SSDATA (absdoc_encoded));
8346 document = absdoc_encoded;
8348 else
8349 document = ENCODE_FILE (document);
8351 else
8352 document = ENCODE_FILE (document);
8354 current_dir = ENCODE_FILE (current_dir);
8355 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
8356 be a URL that is not limited to MAX_PATH chararcters. */
8357 doclen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
8358 SSDATA (document), -1, NULL, 0);
8359 doc_w = xmalloc (doclen * sizeof (wchar_t));
8360 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
8361 SSDATA (document), -1, doc_w, doclen);
8362 if (use_unicode)
8364 wchar_t current_dir_w[MAX_PATH];
8365 SHELLEXECUTEINFOW shexinfo_w;
8367 /* Encode the current directory and parameters, and convert
8368 operation to UTF-16. */
8369 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
8370 if (STRINGP (parameters))
8372 int len;
8374 parameters = ENCODE_SYSTEM (parameters);
8375 len = pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
8376 SSDATA (parameters), -1, NULL, 0);
8377 if (len > 32768)
8378 len = 32768;
8379 params_w = alloca (len * sizeof (wchar_t));
8380 pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
8381 SSDATA (parameters), -1, params_w, len);
8382 params_w[len - 1] = 0;
8384 if (STRINGP (operation))
8386 /* Assume OPERATION is pure ASCII. */
8387 const char *s = SSDATA (operation);
8388 wchar_t *d;
8389 int len = SBYTES (operation) + 1;
8391 if (len > 32768)
8392 len = 32768;
8393 d = ops_w = alloca (len * sizeof (wchar_t));
8394 while (d < ops_w + len - 1)
8395 *d++ = *s++;
8396 *d = 0;
8399 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
8400 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
8401 able to invoke verbs from shortcut menu extensions, not just
8402 static verbs listed in the Registry. */
8403 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
8404 shexinfo_w.cbSize = sizeof (shexinfo_w);
8405 shexinfo_w.fMask =
8406 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8407 shexinfo_w.hwnd = NULL;
8408 shexinfo_w.lpVerb = ops_w;
8409 shexinfo_w.lpFile = doc_w;
8410 shexinfo_w.lpParameters = params_w;
8411 shexinfo_w.lpDirectory = current_dir_w;
8412 shexinfo_w.nShow =
8413 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8414 success = ShellExecuteExW (&shexinfo_w);
8415 xfree (doc_w);
8417 else
8419 char current_dir_a[MAX_PATH];
8420 SHELLEXECUTEINFOA shexinfo_a;
8421 int codepage = codepage_for_filenames (NULL);
8422 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
8423 NULL, NULL);
8425 doc_a = xmalloc (ldoc_a);
8426 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
8427 filename_to_ansi (SSDATA (current_dir), current_dir_a);
8428 if (STRINGP (parameters))
8430 parameters = ENCODE_SYSTEM (parameters);
8431 params_a = SSDATA (parameters);
8433 if (STRINGP (operation))
8435 /* Assume OPERATION is pure ASCII. */
8436 ops_a = SSDATA (operation);
8438 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
8439 shexinfo_a.cbSize = sizeof (shexinfo_a);
8440 shexinfo_a.fMask =
8441 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8442 shexinfo_a.hwnd = NULL;
8443 shexinfo_a.lpVerb = ops_a;
8444 shexinfo_a.lpFile = doc_a;
8445 shexinfo_a.lpParameters = params_a;
8446 shexinfo_a.lpDirectory = current_dir_a;
8447 shexinfo_a.nShow =
8448 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8449 success = ShellExecuteExA (&shexinfo_a);
8450 xfree (doc_w);
8451 xfree (doc_a);
8454 if (success)
8455 return Qt;
8457 errstr = w32_strerror (0);
8459 #endif /* !CYGWIN */
8461 /* The error string might be encoded in the locale's encoding. */
8462 if (!NILP (Vlocale_coding_system))
8464 Lisp_Object decoded =
8465 code_convert_string_norecord (build_unibyte_string (errstr),
8466 Vlocale_coding_system, 0);
8467 errstr = SSDATA (decoded);
8469 error ("ShellExecute failed: %s", errstr);
8472 /* Lookup virtual keycode from string representing the name of a
8473 non-ascii keystroke into the corresponding virtual key, using
8474 lispy_function_keys. */
8475 static int
8476 lookup_vk_code (char *key)
8478 int i;
8480 for (i = 0; i < 256; i++)
8481 if (lispy_function_keys[i]
8482 && strcmp (lispy_function_keys[i], key) == 0)
8483 return i;
8485 if (w32_kbdhook_active)
8487 /* Alphanumerics map to themselves. */
8488 if (key[1] == 0)
8490 if ((key[0] >= 'A' && key[0] <= 'Z')
8491 || (key[0] >= '0' && key[0] <= '9'))
8492 return key[0];
8493 if (key[0] >= 'a' && key[0] <= 'z')
8494 return toupper(key[0]);
8498 return -1;
8501 /* Convert a one-element vector style key sequence to a hot key
8502 definition. */
8503 static Lisp_Object
8504 w32_parse_and_hook_hot_key (Lisp_Object key, int hook)
8506 /* Copied from Fdefine_key and store_in_keymap. */
8507 register Lisp_Object c;
8508 int vk_code = 0;
8509 int lisp_modifiers = 0;
8510 int w32_modifiers;
8511 Lisp_Object res = Qnil;
8512 char* vkname;
8514 CHECK_VECTOR (key);
8516 if (ASIZE (key) != 1)
8517 return Qnil;
8519 c = AREF (key, 0);
8521 if (CONSP (c) && lucid_event_type_list_p (c))
8522 c = Fevent_convert_list (c);
8524 if (! INTEGERP (c) && ! SYMBOLP (c))
8525 error ("Key definition is invalid");
8527 /* Work out the base key and the modifiers. */
8528 if (SYMBOLP (c))
8530 c = parse_modifiers (c);
8531 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8532 c = Fcar (c);
8533 if (!SYMBOLP (c))
8534 emacs_abort ();
8535 vkname = SSDATA (SYMBOL_NAME (c));
8536 /* [s-], [M-], [h-]: Register all keys for this modifier */
8537 if (w32_kbdhook_active && vkname[0] == 0)
8538 vk_code = VK_ANY;
8539 else
8540 vk_code = lookup_vk_code (vkname);
8542 else if (INTEGERP (c))
8544 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8545 /* Many ascii characters are their own virtual key code. */
8546 vk_code = XINT (c) & CHARACTERBITS;
8549 if (vk_code < 0 || vk_code > 255)
8550 return Qnil;
8552 if ((lisp_modifiers & meta_modifier) != 0
8553 && !NILP (Vw32_alt_is_meta))
8554 lisp_modifiers |= alt_modifier;
8556 /* Supply defs missing from mingw32. */
8557 #ifndef MOD_ALT
8558 #define MOD_ALT 0x0001
8559 #define MOD_CONTROL 0x0002
8560 #define MOD_SHIFT 0x0004
8561 #define MOD_WIN 0x0008
8562 #endif
8564 if (w32_kbdhook_active)
8566 /* Register Alt-x combinations. */
8567 if (lisp_modifiers & alt_modifier)
8569 hook_w32_key (hook, VK_MENU, vk_code);
8570 res = Qt;
8572 /* Register Win-x combinations based on modifier mappings. */
8573 if (((lisp_modifiers & hyper_modifier)
8574 && EQ (Vw32_lwindow_modifier, Qhyper))
8575 || ((lisp_modifiers & super_modifier)
8576 && EQ (Vw32_lwindow_modifier, Qsuper)))
8578 hook_w32_key (hook, VK_LWIN, vk_code);
8579 res = Qt;
8581 if (((lisp_modifiers & hyper_modifier)
8582 && EQ (Vw32_rwindow_modifier, Qhyper))
8583 || ((lisp_modifiers & super_modifier)
8584 && EQ (Vw32_rwindow_modifier, Qsuper)))
8586 hook_w32_key (hook, VK_RWIN, vk_code);
8587 res = Qt;
8589 return res;
8591 else
8593 /* Convert lisp modifiers to Windows hot-key form. */
8594 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8595 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8596 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8597 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8599 return HOTKEY (vk_code, w32_modifiers);
8603 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8604 Sw32_register_hot_key, 1, 1, 0,
8605 doc: /* Register KEY as a hot-key combination.
8606 Certain key combinations like Alt-Tab and Win-R are reserved for
8607 system use on Windows, and therefore are normally intercepted by the
8608 system. These key combinations can be received by registering them
8609 as hot-keys, except for Win-L which always locks the computer.
8611 On Windows 98 and ME, KEY must be a one element key definition in
8612 vector form that would be acceptable to `define-key' (e.g. [A-tab] for
8613 Alt-Tab). The meta modifier is interpreted as Alt if
8614 `w32-alt-is-meta' is t, and hyper is always interpreted as the Windows
8615 modifier keys. The return value is the hotkey-id if registered, otherwise nil.
8617 On Windows versions since NT, KEY can also be specified as [M-], [s-] or
8618 [h-] to indicate that all combinations of that key should be processed
8619 by Emacs instead of the operating system. The super and hyper
8620 modifiers are interpreted according to the current values of
8621 `w32-lwindow-modifier' and `w32-rwindow-modifier'. For instance,
8622 setting `w32-lwindow-modifier' to `super' and then calling
8623 `(register-hot-key [s-])' grabs all combinations of the left Windows
8624 key to Emacs, but leaves the right Windows key free for the operating
8625 system keyboard shortcuts. The return value is t if the call affected
8626 any key combinations, otherwise nil. */)
8627 (Lisp_Object key)
8629 key = w32_parse_and_hook_hot_key (key, 1);
8631 if (!w32_kbdhook_active
8632 && !NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8634 /* Reuse an empty slot if possible. */
8635 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8637 /* Safe to add new key to list, even if we have focus. */
8638 if (NILP (item))
8639 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8640 else
8641 XSETCAR (item, key);
8643 /* Notify input thread about new hot-key definition, so that it
8644 takes effect without needing to switch focus. */
8645 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8646 (WPARAM) XINT (key), 0);
8649 return key;
8652 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8653 Sw32_unregister_hot_key, 1, 1, 0,
8654 doc: /* Unregister KEY as a hot-key combination. */)
8655 (Lisp_Object key)
8657 Lisp_Object item;
8659 if (!INTEGERP (key))
8660 key = w32_parse_and_hook_hot_key (key, 0);
8662 if (w32_kbdhook_active)
8663 return key;
8665 item = Fmemq (key, w32_grabbed_keys);
8667 if (!NILP (item))
8669 LPARAM lparam;
8671 eassert (CONSP (item));
8672 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
8673 so that it works in a --with-wide-int build as well. */
8674 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
8676 /* Notify input thread about hot-key definition being removed, so
8677 that it takes effect without needing focus switch. */
8678 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8679 (WPARAM) XINT (XCAR (item)), lparam))
8681 MSG msg;
8682 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8684 return Qt;
8686 return Qnil;
8689 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8690 Sw32_registered_hot_keys, 0, 0, 0,
8691 doc: /* Return list of registered hot-key IDs. */)
8692 (void)
8694 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8697 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8698 Sw32_reconstruct_hot_key, 1, 1, 0,
8699 doc: /* Convert hot-key ID to a lisp key combination.
8700 usage: (w32-reconstruct-hot-key ID) */)
8701 (Lisp_Object hotkeyid)
8703 int vk_code, w32_modifiers;
8704 Lisp_Object key;
8706 CHECK_NUMBER (hotkeyid);
8708 vk_code = HOTKEY_VK_CODE (hotkeyid);
8709 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8711 if (vk_code < 256 && lispy_function_keys[vk_code])
8712 key = intern (lispy_function_keys[vk_code]);
8713 else
8714 key = make_number (vk_code);
8716 key = Fcons (key, Qnil);
8717 if (w32_modifiers & MOD_SHIFT)
8718 key = Fcons (Qshift, key);
8719 if (w32_modifiers & MOD_CONTROL)
8720 key = Fcons (Qctrl, key);
8721 if (w32_modifiers & MOD_ALT)
8722 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8723 if (w32_modifiers & MOD_WIN)
8724 key = Fcons (Qhyper, key);
8726 return key;
8729 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8730 Sw32_toggle_lock_key, 1, 2, 0,
8731 doc: /* Toggle the state of the lock key KEY.
8732 KEY can be `capslock', `kp-numlock', or `scroll'.
8733 If the optional parameter NEW-STATE is a number, then the state of KEY
8734 is set to off if the low bit of NEW-STATE is zero, otherwise on.
8735 If NEW-STATE is omitted or nil, the function toggles the state,
8737 Value is the new state of the key, or nil if the function failed
8738 to change the state. */)
8739 (Lisp_Object key, Lisp_Object new_state)
8741 int vk_code;
8742 LPARAM lparam;
8744 if (EQ (key, intern ("capslock")))
8745 vk_code = VK_CAPITAL;
8746 else if (EQ (key, intern ("kp-numlock")))
8747 vk_code = VK_NUMLOCK;
8748 else if (EQ (key, intern ("scroll")))
8749 vk_code = VK_SCROLL;
8750 else
8751 return Qnil;
8753 if (!dwWindowsThreadId)
8754 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8756 if (NILP (new_state))
8757 lparam = -1;
8758 else
8759 lparam = (XUINT (new_state)) & 1;
8760 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8761 (WPARAM) vk_code, lparam))
8763 MSG msg;
8764 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8765 return make_number (msg.wParam);
8767 return Qnil;
8770 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8771 2, 2, 0,
8772 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8774 This is a direct interface to the Windows API FindWindow function. */)
8775 (Lisp_Object class, Lisp_Object name)
8777 HWND hnd;
8779 if (!NILP (class))
8780 CHECK_STRING (class);
8781 if (!NILP (name))
8782 CHECK_STRING (name);
8784 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8785 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8786 if (!hnd)
8787 return Qnil;
8788 return Qt;
8791 DEFUN ("w32-frame-geometry", Fw32_frame_geometry, Sw32_frame_geometry, 0, 1, 0,
8792 doc: /* Return geometric attributes of FRAME.
8793 FRAME must be a live frame and defaults to the selected one. The return
8794 value is an association list of the attributes listed below. All height
8795 and width values are in pixels.
8797 `outer-position' is a cons of the outer left and top edges of FRAME
8798 relative to the origin - the position (0, 0) - of FRAME's display.
8800 `outer-size' is a cons of the outer width and height of FRAME. The
8801 outer size includes the title bar and the external borders as well as
8802 any menu and/or tool bar of frame.
8804 `external-border-size' is a cons of the horizontal and vertical width of
8805 FRAME's external borders as supplied by the window manager.
8807 `title-bar-size' is a cons of the width and height of the title bar of
8808 FRAME as supplied by the window manager. If both of them are zero,
8809 FRAME has no title bar. If only the width is zero, Emacs was not
8810 able to retrieve the width information.
8812 `menu-bar-external', if non-nil, means the menu bar is external (never
8813 included in the inner edges of FRAME).
8815 `menu-bar-size' is a cons of the width and height of the menu bar of
8816 FRAME.
8818 `tool-bar-external', if non-nil, means the tool bar is external (never
8819 included in the inner edges of FRAME).
8821 `tool-bar-position' tells on which side the tool bar on FRAME is and can
8822 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
8823 has no tool bar.
8825 `tool-bar-size' is a cons of the width and height of the tool bar of
8826 FRAME.
8828 `internal-border-width' is the width of the internal border of
8829 FRAME. */)
8830 (Lisp_Object frame)
8832 struct frame *f = decode_live_frame (frame);
8834 MENUBARINFO menu_bar;
8835 WINDOWINFO window;
8836 int left, top, right, bottom;
8837 unsigned int external_border_width, external_border_height;
8838 int title_bar_width = 0, title_bar_height = 0;
8839 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8840 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8841 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8843 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8844 return Qnil;
8846 block_input ();
8847 /* Outer rectangle and borders. */
8848 window.cbSize = sizeof (window);
8849 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8850 external_border_width = window.cxWindowBorders;
8851 external_border_height = window.cyWindowBorders;
8852 /* Title bar. */
8853 if (get_title_bar_info_fn)
8855 TITLEBAR_INFO title_bar;
8857 title_bar.cbSize = sizeof (title_bar);
8858 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8859 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8860 for (int i = 0; i < 6; i++)
8861 title_bar.rgstate[i] = 0;
8862 if (get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar)
8863 && !(title_bar.rgstate[0] & 0x00008001))
8865 title_bar_width
8866 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8867 title_bar_height
8868 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8871 else if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8872 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8873 /* Menu bar. */
8874 menu_bar.cbSize = sizeof (menu_bar);
8875 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8876 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8877 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8878 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8879 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8880 unblock_input ();
8882 left = window.rcWindow.left;
8883 top = window.rcWindow.top;
8884 right = window.rcWindow.right;
8885 bottom = window.rcWindow.bottom;
8887 /* Menu bar. */
8888 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8889 /* Fix menu bar height reported by GetMenuBarInfo. */
8890 if (menu_bar_height > single_menu_bar_height)
8891 /* A wrapped menu bar. */
8892 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8893 else if (menu_bar_height > 0)
8894 /* A single line menu bar. */
8895 menu_bar_height = single_menu_bar_height;
8897 return listn (CONSTYPE_HEAP, 10,
8898 Fcons (Qouter_position,
8899 Fcons (make_number (left), make_number (top))),
8900 Fcons (Qouter_size,
8901 Fcons (make_number (right - left),
8902 make_number (bottom - top))),
8903 Fcons (Qexternal_border_size,
8904 Fcons (make_number (external_border_width),
8905 make_number (external_border_height))),
8906 Fcons (Qtitle_bar_size,
8907 Fcons (make_number (title_bar_width),
8908 make_number (title_bar_height))),
8909 Fcons (Qmenu_bar_external, Qt),
8910 Fcons (Qmenu_bar_size,
8911 Fcons (make_number
8912 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8913 make_number (menu_bar_height))),
8914 Fcons (Qtool_bar_external, Qnil),
8915 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8916 Fcons (Qtool_bar_size,
8917 Fcons (make_number
8918 (tool_bar_height
8919 ? (right - left - 2 * external_border_width
8920 - 2 * internal_border_width)
8921 : 0),
8922 make_number (tool_bar_height))),
8923 Fcons (Qinternal_border_width,
8924 make_number (internal_border_width)));
8927 DEFUN ("w32-frame-edges", Fw32_frame_edges, Sw32_frame_edges, 0, 2, 0,
8928 doc: /* Return edge coordinates of FRAME.
8929 FRAME must be a live frame and defaults to the selected one. The return
8930 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8931 in pixels relative to the origin - the position (0, 0) - of FRAME's
8932 display.
8934 If optional argument TYPE is the symbol `outer-edges', return the outer
8935 edges of FRAME. The outer edges comprise the decorations of the window
8936 manager (like the title bar or external borders) as well as any external
8937 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8938 `native-edges' or nil, return the native edges of FRAME. The native
8939 edges exclude the decorations of the window manager and any external
8940 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8941 the inner edges of FRAME. These edges exclude title bar, any borders,
8942 menu bar or tool bar of FRAME. */)
8943 (Lisp_Object frame, Lisp_Object type)
8945 struct frame *f = decode_live_frame (frame);
8947 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8948 return Qnil;
8950 if (EQ (type, Qouter_edges))
8952 RECT rectangle;
8954 block_input ();
8955 /* Outer frame rectangle, including outer borders and title bar. */
8956 GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8957 unblock_input ();
8959 return list4 (make_number (rectangle.left),
8960 make_number (rectangle.top),
8961 make_number (rectangle.right),
8962 make_number (rectangle.bottom));
8964 else
8966 RECT rectangle;
8967 POINT pt;
8968 int left, top, right, bottom;
8970 block_input ();
8971 /* Inner frame rectangle, excluding borders and title bar. */
8972 GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
8973 /* Get top-left corner of native rectangle in screen
8974 coordinates. */
8975 pt.x = 0;
8976 pt.y = 0;
8977 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
8978 unblock_input ();
8980 left = pt.x;
8981 top = pt.y;
8982 right = left + rectangle.right;
8983 bottom = top + rectangle.bottom;
8985 if (EQ (type, Qinner_edges))
8987 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8989 return list4 (make_number (left + internal_border_width),
8990 make_number (top
8991 + FRAME_TOOL_BAR_HEIGHT (f)
8992 + internal_border_width),
8993 make_number (right - internal_border_width),
8994 make_number (bottom - internal_border_width));
8996 else
8997 return list4 (make_number (left), make_number (top),
8998 make_number (right), make_number (bottom));
9003 * w32_frame_list_z_order:
9005 * Recursively add list of all frames on the display specified via
9006 * DPYINFO and whose window-system window's parent is specified by
9007 * WINDOW to FRAMES and return FRAMES.
9009 static Lisp_Object
9010 w32_frame_list_z_order (struct w32_display_info *dpyinfo, HWND window)
9012 Lisp_Object frame, frames = Qnil;
9014 while (window)
9016 struct frame *f = x_window_to_frame (dpyinfo, window);
9018 if (f)
9020 XSETFRAME (frame, f);
9021 frames = Fcons (frame, frames);
9024 block_input ();
9025 window = GetNextWindow (window, GW_HWNDNEXT);
9026 unblock_input ();
9029 return Fnreverse (frames);
9032 DEFUN ("w32-frame-list-z-order", Fw32_frame_list_z_order,
9033 Sw32_frame_list_z_order, 0, 1, 0,
9034 doc: /* Return list of Emacs' frames, in Z (stacking) order.
9035 The optional argument DISPLAY specifies which display to ask about.
9036 DISPLAY should be either a frame or a display name (a string). If
9037 omitted or nil, that stands for the selected frame's display.
9039 As a special case, if DISPLAY is non-nil and specifies a live frame,
9040 return the child frames of that frame in Z (stacking) order.
9042 Frames are listed from topmost (first) to bottommost (last). */)
9043 (Lisp_Object display)
9045 struct w32_display_info *dpyinfo = check_x_display_info (display);
9046 HWND window;
9048 block_input ();
9049 if (FRAMEP (display) && FRAME_LIVE_P (XFRAME (display)))
9050 window = GetWindow (FRAME_W32_WINDOW (XFRAME (display)), GW_CHILD);
9051 else
9052 window = GetTopWindow (NULL);
9053 unblock_input ();
9055 return w32_frame_list_z_order (dpyinfo, window);
9059 * w32_frame_restack:
9061 * Restack frame F1 below frame F2, above if ABOVE_FLAG is non-nil. In
9062 * practice this is a two-step action: The first step removes F1's
9063 * window-system window from the display. The second step reinserts
9064 * F1's window below (above if ABOVE_FLAG is true) that of F2.
9066 static void
9067 w32_frame_restack (struct frame *f1, struct frame *f2, bool above_flag)
9069 HWND hwnd1 = FRAME_W32_WINDOW (f1);
9070 HWND hwnd2 = FRAME_W32_WINDOW (f2);
9072 block_input ();
9073 if (above_flag)
9074 /* Put F1 above F2 in the z-order. */
9076 if (GetNextWindow (hwnd1, GW_HWNDNEXT) != hwnd2)
9078 /* Make sure F1 is below F2 first because we must not
9079 change the relative position of F2 wrt any other
9080 window but F1. */
9081 if (GetNextWindow (hwnd2, GW_HWNDNEXT) != hwnd1)
9082 SetWindowPos (hwnd1, hwnd2, 0, 0, 0, 0,
9083 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
9084 | SWP_FRAMECHANGED);
9085 /* Now put F1 above F2. */
9086 SetWindowPos (hwnd2, hwnd1, 0, 0, 0, 0,
9087 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
9088 | SWP_FRAMECHANGED);
9091 else if (GetNextWindow (hwnd2, GW_HWNDNEXT) != hwnd1)
9092 /* Put F1 below F2 in the z-order. */
9093 SetWindowPos (hwnd1, hwnd2, 0, 0, 0, 0,
9094 SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE
9095 | SWP_FRAMECHANGED);
9096 unblock_input ();
9099 DEFUN ("w32-frame-restack", Fw32_frame_restack, Sw32_frame_restack, 2, 3, 0,
9100 doc: /* Restack FRAME1 below FRAME2.
9101 This means that if both frames are visible and the display areas of
9102 these frames overlap, FRAME2 (partially) obscures FRAME1. If optional
9103 third argument ABOVE is non-nil, restack FRAME1 above FRAME2. This
9104 means that if both frames are visible and the display areas of these
9105 frames overlap, FRAME1 (partially) obscures FRAME2.
9107 This may be thought of as an atomic action performed in two steps: The
9108 first step removes FRAME1's window-system window from the display. The
9109 second step reinserts FRAME1's window below (above if ABOVE is true)
9110 that of FRAME2. Hence the position of FRAME2 in its display's Z
9111 \(stacking) order relative to all other frames excluding FRAME1 remains
9112 unaltered.
9114 Some window managers may refuse to restack windows. */)
9115 (Lisp_Object frame1, Lisp_Object frame2, Lisp_Object above)
9117 struct frame *f1 = decode_live_frame (frame1);
9118 struct frame *f2 = decode_live_frame (frame2);
9120 if (FRAME_W32_P (f1) && FRAME_W32_P (f2))
9122 w32_frame_restack (f1, f2, !NILP (above));
9123 return Qt;
9125 else
9127 error ("Cannot restack frames");
9128 return Qnil;
9132 DEFUN ("w32-mouse-absolute-pixel-position", Fw32_mouse_absolute_pixel_position,
9133 Sw32_mouse_absolute_pixel_position, 0, 0, 0,
9134 doc: /* Return absolute position of mouse cursor in pixels.
9135 The position is returned as a cons cell (X . Y) of the coordinates of
9136 the mouse cursor position in pixels relative to a position (0, 0) of the
9137 selected frame's display. */)
9138 (void)
9140 POINT pt;
9142 block_input ();
9143 GetCursorPos (&pt);
9144 unblock_input ();
9146 return Fcons (make_number (pt.x), make_number (pt.y));
9149 DEFUN ("w32-set-mouse-absolute-pixel-position", Fw32_set_mouse_absolute_pixel_position,
9150 Sw32_set_mouse_absolute_pixel_position, 2, 2, 0,
9151 doc: /* Move mouse pointer to absolute pixel position (X, Y).
9152 The coordinates X and Y are interpreted in pixels relative to a position
9153 \(0, 0) of the selected frame's display. */)
9154 (Lisp_Object x, Lisp_Object y)
9156 UINT trail_num = 0;
9157 BOOL ret = false;
9159 CHECK_TYPE_RANGED_INTEGER (int, x);
9160 CHECK_TYPE_RANGED_INTEGER (int, y);
9162 block_input ();
9163 /* When "mouse trails" are in effect, moving the mouse cursor
9164 sometimes leaves behind an annoying "ghost" of the pointer.
9165 Avoid that by momentarily switching off mouse trails. */
9166 if (os_subtype == OS_NT
9167 && w32_major_version + w32_minor_version >= 6)
9168 ret = SystemParametersInfo (SPI_GETMOUSETRAILS, 0, &trail_num, 0);
9169 SetCursorPos (XINT (x), XINT (y));
9170 if (ret)
9171 SystemParametersInfo (SPI_SETMOUSETRAILS, trail_num, NULL, 0);
9172 unblock_input ();
9174 return Qnil;
9177 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
9178 doc: /* Get power status information from Windows system.
9180 The following %-sequences are provided:
9181 %L AC line status (verbose)
9182 %B Battery status (verbose)
9183 %b Battery status, empty means high, `-' means low,
9184 `!' means critical, and `+' means charging
9185 %p Battery load percentage
9186 %s Remaining time (to charge or discharge) in seconds
9187 %m Remaining time (to charge or discharge) in minutes
9188 %h Remaining time (to charge or discharge) in hours
9189 %t Remaining time (to charge or discharge) in the form `h:min' */)
9190 (void)
9192 Lisp_Object status = Qnil;
9194 SYSTEM_POWER_STATUS system_status;
9195 if (GetSystemPowerStatus (&system_status))
9197 Lisp_Object line_status, battery_status, battery_status_symbol;
9198 Lisp_Object load_percentage, seconds, minutes, hours, remain;
9200 long seconds_left = (long) system_status.BatteryLifeTime;
9202 if (system_status.ACLineStatus == 0)
9203 line_status = build_string ("off-line");
9204 else if (system_status.ACLineStatus == 1)
9205 line_status = build_string ("on-line");
9206 else
9207 line_status = build_string ("N/A");
9209 if (system_status.BatteryFlag & 128)
9211 battery_status = build_string ("N/A");
9212 battery_status_symbol = empty_unibyte_string;
9214 else if (system_status.BatteryFlag & 8)
9216 battery_status = build_string ("charging");
9217 battery_status_symbol = build_string ("+");
9218 if (system_status.BatteryFullLifeTime != -1L)
9219 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
9221 else if (system_status.BatteryFlag & 4)
9223 battery_status = build_string ("critical");
9224 battery_status_symbol = build_string ("!");
9226 else if (system_status.BatteryFlag & 2)
9228 battery_status = build_string ("low");
9229 battery_status_symbol = build_string ("-");
9231 else if (system_status.BatteryFlag & 1)
9233 battery_status = build_string ("high");
9234 battery_status_symbol = empty_unibyte_string;
9236 else
9238 battery_status = build_string ("medium");
9239 battery_status_symbol = empty_unibyte_string;
9242 if (system_status.BatteryLifePercent > 100)
9243 load_percentage = build_string ("N/A");
9244 else
9246 char buffer[16];
9247 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
9248 load_percentage = build_string (buffer);
9251 if (seconds_left < 0)
9252 seconds = minutes = hours = remain = build_string ("N/A");
9253 else
9255 long m;
9256 double h;
9257 char buffer[16];
9258 snprintf (buffer, 16, "%ld", seconds_left);
9259 seconds = build_string (buffer);
9261 m = seconds_left / 60;
9262 snprintf (buffer, 16, "%ld", m);
9263 minutes = build_string (buffer);
9265 h = seconds_left / 3600.0;
9266 snprintf (buffer, 16, "%3.1f", h);
9267 hours = build_string (buffer);
9269 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
9270 remain = build_string (buffer);
9273 status = listn (CONSTYPE_HEAP, 8,
9274 Fcons (make_number ('L'), line_status),
9275 Fcons (make_number ('B'), battery_status),
9276 Fcons (make_number ('b'), battery_status_symbol),
9277 Fcons (make_number ('p'), load_percentage),
9278 Fcons (make_number ('s'), seconds),
9279 Fcons (make_number ('m'), minutes),
9280 Fcons (make_number ('h'), hours),
9281 Fcons (make_number ('t'), remain));
9283 return status;
9287 #ifdef WINDOWSNT
9288 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
9289 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
9290 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
9291 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
9293 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
9294 doc: /* Return storage information about the file system FILENAME is on.
9295 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
9296 storage of the file system, FREE is the free storage, and AVAIL is the
9297 storage available to a non-superuser. All 3 numbers are in bytes.
9298 If the underlying system call fails, value is nil. */)
9299 (Lisp_Object filename)
9301 Lisp_Object encoded, value;
9303 CHECK_STRING (filename);
9304 filename = Fexpand_file_name (filename, Qnil);
9305 encoded = ENCODE_FILE (filename);
9307 value = Qnil;
9309 /* Determining the required information on Windows turns out, sadly,
9310 to be more involved than one would hope. The original Windows API
9311 call for this will return bogus information on some systems, but we
9312 must dynamically probe for the replacement api, since that was
9313 added rather late on. */
9315 HMODULE hKernel = GetModuleHandle ("kernel32");
9316 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
9317 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
9318 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
9319 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
9320 bool have_pfn_GetDiskFreeSpaceEx =
9321 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
9322 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
9324 /* On Windows, we may need to specify the root directory of the
9325 volume holding FILENAME. */
9326 char rootname[MAX_UTF8_PATH];
9327 wchar_t rootname_w[MAX_PATH];
9328 char rootname_a[MAX_PATH];
9329 char *name = SSDATA (encoded);
9330 BOOL result;
9332 /* find the root name of the volume if given */
9333 if (isalpha (name[0]) && name[1] == ':')
9335 rootname[0] = name[0];
9336 rootname[1] = name[1];
9337 rootname[2] = '\\';
9338 rootname[3] = 0;
9340 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
9342 char *str = rootname;
9343 int slashes = 4;
9346 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
9347 break;
9348 *str++ = *name++;
9350 while ( *name );
9352 *str++ = '\\';
9353 *str = 0;
9356 if (w32_unicode_filenames)
9357 filename_to_utf16 (rootname, rootname_w);
9358 else
9359 filename_to_ansi (rootname, rootname_a);
9361 if (have_pfn_GetDiskFreeSpaceEx)
9363 /* Unsigned large integers cannot be cast to double, so
9364 use signed ones instead. */
9365 LARGE_INTEGER availbytes;
9366 LARGE_INTEGER freebytes;
9367 LARGE_INTEGER totalbytes;
9369 if (w32_unicode_filenames)
9370 result = pfn_GetDiskFreeSpaceExW (rootname_w,
9371 (ULARGE_INTEGER *)&availbytes,
9372 (ULARGE_INTEGER *)&totalbytes,
9373 (ULARGE_INTEGER *)&freebytes);
9374 else
9375 result = pfn_GetDiskFreeSpaceExA (rootname_a,
9376 (ULARGE_INTEGER *)&availbytes,
9377 (ULARGE_INTEGER *)&totalbytes,
9378 (ULARGE_INTEGER *)&freebytes);
9379 if (result)
9380 value = list3 (make_float ((double) totalbytes.QuadPart),
9381 make_float ((double) freebytes.QuadPart),
9382 make_float ((double) availbytes.QuadPart));
9384 else
9386 DWORD sectors_per_cluster;
9387 DWORD bytes_per_sector;
9388 DWORD free_clusters;
9389 DWORD total_clusters;
9391 if (w32_unicode_filenames)
9392 result = GetDiskFreeSpaceW (rootname_w,
9393 &sectors_per_cluster,
9394 &bytes_per_sector,
9395 &free_clusters,
9396 &total_clusters);
9397 else
9398 result = GetDiskFreeSpaceA (rootname_a,
9399 &sectors_per_cluster,
9400 &bytes_per_sector,
9401 &free_clusters,
9402 &total_clusters);
9403 if (result)
9404 value = list3 (make_float ((double) total_clusters
9405 * sectors_per_cluster * bytes_per_sector),
9406 make_float ((double) free_clusters
9407 * sectors_per_cluster * bytes_per_sector),
9408 make_float ((double) free_clusters
9409 * sectors_per_cluster * bytes_per_sector));
9413 return value;
9415 #endif /* WINDOWSNT */
9418 #ifdef WINDOWSNT
9419 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
9420 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
9421 (void)
9423 static char pname_buf[256];
9424 int err;
9425 HANDLE hPrn;
9426 PRINTER_INFO_2W *ppi2w = NULL;
9427 PRINTER_INFO_2A *ppi2a = NULL;
9428 DWORD dwNeeded = 0, dwReturned = 0;
9429 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
9430 char port_name[MAX_UTF8_PATH];
9432 /* Retrieve the default string from Win.ini (the registry).
9433 * String will be in form "printername,drivername,portname".
9434 * This is the most portable way to get the default printer. */
9435 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
9436 return Qnil;
9437 /* printername precedes first "," character */
9438 strtok (pname_buf, ",");
9439 /* We want to know more than the printer name */
9440 if (!OpenPrinter (pname_buf, &hPrn, NULL))
9441 return Qnil;
9442 /* GetPrinterW is not supported by unicows.dll. */
9443 if (w32_unicode_filenames && os_subtype != OS_9X)
9444 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
9445 else
9446 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
9447 if (dwNeeded == 0)
9449 ClosePrinter (hPrn);
9450 return Qnil;
9452 /* Call GetPrinter again with big enough memory block. */
9453 if (w32_unicode_filenames && os_subtype != OS_9X)
9455 /* Allocate memory for the PRINTER_INFO_2 struct. */
9456 ppi2w = xmalloc (dwNeeded);
9457 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
9458 ClosePrinter (hPrn);
9459 if (!err)
9461 xfree (ppi2w);
9462 return Qnil;
9465 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
9466 && ppi2w->pServerName)
9468 filename_from_utf16 (ppi2w->pServerName, server_name);
9469 filename_from_utf16 (ppi2w->pShareName, share_name);
9471 else
9473 server_name[0] = '\0';
9474 filename_from_utf16 (ppi2w->pPortName, port_name);
9477 else
9479 ppi2a = xmalloc (dwNeeded);
9480 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
9481 ClosePrinter (hPrn);
9482 if (!err)
9484 xfree (ppi2a);
9485 return Qnil;
9488 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
9489 && ppi2a->pServerName)
9491 filename_from_ansi (ppi2a->pServerName, server_name);
9492 filename_from_ansi (ppi2a->pShareName, share_name);
9494 else
9496 server_name[0] = '\0';
9497 filename_from_ansi (ppi2a->pPortName, port_name);
9501 if (server_name[0])
9503 /* a remote printer */
9504 if (server_name[0] == '\\')
9505 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
9506 share_name);
9507 else
9508 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
9509 share_name);
9510 pname_buf[sizeof (pname_buf) - 1] = '\0';
9512 else
9514 /* a local printer */
9515 strncpy (pname_buf, port_name, sizeof (pname_buf));
9516 pname_buf[sizeof (pname_buf) - 1] = '\0';
9517 /* `pPortName' can include several ports, delimited by ','.
9518 * we only use the first one. */
9519 strtok (pname_buf, ",");
9522 return DECODE_FILE (build_unibyte_string (pname_buf));
9524 #endif /* WINDOWSNT */
9527 /* Equivalent of strerror for W32 error codes. */
9528 char *
9529 w32_strerror (int error_no)
9531 static char buf[500];
9532 DWORD ret;
9534 if (error_no == 0)
9535 error_no = GetLastError ();
9537 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
9538 FORMAT_MESSAGE_IGNORE_INSERTS,
9539 NULL,
9540 error_no,
9541 0, /* choose most suitable language */
9542 buf, sizeof (buf), NULL);
9544 while (ret > 0 && (buf[ret - 1] == '\n' ||
9545 buf[ret - 1] == '\r' ))
9546 --ret;
9547 buf[ret] = '\0';
9548 if (!ret)
9549 sprintf (buf, "w32 error %d", error_no);
9551 return buf;
9554 /* For convenience when debugging. (You cannot call GetLastError
9555 directly from GDB: it will crash, because it uses the __stdcall
9556 calling convention, not the _cdecl convention assumed by GDB.) */
9557 DWORD w32_last_error (void);
9559 DWORD
9560 w32_last_error (void)
9562 return GetLastError ();
9565 /* Cache information describing the NT system for later use. */
9566 void
9567 cache_system_info (void)
9569 union
9571 struct info
9573 char major;
9574 char minor;
9575 short platform;
9576 } info;
9577 DWORD data;
9578 } version;
9580 /* Cache the module handle of Emacs itself. */
9581 hinst = GetModuleHandle (NULL);
9583 /* Cache the version of the operating system. */
9584 version.data = GetVersion ();
9585 w32_major_version = version.info.major;
9586 w32_minor_version = version.info.minor;
9588 if (version.info.platform & 0x8000)
9589 os_subtype = OS_9X;
9590 else
9591 os_subtype = OS_NT;
9593 /* Cache page size, allocation unit, processor type, etc. */
9594 GetSystemInfo (&sysinfo_cache);
9595 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
9597 /* Cache os info. */
9598 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
9599 GetVersionEx (&osinfo_cache);
9601 w32_build_number = osinfo_cache.dwBuildNumber;
9602 if (os_subtype == OS_9X)
9603 w32_build_number &= 0xffff;
9605 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
9608 #ifdef EMACSDEBUG
9609 void
9610 _DebPrint (const char *fmt, ...)
9612 char buf[1024];
9613 va_list args;
9615 va_start (args, fmt);
9616 vsprintf (buf, fmt, args);
9617 va_end (args);
9618 #if CYGWIN
9619 fprintf (stderr, "%s", buf);
9620 #endif
9621 OutputDebugString (buf);
9623 #endif
9626 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
9628 int cur_state = (GetKeyState (vk_code) & 1);
9630 if (NILP (new_state)
9631 || (NUMBERP (new_state)
9632 && ((XUINT (new_state)) & 1) != cur_state))
9634 #ifdef WINDOWSNT
9635 faked_key = vk_code;
9636 #endif /* WINDOWSNT */
9638 keybd_event ((BYTE) vk_code,
9639 (BYTE) MapVirtualKey (vk_code, 0),
9640 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9641 keybd_event ((BYTE) vk_code,
9642 (BYTE) MapVirtualKey (vk_code, 0),
9643 KEYEVENTF_EXTENDEDKEY | 0, 0);
9644 keybd_event ((BYTE) vk_code,
9645 (BYTE) MapVirtualKey (vk_code, 0),
9646 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9647 cur_state = !cur_state;
9650 return cur_state;
9653 /* Translate console modifiers to emacs modifiers.
9654 German keyboard support (Kai Morgan Zeise 2/18/95). */
9656 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
9658 int retval = 0;
9660 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
9661 pressed, first remove those modifiers. */
9662 if (!NILP (Vw32_recognize_altgr)
9663 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9664 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9665 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
9667 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
9668 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
9670 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9672 retval |= ctrl_modifier;
9673 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9674 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9675 retval |= meta_modifier;
9678 if (mods & LEFT_WIN_PRESSED)
9679 retval |= w32_key_to_modifier (VK_LWIN);
9680 if (mods & RIGHT_WIN_PRESSED)
9681 retval |= w32_key_to_modifier (VK_RWIN);
9682 if (mods & APPS_PRESSED)
9683 retval |= w32_key_to_modifier (VK_APPS);
9684 if (mods & SCROLLLOCK_ON)
9685 retval |= w32_key_to_modifier (VK_SCROLL);
9687 /* Just in case someone wanted the original behavior, make it
9688 optional by setting w32-capslock-is-shiftlock to t. */
9689 if (NILP (Vw32_capslock_is_shiftlock)
9690 /* Keys that should _not_ be affected by CapsLock. */
9691 && ( (key == VK_BACK)
9692 || (key == VK_TAB)
9693 || (key == VK_CLEAR)
9694 || (key == VK_RETURN)
9695 || (key == VK_ESCAPE)
9696 || ((key >= VK_SPACE) && (key <= VK_HELP))
9697 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
9698 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
9701 /* Only consider shift state. */
9702 if ((mods & SHIFT_PRESSED) != 0)
9703 retval |= shift_modifier;
9705 else
9707 /* Ignore CapsLock state if not enabled. */
9708 if (NILP (Vw32_enable_caps_lock))
9709 mods &= ~CAPSLOCK_ON;
9710 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
9711 retval |= shift_modifier;
9714 return retval;
9717 /* The return code indicates key code size. cpID is the codepage to
9718 use for translation to Unicode; -1 means use the current console
9719 input codepage. */
9721 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
9723 unsigned int key_code = event->wVirtualKeyCode;
9724 unsigned int mods = event->dwControlKeyState;
9725 BYTE keystate[256];
9726 static BYTE ansi_code[4];
9727 static int isdead = 0;
9729 if (isdead == 2)
9731 event->uChar.AsciiChar = ansi_code[2];
9732 isdead = 0;
9733 return 1;
9735 if (event->uChar.AsciiChar != 0)
9736 return 1;
9738 memset (keystate, 0, sizeof (keystate));
9739 keystate[key_code] = 0x80;
9740 if (mods & SHIFT_PRESSED)
9741 keystate[VK_SHIFT] = 0x80;
9742 if (mods & CAPSLOCK_ON)
9743 keystate[VK_CAPITAL] = 1;
9744 /* If we recognize right-alt and left-ctrl as AltGr, set the key
9745 states accordingly before invoking ToAscii. */
9746 if (!NILP (Vw32_recognize_altgr)
9747 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
9749 keystate[VK_CONTROL] = 0x80;
9750 keystate[VK_LCONTROL] = 0x80;
9751 keystate[VK_MENU] = 0x80;
9752 keystate[VK_RMENU] = 0x80;
9755 #if 0
9756 /* Because of an OS bug, ToAscii corrupts the stack when called to
9757 convert a dead key in console mode on NT4. Unfortunately, trying
9758 to check for dead keys using MapVirtualKey doesn't work either -
9759 these functions apparently use internal information about keyboard
9760 layout which doesn't get properly updated in console programs when
9761 changing layout (though apparently it gets partly updated,
9762 otherwise ToAscii wouldn't crash). */
9763 if (is_dead_key (event->wVirtualKeyCode))
9764 return 0;
9765 #endif
9767 /* On NT, call ToUnicode instead and then convert to the current
9768 console input codepage. */
9769 if (os_subtype == OS_NT)
9771 WCHAR buf[128];
9773 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
9774 keystate, buf, 128, 0);
9775 if (isdead > 0)
9777 /* When we are called from the GUI message processing code,
9778 we are passed the current keyboard codepage, a positive
9779 number, to use below. */
9780 if (cpId == -1)
9781 cpId = GetConsoleCP ();
9783 event->uChar.UnicodeChar = buf[isdead - 1];
9784 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
9785 (LPSTR)ansi_code, 4, NULL, NULL);
9787 else
9788 isdead = 0;
9790 else
9792 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
9793 keystate, (LPWORD) ansi_code, 0);
9796 if (isdead == 0)
9797 return 0;
9798 event->uChar.AsciiChar = ansi_code[0];
9799 return isdead;
9803 void
9804 w32_sys_ring_bell (struct frame *f)
9806 if (sound_type == 0xFFFFFFFF)
9808 Beep (666, 100);
9810 else if (sound_type == MB_EMACS_SILENT)
9812 /* Do nothing. */
9814 else
9815 MessageBeep (sound_type);
9818 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
9819 0, 0, 0,
9820 doc: /* Return non-nil when a menu-bar menu is being used.
9821 Internal use only. */)
9822 (void)
9824 return menubar_in_use ? Qt : Qnil;
9827 #if defined WINDOWSNT && !defined HAVE_DBUS
9829 /***********************************************************************
9830 Tray notifications
9831 ***********************************************************************/
9832 /* A private struct declaration to avoid compile-time limits. */
9833 typedef struct MY_NOTIFYICONDATAW {
9834 DWORD cbSize;
9835 HWND hWnd;
9836 UINT uID;
9837 UINT uFlags;
9838 UINT uCallbackMessage;
9839 HICON hIcon;
9840 WCHAR szTip[128];
9841 DWORD dwState;
9842 DWORD dwStateMask;
9843 WCHAR szInfo[256];
9844 _ANONYMOUS_UNION union {
9845 UINT uTimeout;
9846 UINT uVersion;
9847 } DUMMYUNIONNAME;
9848 WCHAR szInfoTitle[64];
9849 DWORD dwInfoFlags;
9850 GUID guidItem;
9851 HICON hBalloonIcon;
9852 } MY_NOTIFYICONDATAW;
9854 #define MYNOTIFYICONDATAW_V1_SIZE offsetof (MY_NOTIFYICONDATAW, szTip[64])
9855 #define MYNOTIFYICONDATAW_V2_SIZE offsetof (MY_NOTIFYICONDATAW, guidItem)
9856 #define MYNOTIFYICONDATAW_V3_SIZE offsetof (MY_NOTIFYICONDATAW, hBalloonIcon)
9857 #ifndef NIF_INFO
9858 # define NIF_INFO 0x00000010
9859 #endif
9860 #ifndef NIIF_NONE
9861 # define NIIF_NONE 0x00000000
9862 #endif
9863 #ifndef NIIF_INFO
9864 # define NIIF_INFO 0x00000001
9865 #endif
9866 #ifndef NIIF_WARNING
9867 # define NIIF_WARNING 0x00000002
9868 #endif
9869 #ifndef NIIF_ERROR
9870 # define NIIF_ERROR 0x00000003
9871 #endif
9874 #define EMACS_TRAY_NOTIFICATION_ID 42 /* arbitrary */
9875 #define EMACS_NOTIFICATION_MSG (WM_APP + 1)
9877 enum NI_Severity {
9878 Ni_None,
9879 Ni_Info,
9880 Ni_Warn,
9881 Ni_Err
9884 /* Report the version of a DLL given by its name. The return value is
9885 constructed using MAKEDLLVERULL. */
9886 static ULONGLONG
9887 get_dll_version (const char *dll_name)
9889 ULONGLONG version = 0;
9890 HINSTANCE hdll = LoadLibrary (dll_name);
9892 if (hdll)
9894 DLLGETVERSIONPROC pDllGetVersion
9895 = (DLLGETVERSIONPROC) GetProcAddress (hdll, "DllGetVersion");
9897 if (pDllGetVersion)
9899 DLLVERSIONINFO dvi;
9900 HRESULT result;
9902 memset (&dvi, 0, sizeof(dvi));
9903 dvi.cbSize = sizeof(dvi);
9904 result = pDllGetVersion (&dvi);
9905 if (SUCCEEDED (result))
9906 version = MAKEDLLVERULL (dvi.dwMajorVersion, dvi.dwMinorVersion,
9907 0, 0);
9909 FreeLibrary (hdll);
9912 return version;
9915 /* Return the number of bytes in UTF-8 encoded string STR that
9916 corresponds to at most LIM characters. If STR ends before LIM
9917 characters, return the number of bytes in STR including the
9918 terminating null byte. */
9919 static int
9920 utf8_mbslen_lim (const char *str, int lim)
9922 const char *p = str;
9923 int mblen = 0, nchars = 0;
9925 while (*p && nchars < lim)
9927 int nbytes = CHAR_BYTES (*p);
9929 mblen += nbytes;
9930 nchars++;
9931 p += nbytes;
9934 if (!*p && nchars < lim)
9935 mblen++;
9937 return mblen;
9940 /* Low-level subroutine to show tray notifications. All strings are
9941 supposed to be unibyte UTF-8 encoded by the caller. */
9942 static EMACS_INT
9943 add_tray_notification (struct frame *f, const char *icon, const char *tip,
9944 enum NI_Severity severity, unsigned timeout,
9945 const char *title, const char *msg)
9947 EMACS_INT retval = EMACS_TRAY_NOTIFICATION_ID;
9949 if (FRAME_W32_P (f))
9951 MY_NOTIFYICONDATAW nidw;
9952 ULONGLONG shell_dll_version = get_dll_version ("Shell32.dll");
9953 wchar_t tipw[128], msgw[256], titlew[64];
9954 int tiplen;
9956 memset (&nidw, 0, sizeof(nidw));
9958 /* MSDN says the full struct is supported since Vista, whose
9959 Shell32.dll version is said to be 6.0.6. But DllGetVersion
9960 cannot report the 3rd field value, it reports "build number"
9961 instead, which is something else. So we use the Windows 7's
9962 version 6.1 as cutoff, and Vista loses. (Actually, the loss
9963 is not a real one, since we don't expose the hBalloonIcon
9964 member of the struct to Lisp.) */
9965 if (shell_dll_version >= MAKEDLLVERULL (6, 1, 0, 0)) /* >= Windows 7 */
9966 nidw.cbSize = sizeof (nidw);
9967 else if (shell_dll_version >= MAKEDLLVERULL (6, 0, 0, 0)) /* XP */
9968 nidw.cbSize = MYNOTIFYICONDATAW_V3_SIZE;
9969 else if (shell_dll_version >= MAKEDLLVERULL (5, 0, 0, 0)) /* W2K */
9970 nidw.cbSize = MYNOTIFYICONDATAW_V2_SIZE;
9971 else
9972 nidw.cbSize = MYNOTIFYICONDATAW_V1_SIZE; /* < W2K */
9973 nidw.hWnd = FRAME_W32_WINDOW (f);
9974 nidw.uID = EMACS_TRAY_NOTIFICATION_ID;
9975 nidw.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO;
9976 nidw.uCallbackMessage = EMACS_NOTIFICATION_MSG;
9977 if (!*icon)
9978 nidw.hIcon = LoadIcon (hinst, EMACS_CLASS);
9979 else
9981 if (w32_unicode_filenames)
9983 wchar_t icon_w[MAX_PATH];
9985 if (filename_to_utf16 (icon, icon_w) != 0)
9987 errno = ENOENT;
9988 return -1;
9990 nidw.hIcon = LoadImageW (NULL, icon_w, IMAGE_ICON, 0, 0,
9991 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9993 else
9995 char icon_a[MAX_PATH];
9997 if (filename_to_ansi (icon, icon_a) != 0)
9999 errno = ENOENT;
10000 return -1;
10002 nidw.hIcon = LoadImageA (NULL, icon_a, IMAGE_ICON, 0, 0,
10003 LR_DEFAULTSIZE | LR_LOADFROMFILE);
10006 if (!nidw.hIcon)
10008 switch (GetLastError ())
10010 case ERROR_FILE_NOT_FOUND:
10011 errno = ENOENT;
10012 break;
10013 default:
10014 errno = ENOMEM;
10015 break;
10017 return -1;
10020 /* Windows 9X and NT4 support only 64 characters in the Tip,
10021 later versions support up to 128. */
10022 if (nidw.cbSize == MYNOTIFYICONDATAW_V1_SIZE)
10024 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10025 tip, utf8_mbslen_lim (tip, 63),
10026 tipw, 64);
10027 if (tiplen >= 63)
10028 tipw[63] = 0;
10030 else
10032 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10033 tip, utf8_mbslen_lim (tip, 127),
10034 tipw, 128);
10035 if (tiplen >= 127)
10036 tipw[127] = 0;
10038 if (tiplen == 0)
10040 errno = EINVAL;
10041 retval = -1;
10042 goto done;
10044 wcscpy (nidw.szTip, tipw);
10046 /* The rest of the structure is only supported since Windows 2000. */
10047 if (nidw.cbSize > MYNOTIFYICONDATAW_V1_SIZE)
10049 int slen;
10051 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10052 msg, utf8_mbslen_lim (msg, 255),
10053 msgw, 256);
10054 if (slen >= 255)
10055 msgw[255] = 0;
10056 else if (slen == 0)
10058 errno = EINVAL;
10059 retval = -1;
10060 goto done;
10062 wcscpy (nidw.szInfo, msgw);
10063 nidw.uTimeout = timeout;
10064 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
10065 title, utf8_mbslen_lim (title, 63),
10066 titlew, 64);
10067 if (slen >= 63)
10068 titlew[63] = 0;
10069 else if (slen == 0)
10071 errno = EINVAL;
10072 retval = -1;
10073 goto done;
10075 wcscpy (nidw.szInfoTitle, titlew);
10077 switch (severity)
10079 case Ni_None:
10080 nidw.dwInfoFlags = NIIF_NONE;
10081 break;
10082 case Ni_Info:
10083 default:
10084 nidw.dwInfoFlags = NIIF_INFO;
10085 break;
10086 case Ni_Warn:
10087 nidw.dwInfoFlags = NIIF_WARNING;
10088 break;
10089 case Ni_Err:
10090 nidw.dwInfoFlags = NIIF_ERROR;
10091 break;
10095 if (!Shell_NotifyIconW (NIM_ADD, (PNOTIFYICONDATAW)&nidw))
10097 /* GetLastError returns meaningless results when
10098 Shell_NotifyIcon fails. */
10099 DebPrint (("Shell_NotifyIcon ADD failed (err=%d)\n",
10100 GetLastError ()));
10101 errno = EINVAL;
10102 retval = -1;
10104 done:
10105 if (*icon && !DestroyIcon (nidw.hIcon))
10106 DebPrint (("DestroyIcon failed (err=%d)\n", GetLastError ()));
10108 return retval;
10111 /* Low-level subroutine to remove a tray notification. Note: we only
10112 pass the minimum data about the notification: its ID and the handle
10113 of the window to which it sends messages. MSDN doesn't say this is
10114 enough, but it works in practice. This allows us to avoid keeping
10115 the notification data around after we show the notification. */
10116 static void
10117 delete_tray_notification (struct frame *f, int id)
10119 if (FRAME_W32_P (f))
10121 MY_NOTIFYICONDATAW nidw;
10123 memset (&nidw, 0, sizeof(nidw));
10124 nidw.hWnd = FRAME_W32_WINDOW (f);
10125 nidw.uID = id;
10127 if (!Shell_NotifyIconW (NIM_DELETE, (PNOTIFYICONDATAW)&nidw))
10129 /* GetLastError returns meaningless results when
10130 Shell_NotifyIcon fails. */
10131 DebPrint (("Shell_NotifyIcon DELETE failed\n"));
10132 errno = EINVAL;
10133 return;
10136 return;
10139 DEFUN ("w32-notification-notify",
10140 Fw32_notification_notify, Sw32_notification_notify,
10141 0, MANY, 0,
10142 doc: /* Display an MS-Windows tray notification as specified by PARAMS.
10144 Value is the integer unique ID of the notification that can be used
10145 to remove the notification using `w32-notification-close', which see.
10146 If the function fails, the return value is nil.
10148 Tray notifications, a.k.a. \"taskbar messages\", are messages that
10149 inform the user about events unrelated to the current user activity,
10150 such as a significant system event, by briefly displaying informative
10151 text in a balloon from an icon in the notification area of the taskbar.
10153 Parameters in PARAMS are specified as keyword/value pairs. All the
10154 parameters are optional, but if no parameters are specified, the
10155 function will do nothing and return nil.
10157 The following parameters are supported:
10159 :icon ICON -- Display ICON in the system tray. If ICON is a string,
10160 it should specify a file name from which to load the
10161 icon; the specified file should be a .ico Windows icon
10162 file. If ICON is not a string, or if this parameter
10163 is not specified, the standard Emacs icon will be used.
10165 :tip TIP -- Use TIP as the tooltip for the notification. If TIP
10166 is a string, this is the text of a tooltip that will
10167 be shown when the mouse pointer hovers over the tray
10168 icon added by the notification. If TIP is not a
10169 string, or if this parameter is not specified, the
10170 default tooltip text is \"Emacs notification\". The
10171 tooltip text can be up to 127 characters long (63
10172 on Windows versions before W2K). Longer strings
10173 will be truncated.
10175 :level LEVEL -- Notification severity level, one of `info',
10176 `warning', or `error'. If given, the value
10177 determines the icon displayed to the left of the
10178 notification title, but only if the `:title'
10179 parameter (see below) is also specified and is a
10180 string.
10182 :title TITLE -- The title of the notification. If TITLE is a string,
10183 it is displayed in a larger font immediately above
10184 the body text. The title text can be up to 63
10185 characters long; longer text will be truncated.
10187 :body BODY -- The body of the notification. If BODY is a string,
10188 it specifies the text of the notification message.
10189 Use embedded newlines to control how the text is
10190 broken into lines. The body text can be up to 255
10191 characters long, and will be truncated if it's longer.
10193 Note that versions of Windows before W2K support only `:icon' and `:tip'.
10194 You can pass the other parameters, but they will be ignored on those
10195 old systems.
10197 There can be at most one active notification at any given time. An
10198 active notification must be removed by calling `w32-notification-close'
10199 before a new one can be shown.
10201 usage: (w32-notification-notify &rest PARAMS) */)
10202 (ptrdiff_t nargs, Lisp_Object *args)
10204 struct frame *f = SELECTED_FRAME ();
10205 Lisp_Object arg_plist, lres;
10206 EMACS_INT retval;
10207 char *icon, *tip, *title, *msg;
10208 enum NI_Severity severity;
10209 unsigned timeout = 0;
10211 if (nargs == 0)
10212 return Qnil;
10214 arg_plist = Flist (nargs, args);
10216 /* Icon. */
10217 lres = Fplist_get (arg_plist, QCicon);
10218 if (STRINGP (lres))
10219 icon = SSDATA (ENCODE_FILE (Fexpand_file_name (lres, Qnil)));
10220 else
10221 icon = (char *)"";
10223 /* Tip. */
10224 lres = Fplist_get (arg_plist, QCtip);
10225 if (STRINGP (lres))
10226 tip = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10227 else
10228 tip = (char *)"Emacs notification";
10230 /* Severity. */
10231 lres = Fplist_get (arg_plist, QClevel);
10232 if (NILP (lres))
10233 severity = Ni_None;
10234 else if (EQ (lres, Qinfo))
10235 severity = Ni_Info;
10236 else if (EQ (lres, Qwarning))
10237 severity = Ni_Warn;
10238 else if (EQ (lres, Qerror))
10239 severity = Ni_Err;
10240 else
10241 severity = Ni_Info;
10243 /* Title. */
10244 lres = Fplist_get (arg_plist, QCtitle);
10245 if (STRINGP (lres))
10246 title = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10247 else
10248 title = (char *)"";
10250 /* Notification body text. */
10251 lres = Fplist_get (arg_plist, QCbody);
10252 if (STRINGP (lres))
10253 msg = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
10254 else
10255 msg = (char *)"";
10257 /* Do it! */
10258 retval = add_tray_notification (f, icon, tip, severity, timeout, title, msg);
10259 return (retval < 0 ? Qnil : make_number (retval));
10262 DEFUN ("w32-notification-close",
10263 Fw32_notification_close, Sw32_notification_close,
10264 1, 1, 0,
10265 doc: /* Remove the MS-Windows tray notification specified by its ID. */)
10266 (Lisp_Object id)
10268 struct frame *f = SELECTED_FRAME ();
10270 if (INTEGERP (id))
10271 delete_tray_notification (f, XINT (id));
10273 return Qnil;
10276 #endif /* WINDOWSNT && !HAVE_DBUS */
10279 /***********************************************************************
10280 Initialization
10281 ***********************************************************************/
10283 /* Keep this list in the same order as frame_parms in frame.c.
10284 Use 0 for unsupported frame parameters. */
10286 frame_parm_handler w32_frame_parm_handlers[] =
10288 x_set_autoraise,
10289 x_set_autolower,
10290 x_set_background_color,
10291 x_set_border_color,
10292 x_set_border_width,
10293 x_set_cursor_color,
10294 x_set_cursor_type,
10295 x_set_font,
10296 x_set_foreground_color,
10297 x_set_icon_name,
10298 x_set_icon_type,
10299 x_set_internal_border_width,
10300 x_set_right_divider_width,
10301 x_set_bottom_divider_width,
10302 x_set_menu_bar_lines,
10303 x_set_mouse_color,
10304 x_explicitly_set_name,
10305 x_set_scroll_bar_width,
10306 x_set_scroll_bar_height,
10307 x_set_title,
10308 x_set_unsplittable,
10309 x_set_vertical_scroll_bars,
10310 x_set_horizontal_scroll_bars,
10311 x_set_visibility,
10312 x_set_tool_bar_lines,
10313 0, /* x_set_scroll_bar_foreground, */
10314 0, /* x_set_scroll_bar_background, */
10315 x_set_screen_gamma,
10316 x_set_line_spacing,
10317 x_set_left_fringe,
10318 x_set_right_fringe,
10319 0, /* x_set_wait_for_wm, */
10320 x_set_fullscreen,
10321 x_set_font_backend,
10322 x_set_alpha,
10323 0, /* x_set_sticky */
10324 0, /* x_set_tool_bar_position */
10325 0, /* x_set_inhibit_double_buffering */
10326 x_set_undecorated,
10327 x_set_parent_frame,
10328 x_set_skip_taskbar,
10329 x_set_no_focus_on_map,
10330 x_set_no_accept_focus,
10331 x_set_z_group,
10332 0, /* x_set_override_redirect */
10335 void
10336 syms_of_w32fns (void)
10338 globals_of_w32fns ();
10339 track_mouse_window = NULL;
10341 w32_visible_system_caret_hwnd = NULL;
10343 DEFSYM (Qundefined_color, "undefined-color");
10344 DEFSYM (Qcancel_timer, "cancel-timer");
10345 DEFSYM (Qhyper, "hyper");
10346 DEFSYM (Qsuper, "super");
10347 DEFSYM (Qmeta, "meta");
10348 DEFSYM (Qalt, "alt");
10349 DEFSYM (Qctrl, "ctrl");
10350 DEFSYM (Qcontrol, "control");
10351 DEFSYM (Qshift, "shift");
10352 DEFSYM (Qfont_parameter, "font-parameter");
10353 DEFSYM (Qgeometry, "geometry");
10354 DEFSYM (Qworkarea, "workarea");
10355 DEFSYM (Qmm_size, "mm-size");
10356 DEFSYM (Qframes, "frames");
10357 DEFSYM (Qtip_frame, "tip-frame");
10358 DEFSYM (Qassq_delete_all, "assq-delete-all");
10359 DEFSYM (Qunicode_sip, "unicode-sip");
10360 #if defined WINDOWSNT && !defined HAVE_DBUS
10361 DEFSYM (QCicon, ":icon");
10362 DEFSYM (QCtip, ":tip");
10363 DEFSYM (QClevel, ":level");
10364 DEFSYM (Qinfo, "info");
10365 DEFSYM (Qwarning, "warning");
10366 DEFSYM (QCtitle, ":title");
10367 DEFSYM (QCbody, ":body");
10368 #endif
10370 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
10371 DEFSYM (Qgnutls, "gnutls");
10372 DEFSYM (Qlibxml2, "libxml2");
10373 DEFSYM (Qserif, "serif");
10374 DEFSYM (Qzlib, "zlib");
10376 Fput (Qundefined_color, Qerror_conditions,
10377 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
10378 Fput (Qundefined_color, Qerror_message,
10379 build_pure_c_string ("Undefined color"));
10381 staticpro (&w32_grabbed_keys);
10382 w32_grabbed_keys = Qnil;
10384 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
10385 doc: /* An array of color name mappings for Windows. */);
10386 Vw32_color_map = Qnil;
10388 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
10389 doc: /* Non-nil if Alt key presses are passed on to Windows.
10390 When non-nil, for example, Alt pressed and released and then space will
10391 open the System menu. When nil, Emacs processes the Alt key events, and
10392 then silently swallows them. */);
10393 Vw32_pass_alt_to_system = Qnil;
10395 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
10396 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
10397 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
10398 Vw32_alt_is_meta = Qt;
10400 DEFVAR_INT ("w32-quit-key", w32_quit_key,
10401 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
10402 w32_quit_key = 0;
10404 DEFVAR_LISP ("w32-pass-lwindow-to-system",
10405 Vw32_pass_lwindow_to_system,
10406 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
10408 When non-nil, the Start menu is opened by tapping the key.
10409 If you set this to nil, the left \"Windows\" key is processed by Emacs
10410 according to the value of `w32-lwindow-modifier', which see.
10412 Note that some combinations of the left \"Windows\" key with other
10413 keys are caught by Windows at low level. For example, <lwindow>-r
10414 pops up the Windows Run dialog, <lwindow>-<Pause> pops up the "System
10415 Properties" dialog, etc. On Windows 10, no \"Windows\" key
10416 combinations are normally handed to applications. To enable Emacs to
10417 process \"Windows\" key combinations, use the function
10418 `w32-register-hot-key`.
10420 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
10421 Vw32_pass_lwindow_to_system = Qt;
10423 DEFVAR_LISP ("w32-pass-rwindow-to-system",
10424 Vw32_pass_rwindow_to_system,
10425 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
10427 When non-nil, the Start menu is opened by tapping the key.
10428 If you set this to nil, the right \"Windows\" key is processed by Emacs
10429 according to the value of `w32-rwindow-modifier', which see.
10431 Note that some combinations of the right \"Windows\" key with other
10432 keys are caught by Windows at low level. For example, <rwindow>-r
10433 pops up the Windows Run dialog, <rwindow>-<Pause> pops up the "System
10434 Properties" dialog, etc. On Windows 10, no \"Windows\" key
10435 combinations are normally handed to applications. To enable Emacs to
10436 process \"Windows\" key combinations, use the function
10437 `w32-register-hot-key`.
10439 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
10440 Vw32_pass_rwindow_to_system = Qt;
10442 DEFVAR_LISP ("w32-phantom-key-code",
10443 Vw32_phantom_key_code,
10444 doc: /* Virtual key code used to generate \"phantom\" key presses.
10445 Value is a number between 0 and 255.
10447 Phantom key presses are generated in order to stop the system from
10448 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
10449 `w32-pass-rwindow-to-system' is nil.
10451 This variable is only used on Windows 98 and ME. For other Windows
10452 versions, see the documentation of the `w32-register-hot-key`
10453 function. */);
10454 /* Although 255 is technically not a valid key code, it works and
10455 means that this hack won't interfere with any real key code. */
10456 XSETINT (Vw32_phantom_key_code, 255);
10458 DEFVAR_LISP ("w32-enable-num-lock",
10459 Vw32_enable_num_lock,
10460 doc: /* If non-nil, the Num Lock key acts normally.
10461 Set to nil to handle Num Lock as the `kp-numlock' key. */);
10462 Vw32_enable_num_lock = Qt;
10464 DEFVAR_LISP ("w32-enable-caps-lock",
10465 Vw32_enable_caps_lock,
10466 doc: /* If non-nil, the Caps Lock key acts normally.
10467 Set to nil to handle Caps Lock as the `capslock' key. */);
10468 Vw32_enable_caps_lock = Qt;
10470 DEFVAR_LISP ("w32-scroll-lock-modifier",
10471 Vw32_scroll_lock_modifier,
10472 doc: /* Modifier to use for the Scroll Lock ON state.
10473 The value can be hyper, super, meta, alt, control or shift for the
10474 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
10475 Any other value will cause the Scroll Lock key to be ignored by Emacs,
10476 and it will have the same effect as in other applications. */);
10477 Vw32_scroll_lock_modifier = Qnil;
10479 DEFVAR_LISP ("w32-lwindow-modifier",
10480 Vw32_lwindow_modifier,
10481 doc: /* Modifier to use for the left \"Windows\" key.
10482 The value can be hyper, super, meta, alt, control or shift for the
10483 respective modifier, or nil to appear as the `lwindow' key.
10484 Any other value will cause the key to be ignored.
10486 Also see the documentation of the `w32-register-hot-key` function. */);
10487 Vw32_lwindow_modifier = Qnil;
10489 DEFVAR_LISP ("w32-rwindow-modifier",
10490 Vw32_rwindow_modifier,
10491 doc: /* Modifier to use for the right \"Windows\" key.
10492 The value can be hyper, super, meta, alt, control or shift for the
10493 respective modifier, or nil to appear as the `rwindow' key.
10494 Any other value will cause the key to be ignored.
10496 Also see the documentation of the `w32-register-hot-key` function. */);
10497 Vw32_rwindow_modifier = Qnil;
10499 DEFVAR_LISP ("w32-apps-modifier",
10500 Vw32_apps_modifier,
10501 doc: /* Modifier to use for the \"Apps\" key.
10502 The value can be hyper, super, meta, alt, control or shift for the
10503 respective modifier, or nil to appear as the `apps' key.
10504 Any other value will cause the key to be ignored. */);
10505 Vw32_apps_modifier = Qnil;
10507 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
10508 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
10509 w32_enable_synthesized_fonts = 0;
10511 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
10512 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
10513 Vw32_enable_palette = Qt;
10515 DEFVAR_INT ("w32-mouse-button-tolerance",
10516 w32_mouse_button_tolerance,
10517 doc: /* Analogue of double click interval for faking middle mouse events.
10518 The value is the minimum time in milliseconds that must elapse between
10519 left and right button down events before they are considered distinct events.
10520 If both mouse buttons are depressed within this interval, a middle mouse
10521 button down event is generated instead. */);
10522 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
10524 DEFVAR_INT ("w32-mouse-move-interval",
10525 w32_mouse_move_interval,
10526 doc: /* Minimum interval between mouse move events.
10527 The value is the minimum time in milliseconds that must elapse between
10528 successive mouse move (or scroll bar drag) events before they are
10529 reported as lisp events. */);
10530 w32_mouse_move_interval = 0;
10532 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
10533 w32_pass_extra_mouse_buttons_to_system,
10534 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
10535 Recent versions of Windows support mice with up to five buttons.
10536 Since most applications don't support these extra buttons, most mouse
10537 drivers will allow you to map them to functions at the system level.
10538 If this variable is non-nil, Emacs will pass them on, allowing the
10539 system to handle them. */);
10540 w32_pass_extra_mouse_buttons_to_system = 0;
10542 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
10543 w32_pass_multimedia_buttons_to_system,
10544 doc: /* If non-nil, media buttons are passed to Windows.
10545 Some modern keyboards contain buttons for controlling media players, web
10546 browsers and other applications. Generally these buttons are handled on a
10547 system wide basis, but by setting this to nil they are made available
10548 to Emacs for binding. Depending on your keyboard, additional keys that
10549 may be available are:
10551 browser-back, browser-forward, browser-refresh, browser-stop,
10552 browser-search, browser-favorites, browser-home,
10553 mail, mail-reply, mail-forward, mail-send,
10554 app-1, app-2,
10555 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
10556 spell-check, correction-list, toggle-dictate-command,
10557 media-next, media-previous, media-stop, media-play-pause, media-select,
10558 media-play, media-pause, media-record, media-fast-forward, media-rewind,
10559 media-channel-up, media-channel-down,
10560 volume-mute, volume-up, volume-down,
10561 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
10562 bass-down, bass-boost, bass-up, treble-down, treble-up */);
10563 w32_pass_multimedia_buttons_to_system = 1;
10565 #if 0 /* TODO: Mouse cursor customization. */
10566 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
10567 doc: /* The shape of the pointer when over text.
10568 Changing the value does not affect existing frames
10569 unless you set the mouse color. */);
10570 Vx_pointer_shape = Qnil;
10572 Vx_nontext_pointer_shape = Qnil;
10574 Vx_mode_pointer_shape = Qnil;
10576 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
10577 doc: /* The shape of the pointer when Emacs is busy.
10578 This variable takes effect when you create a new frame
10579 or when you set the mouse color. */);
10580 Vx_hourglass_pointer_shape = Qnil;
10582 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
10583 Vx_sensitive_text_pointer_shape,
10584 doc: /* The shape of the pointer when over mouse-sensitive text.
10585 This variable takes effect when you create a new frame
10586 or when you set the mouse color. */);
10587 Vx_sensitive_text_pointer_shape = Qnil;
10589 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
10590 Vx_window_horizontal_drag_shape,
10591 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
10592 This variable takes effect when you create a new frame
10593 or when you set the mouse color. */);
10594 Vx_window_horizontal_drag_shape = Qnil;
10596 DEFVAR_LISP ("x-window-vertical-drag-cursor",
10597 Vx_window_vertical_drag_shape,
10598 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
10599 This variable takes effect when you create a new frame
10600 or when you set the mouse color. */);
10601 Vx_window_vertical_drag_shape = Qnil;
10602 #endif
10604 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
10605 doc: /* A string indicating the foreground color of the cursor box. */);
10606 Vx_cursor_fore_pixel = Qnil;
10608 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
10609 doc: /* Maximum size for tooltips.
10610 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
10611 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
10613 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
10614 doc: /* Non-nil if no window manager is in use.
10615 Emacs doesn't try to figure this out; this is always nil
10616 unless you set it to something else. */);
10617 /* We don't have any way to find this out, so set it to nil
10618 and maybe the user would like to set it to t. */
10619 Vx_no_window_manager = Qnil;
10621 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
10622 Vx_pixel_size_width_font_regexp,
10623 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
10625 Since Emacs gets width of a font matching with this regexp from
10626 PIXEL_SIZE field of the name, font finding mechanism gets faster for
10627 such a font. This is especially effective for such large fonts as
10628 Chinese, Japanese, and Korean. */);
10629 Vx_pixel_size_width_font_regexp = Qnil;
10631 DEFVAR_LISP ("w32-bdf-filename-alist",
10632 Vw32_bdf_filename_alist,
10633 doc: /* List of bdf fonts and their corresponding filenames. */);
10634 Vw32_bdf_filename_alist = Qnil;
10636 DEFVAR_BOOL ("w32-strict-fontnames",
10637 w32_strict_fontnames,
10638 doc: /* Non-nil means only use fonts that are exact matches for those requested.
10639 Default is nil, which allows old fontnames that are not XLFD compliant,
10640 and allows third-party CJK display to work by specifying false charset
10641 fields to trick Emacs into translating to Big5, SJIS etc.
10642 Setting this to t will prevent wrong fonts being selected when
10643 fontsets are automatically created. */);
10644 w32_strict_fontnames = 0;
10646 DEFVAR_BOOL ("w32-strict-painting",
10647 w32_strict_painting,
10648 doc: /* Non-nil means use strict rules for repainting frames.
10649 Set this to nil to get the old behavior for repainting; this should
10650 only be necessary if the default setting causes problems. */);
10651 w32_strict_painting = 1;
10653 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
10654 w32_use_fallback_wm_chars_method,
10655 doc: /* Non-nil means use old method of processing character keys.
10656 This is intended only for debugging of the new processing method.
10657 Default is nil.
10659 This variable has effect only on NT family of systems, not on Windows 9X. */);
10660 w32_use_fallback_wm_chars_method = 0;
10662 DEFVAR_BOOL ("w32-disable-new-uniscribe-apis",
10663 w32_disable_new_uniscribe_apis,
10664 doc: /* Non-nil means don't use new Uniscribe APIs.
10665 The new APIs are used to access OTF features supported by fonts.
10666 This is intended only for debugging of the new Uniscribe-related code.
10667 Default is nil.
10669 This variable has effect only on Windows Vista and later. */);
10670 w32_disable_new_uniscribe_apis = 0;
10672 DEFVAR_LISP ("w32-tooltip-extra-pixels",
10673 Vw32_tooltip_extra_pixels,
10674 doc: /* Number of pixels added after tooltip text.
10675 On Windows some fonts may cause the last character of a tooltip be
10676 truncated or wrapped around to the next line. Adding some extra space
10677 at the end of the toooltip works around this problem.
10679 This variable specifies the number of pixels that shall be added. The
10680 default value t means to add the width of one canonical character of the
10681 tip frame. */);
10682 Vw32_tooltip_extra_pixels = Qt;
10684 #if 0 /* TODO: Port to W32 */
10685 defsubr (&Sx_change_window_property);
10686 defsubr (&Sx_delete_window_property);
10687 defsubr (&Sx_window_property);
10688 #endif
10689 defsubr (&Sxw_display_color_p);
10690 defsubr (&Sx_display_grayscale_p);
10691 defsubr (&Sxw_color_defined_p);
10692 defsubr (&Sxw_color_values);
10693 defsubr (&Sx_server_max_request_size);
10694 defsubr (&Sx_server_vendor);
10695 defsubr (&Sx_server_version);
10696 defsubr (&Sx_display_pixel_width);
10697 defsubr (&Sx_display_pixel_height);
10698 defsubr (&Sx_display_mm_width);
10699 defsubr (&Sx_display_mm_height);
10700 defsubr (&Sx_display_screens);
10701 defsubr (&Sx_display_planes);
10702 defsubr (&Sx_display_color_cells);
10703 defsubr (&Sx_display_visual_class);
10704 defsubr (&Sx_display_backing_store);
10705 defsubr (&Sx_display_save_under);
10706 defsubr (&Sx_create_frame);
10707 defsubr (&Sx_open_connection);
10708 defsubr (&Sx_close_connection);
10709 defsubr (&Sx_display_list);
10710 defsubr (&Sw32_frame_geometry);
10711 defsubr (&Sw32_frame_edges);
10712 defsubr (&Sw32_frame_list_z_order);
10713 defsubr (&Sw32_frame_restack);
10714 defsubr (&Sw32_mouse_absolute_pixel_position);
10715 defsubr (&Sw32_set_mouse_absolute_pixel_position);
10716 defsubr (&Sx_synchronize);
10718 /* W32 specific functions */
10720 defsubr (&Sw32_define_rgb_color);
10721 defsubr (&Sw32_default_color_map);
10722 defsubr (&Sw32_display_monitor_attributes_list);
10723 defsubr (&Sw32_send_sys_command);
10724 defsubr (&Sw32_shell_execute);
10725 defsubr (&Sw32_register_hot_key);
10726 defsubr (&Sw32_unregister_hot_key);
10727 defsubr (&Sw32_registered_hot_keys);
10728 defsubr (&Sw32_reconstruct_hot_key);
10729 defsubr (&Sw32_toggle_lock_key);
10730 defsubr (&Sw32_window_exists_p);
10731 defsubr (&Sw32_battery_status);
10732 defsubr (&Sw32__menu_bar_in_use);
10733 #if defined WINDOWSNT && !defined HAVE_DBUS
10734 defsubr (&Sw32_notification_notify);
10735 defsubr (&Sw32_notification_close);
10736 #endif
10738 #ifdef WINDOWSNT
10739 defsubr (&Sfile_system_info);
10740 defsubr (&Sdefault_printer_name);
10741 #endif
10743 defsubr (&Sset_message_beep);
10744 defsubr (&Sx_show_tip);
10745 defsubr (&Sx_hide_tip);
10746 tip_timer = Qnil;
10747 staticpro (&tip_timer);
10748 tip_frame = Qnil;
10749 staticpro (&tip_frame);
10751 last_show_tip_args = Qnil;
10752 staticpro (&last_show_tip_args);
10754 defsubr (&Sx_file_dialog);
10755 #ifdef WINDOWSNT
10756 defsubr (&Ssystem_move_file_to_trash);
10757 #endif
10762 /* Crashing and reporting backtrace. */
10764 #ifndef CYGWIN
10765 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
10766 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
10767 #endif
10768 static DWORD except_code;
10769 static PVOID except_addr;
10771 #ifndef CYGWIN
10773 /* Stack overflow recovery. */
10775 /* MinGW headers don't declare this (should be in malloc.h). Also,
10776 the function is not present pre-W2K, so make the call through
10777 a function pointer. */
10778 typedef int (__cdecl *_resetstkoflw_proc) (void);
10779 static _resetstkoflw_proc resetstkoflw;
10781 /* Re-establish the guard page at stack limit. This is needed because
10782 when a stack overflow is detected, Windows removes the guard bit
10783 from the guard page, so if we don't re-establish that protection,
10784 the next stack overflow will cause a crash. */
10785 void
10786 w32_reset_stack_overflow_guard (void)
10788 if (resetstkoflw == NULL)
10789 resetstkoflw =
10790 (_resetstkoflw_proc)GetProcAddress (GetModuleHandle ("msvcrt.dll"),
10791 "_resetstkoflw");
10792 /* We ignore the return value. If _resetstkoflw fails, the next
10793 stack overflow will crash the program. */
10794 if (resetstkoflw != NULL)
10795 (void)resetstkoflw ();
10798 static void
10799 stack_overflow_handler (void)
10801 /* Hard GC error may lead to stack overflow caused by
10802 too nested calls to mark_object. No way to survive. */
10803 if (gc_in_progress)
10804 terminate_due_to_signal (SIGSEGV, 40);
10805 #ifdef _WIN64
10806 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
10807 __builtin_longjmp (return_to_command_loop, 1);
10808 #else
10809 sys_longjmp (return_to_command_loop, 1);
10810 #endif
10813 /* This handler records the exception code and the address where it
10814 was triggered so that this info could be included in the backtrace.
10815 Without that, the backtrace in some cases has no information
10816 whatsoever about the offending code, and looks as if the top-level
10817 exception handler in the MinGW startup code was the one that
10818 crashed. We also recover from stack overflow, by calling our stack
10819 overflow handler that jumps back to top level. */
10820 static LONG CALLBACK
10821 my_exception_handler (EXCEPTION_POINTERS * exception_data)
10823 except_code = exception_data->ExceptionRecord->ExceptionCode;
10824 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
10826 /* If this is a stack overflow exception, attempt to recover. */
10827 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
10828 && exception_data->ExceptionRecord->NumberParameters == 2
10829 /* We can only longjmp to top level from the main thread. */
10830 && GetCurrentThreadId () == dwMainThreadId)
10832 /* Call stack_overflow_handler (). */
10833 #ifdef _WIN64
10834 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
10835 #else
10836 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
10837 #endif
10838 /* Zero this out, so the stale address of the stack overflow
10839 exception we handled is not displayed in some future
10840 unrelated crash. */
10841 except_addr = 0;
10842 return EXCEPTION_CONTINUE_EXECUTION;
10845 if (prev_exception_handler)
10846 return prev_exception_handler (exception_data);
10847 return EXCEPTION_EXECUTE_HANDLER;
10849 #endif
10851 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
10852 PULONG);
10854 #define BACKTRACE_LIMIT_MAX 62
10856 static int
10857 w32_backtrace (void **buffer, int limit)
10859 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
10860 HMODULE hm_kernel32 = NULL;
10862 if (!s_pfn_CaptureStackBackTrace)
10864 hm_kernel32 = LoadLibrary ("Kernel32.dll");
10865 s_pfn_CaptureStackBackTrace =
10866 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
10867 "RtlCaptureStackBackTrace");
10869 if (s_pfn_CaptureStackBackTrace)
10870 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
10871 buffer, NULL);
10872 return 0;
10875 void
10876 emacs_abort (void)
10878 int button;
10879 button = MessageBox (NULL,
10880 "A fatal error has occurred!\n\n"
10881 "Would you like to attach a debugger?\n\n"
10882 "Select:\n"
10883 "YES -- to debug Emacs, or\n"
10884 "NO -- to abort Emacs and produce a backtrace\n"
10885 " (emacs_backtrace.txt in current directory)."
10886 #if __GNUC__
10887 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
10888 "\"continue\" inside GDB before clicking YES.)"
10889 #endif
10890 , "Emacs Abort Dialog",
10891 MB_ICONEXCLAMATION | MB_TASKMODAL
10892 | MB_SETFOREGROUND | MB_YESNO);
10893 switch (button)
10895 case IDYES:
10896 DebugBreak ();
10897 exit (2); /* tell the compiler we will never return */
10898 case IDNO:
10899 default:
10901 void *stack[BACKTRACE_LIMIT_MAX + 1];
10902 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
10904 if (i)
10906 int errfile_fd = -1;
10907 int j;
10908 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
10909 /* The type below should really be 'void *', but
10910 INT_BUFSIZE_BOUND cannot handle that without
10911 triggering compiler warnings (under certain
10912 pedantic warning switches), it wants an
10913 integer type. */
10914 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
10915 #ifdef CYGWIN
10916 int stderr_fd = 2;
10917 #else
10918 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
10919 int stderr_fd = -1;
10921 if (errout && errout != INVALID_HANDLE_VALUE)
10922 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
10923 #endif
10925 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
10926 but not on Windows 7. addr2line doesn't mind a missing
10927 "0x", but will be confused by an extra one. */
10928 if (except_addr)
10929 sprintf (buf, "\r\nException 0x%x at this address:\r\n%p\r\n",
10930 (unsigned int) except_code, except_addr);
10931 if (stderr_fd >= 0)
10933 if (except_addr)
10934 write (stderr_fd, buf, strlen (buf));
10935 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
10937 #ifdef CYGWIN
10938 #define _open open
10939 #endif
10940 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
10941 if (errfile_fd >= 0)
10943 lseek (errfile_fd, 0L, SEEK_END);
10944 if (except_addr)
10945 write (errfile_fd, buf, strlen (buf));
10946 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
10949 for (j = 0; j < i; j++)
10951 /* stack[] gives the return addresses, whereas we want
10952 the address of the call, so decrease each address
10953 by approximate size of 1 CALL instruction. */
10954 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
10955 if (stderr_fd >= 0)
10956 write (stderr_fd, buf, strlen (buf));
10957 if (errfile_fd >= 0)
10958 write (errfile_fd, buf, strlen (buf));
10960 if (i == BACKTRACE_LIMIT_MAX)
10962 if (stderr_fd >= 0)
10963 write (stderr_fd, "...\r\n", 5);
10964 if (errfile_fd >= 0)
10965 write (errfile_fd, "...\r\n", 5);
10967 if (errfile_fd >= 0)
10968 close (errfile_fd);
10970 abort ();
10971 break;
10978 /* Initialization. */
10981 globals_of_w32fns is used to initialize those global variables that
10982 must always be initialized on startup even when the global variable
10983 initialized is non zero (see the function main in emacs.c).
10984 globals_of_w32fns is called from syms_of_w32fns when the global
10985 variable initialized is 0 and directly from main when initialized
10986 is non zero.
10988 void
10989 globals_of_w32fns (void)
10991 HMODULE user32_lib = GetModuleHandle ("user32.dll");
10993 TrackMouseEvent not available in all versions of Windows, so must load
10994 it dynamically. Do it once, here, instead of every time it is used.
10996 track_mouse_event_fn = (TrackMouseEvent_Proc)
10997 GetProcAddress (user32_lib, "TrackMouseEvent");
10999 monitor_from_point_fn = (MonitorFromPoint_Proc)
11000 GetProcAddress (user32_lib, "MonitorFromPoint");
11001 get_monitor_info_fn = (GetMonitorInfo_Proc)
11002 GetProcAddress (user32_lib, "GetMonitorInfoA");
11003 monitor_from_window_fn = (MonitorFromWindow_Proc)
11004 GetProcAddress (user32_lib, "MonitorFromWindow");
11005 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
11006 GetProcAddress (user32_lib, "EnumDisplayMonitors");
11007 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
11008 GetProcAddress (user32_lib, "GetTitleBarInfo");
11011 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
11012 get_composition_string_fn = (ImmGetCompositionString_Proc)
11013 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
11014 get_ime_context_fn = (ImmGetContext_Proc)
11015 GetProcAddress (imm32_lib, "ImmGetContext");
11016 release_ime_context_fn = (ImmReleaseContext_Proc)
11017 GetProcAddress (imm32_lib, "ImmReleaseContext");
11018 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
11019 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
11022 except_code = 0;
11023 except_addr = 0;
11024 #ifndef CYGWIN
11025 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
11026 resetstkoflw = NULL;
11027 #endif
11029 DEFVAR_INT ("w32-ansi-code-page",
11030 w32_ansi_code_page,
11031 doc: /* The ANSI code page used by the system. */);
11032 w32_ansi_code_page = GetACP ();
11034 if (os_subtype == OS_NT)
11035 w32_unicode_gui = 1;
11036 else
11037 w32_unicode_gui = 0;
11039 after_deadkey = -1;
11041 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
11042 InitCommonControls ();
11044 syms_of_w32uniscribe ();
11047 #ifdef NTGUI_UNICODE
11049 Lisp_Object
11050 ntgui_encode_system (Lisp_Object str)
11052 Lisp_Object encoded;
11053 to_unicode (str, &encoded);
11054 return encoded;
11057 #endif /* NTGUI_UNICODE */