]> code.delx.au - gnu-emacs/blob - src/w32fns.c
Don't install keyboard hook when debugged on MS-Windows
[gnu-emacs] / src / w32fns.c
1 /* Graphical user interface functions for the Microsoft Windows API.
2
3 Copyright (C) 1989, 1992-2016 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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/>. */
19
20 /* Added by Kevin Gallo */
21
22 #include <config.h>
23 /* Override API version to get the latest functionality. */
24 #undef _WIN32_WINNT
25 #define _WIN32_WINNT 0x0600
26
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>
34
35 #include <c-ctype.h>
36
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"
45
46 #include "w32common.h"
47 #include "w32inevt.h"
48
49 #ifdef WINDOWSNT
50 #include <mbstring.h>
51 #endif /* WINDOWSNT */
52
53 #if CYGWIN
54 #include "cygw32.h"
55 #else
56 #include "w32.h"
57 #endif
58
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>
68
69 #include <dlgs.h>
70 #include <imm.h>
71 #include <windowsx.h>
72
73 #ifndef FOF_NO_CONNECTED_ELEMENTS
74 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
75 #endif
76
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 **);
81
82 #ifndef IDC_HAND
83 #define IDC_HAND MAKEINTRESOURCE(32649)
84 #endif
85
86 /* Prefix for system colors. */
87 #define SYSTEM_COLOR_PREFIX "System"
88 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
89
90 /* State variables for emulating a three button mouse. */
91 #define LMOUSE 1
92 #define MMOUSE 2
93 #define RMOUSE 4
94
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;
100
101 /* Window that is tracking the mouse. */
102 static HWND track_mouse_window;
103
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
121 {
122 DWORD cbSize;
123 RECT rcMonitor;
124 RECT rcWork;
125 DWORD dwFlags;
126 };
127
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
134 {
135 DWORD cbSize;
136 RECT rcTitleBar;
137 DWORD rgstate[C_CHILDREN_TITLEBAR+1];
138 } TITLEBAR_INFO, *PTITLEBAR_INFO;
139 #endif
140
141 #ifndef CCHDEVICENAME
142 #define CCHDEVICENAME 32
143 #endif
144 struct MONITOR_INFO_EX
145 {
146 DWORD cbSize;
147 RECT rcMonitor;
148 RECT rcWork;
149 DWORD dwFlags;
150 char szDevice[CCHDEVICENAME];
151 };
152
153 /* Reportedly, MSVC does not have this in its headers. */
154 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
155 DECLARE_HANDLE(HMONITOR);
156 #endif
157
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);
177
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;
188
189 extern AppendMenuW_Proc unicode_append_menu;
190
191 /* Flag to selectively ignore WM_IME_CHAR messages. */
192 static int ignore_ime_char = 0;
193
194 /* W95 mousewheel handler */
195 unsigned int msh_mousewheel = 0;
196
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;
205
206 #ifdef GLYPH_DEBUG
207 static ptrdiff_t image_cache_refcount;
208 static int dpyinfo_refcount;
209 #endif
210
211 static HWND w32_visible_system_caret_hwnd;
212
213 static int w32_unicode_gui;
214
215 /* From w32menu.c */
216 int menubar_in_use = 0;
217
218 /* From w32uniscribe.c */
219 extern void syms_of_w32uniscribe (void);
220 extern int uniscribe_available;
221
222 #ifdef WINDOWSNT
223 /* From w32inevt.c */
224 extern int faked_key;
225 #endif /* WINDOWSNT */
226
227 /* This gives us the page size and the size of the allocation unit on NT. */
228 SYSTEM_INFO sysinfo_cache;
229
230 /* This gives us version, build, and platform identification. */
231 OSVERSIONINFO osinfo_cache;
232
233 DWORD_PTR syspage_mask = 0;
234
235 /* The major and minor versions of NT. */
236 int w32_major_version;
237 int w32_minor_version;
238 int w32_build_number;
239
240 /* Distinguish between Windows NT and Windows 95. */
241 int os_subtype;
242
243 #ifdef HAVE_NTGUI
244 HINSTANCE hinst = NULL;
245 #endif
246
247 static unsigned int sound_type = 0xFFFFFFFF;
248 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
249
250 /* Special virtual key code for indicating "any" key. */
251 #define VK_ANY 0xFF
252
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
258
259 /* Keyboard hook state data. */
260 static struct
261 {
262 int hook_count; /* counter, if several windows are created */
263 HHOOK hook; /* hook handle */
264 HWND console; /* console window handle */
265
266 int lwindown; /* Left Windows key currently pressed (and hooked) */
267 int rwindown; /* Right Windows key currently pressed (and hooked) */
268 int winsdown; /* Number of handled keys currently pressed */
269 int send_win_up; /* Pass through the keyup for this Windows key press? */
270 int suppress_lone; /* Suppress simulated Windows keydown-keyup for this press? */
271 int winseen; /* Windows keys seen during this press? */
272
273 char alt_hooked[256]; /* hook Alt+[this key]? */
274 char lwin_hooked[256]; /* hook left Win+[this key]? */
275 char rwin_hooked[256]; /* hook right Win+[this key]? */
276 } kbdhook;
277 typedef HWND (WINAPI *GetConsoleWindow_Proc) (void);
278
279 typedef BOOL (WINAPI *IsDebuggerPresent_Proc) (void);
280
281 /* stdin, from w32console.c */
282 extern HANDLE keyboard_handle;
283
284 /* Let the user specify a display with a frame.
285 nil stands for the selected frame--or, if that is not a w32 frame,
286 the first display on the list. */
287
288 struct w32_display_info *
289 check_x_display_info (Lisp_Object object)
290 {
291 if (NILP (object))
292 {
293 struct frame *sf = XFRAME (selected_frame);
294
295 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
296 return FRAME_DISPLAY_INFO (sf);
297 else
298 return &one_w32_display_info;
299 }
300 else if (TERMINALP (object))
301 {
302 struct terminal *t = decode_live_terminal (object);
303
304 if (t->type != output_w32)
305 error ("Terminal %d is not a W32 display", t->id);
306
307 return t->display_info.w32;
308 }
309 else if (STRINGP (object))
310 return x_display_info_for_name (object);
311 else
312 {
313 struct frame *f;
314
315 CHECK_LIVE_FRAME (object);
316 f = XFRAME (object);
317 if (! FRAME_W32_P (f))
318 error ("Non-W32 frame used");
319 return FRAME_DISPLAY_INFO (f);
320 }
321 }
322 \f
323 /* Return the Emacs frame-object corresponding to an w32 window.
324 It could be the frame's main window or an icon window. */
325
326 struct frame *
327 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
328 {
329 Lisp_Object tail, frame;
330 struct frame *f;
331
332 FOR_EACH_FRAME (tail, frame)
333 {
334 f = XFRAME (frame);
335 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
336 continue;
337
338 if (FRAME_W32_WINDOW (f) == wdesc)
339 return f;
340 }
341 return 0;
342 }
343
344 \f
345 static Lisp_Object unwind_create_frame (Lisp_Object);
346 static void my_create_window (struct frame *);
347 static void my_create_tip_window (struct frame *);
348
349 /* TODO: Native Input Method support; see x_create_im. */
350 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
351 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
352 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
353 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
354 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
355 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
356 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
357 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
358 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
359 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
360 \f
361
362 /* Store the screen positions of frame F into XPTR and YPTR.
363 These are the positions of the containing window manager window,
364 not Emacs's own window. */
365
366 void
367 x_real_positions (struct frame *f, int *xptr, int *yptr)
368 {
369 POINT pt;
370 RECT rect;
371
372 /* Get the bounds of the WM window. */
373 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
374
375 pt.x = 0;
376 pt.y = 0;
377
378 /* Convert (0, 0) in the client area to screen co-ordinates. */
379 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
380
381 *xptr = rect.left;
382 *yptr = rect.top;
383 }
384
385 /* Returns the window rectangle appropriate for the given fullscreen mode.
386 The normal rect parameter was the window's rectangle prior to entering
387 fullscreen mode. If multiple monitor support is available, the nearest
388 monitor to the window is chosen. */
389
390 void
391 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
392 {
393 struct MONITOR_INFO mi = { sizeof(mi) };
394 if (monitor_from_window_fn && get_monitor_info_fn)
395 {
396 HMONITOR monitor =
397 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
398 get_monitor_info_fn (monitor, &mi);
399 }
400 else
401 {
402 mi.rcMonitor.left = 0;
403 mi.rcMonitor.top = 0;
404 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
405 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
406 mi.rcWork.left = 0;
407 mi.rcWork.top = 0;
408 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
409 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
410 }
411
412 switch (fsmode)
413 {
414 case FULLSCREEN_BOTH:
415 rect->left = mi.rcMonitor.left;
416 rect->top = mi.rcMonitor.top;
417 rect->right = mi.rcMonitor.right;
418 rect->bottom = mi.rcMonitor.bottom;
419 break;
420 case FULLSCREEN_WIDTH:
421 rect->left = mi.rcWork.left;
422 rect->top = normal.top;
423 rect->right = mi.rcWork.right;
424 rect->bottom = normal.bottom;
425 break;
426 case FULLSCREEN_HEIGHT:
427 rect->left = normal.left;
428 rect->top = mi.rcWork.top;
429 rect->right = normal.right;
430 rect->bottom = mi.rcWork.bottom;
431 break;
432 default:
433 *rect = normal;
434 break;
435 }
436 }
437
438 \f
439
440 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
441 Sw32_define_rgb_color, 4, 4, 0,
442 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
443 This adds or updates a named color to `w32-color-map', making it
444 available for use. The original entry's RGB ref is returned, or nil
445 if the entry is new. */)
446 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
447 {
448 Lisp_Object rgb;
449 Lisp_Object oldrgb = Qnil;
450 Lisp_Object entry;
451
452 CHECK_NUMBER (red);
453 CHECK_NUMBER (green);
454 CHECK_NUMBER (blue);
455 CHECK_STRING (name);
456
457 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
458
459 block_input ();
460
461 /* replace existing entry in w32-color-map or add new entry. */
462 entry = Fassoc (name, Vw32_color_map);
463 if (NILP (entry))
464 {
465 entry = Fcons (name, rgb);
466 Vw32_color_map = Fcons (entry, Vw32_color_map);
467 }
468 else
469 {
470 oldrgb = Fcdr (entry);
471 Fsetcdr (entry, rgb);
472 }
473
474 unblock_input ();
475
476 return (oldrgb);
477 }
478
479 /* The default colors for the w32 color map */
480 typedef struct colormap_t
481 {
482 const char *name;
483 COLORREF colorref;
484 } colormap_t;
485
486 colormap_t w32_color_map[] =
487 {
488 {"snow" , PALETTERGB (255,250,250)},
489 {"ghost white" , PALETTERGB (248,248,255)},
490 {"GhostWhite" , PALETTERGB (248,248,255)},
491 {"white smoke" , PALETTERGB (245,245,245)},
492 {"WhiteSmoke" , PALETTERGB (245,245,245)},
493 {"gainsboro" , PALETTERGB (220,220,220)},
494 {"floral white" , PALETTERGB (255,250,240)},
495 {"FloralWhite" , PALETTERGB (255,250,240)},
496 {"old lace" , PALETTERGB (253,245,230)},
497 {"OldLace" , PALETTERGB (253,245,230)},
498 {"linen" , PALETTERGB (250,240,230)},
499 {"antique white" , PALETTERGB (250,235,215)},
500 {"AntiqueWhite" , PALETTERGB (250,235,215)},
501 {"papaya whip" , PALETTERGB (255,239,213)},
502 {"PapayaWhip" , PALETTERGB (255,239,213)},
503 {"blanched almond" , PALETTERGB (255,235,205)},
504 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
505 {"bisque" , PALETTERGB (255,228,196)},
506 {"peach puff" , PALETTERGB (255,218,185)},
507 {"PeachPuff" , PALETTERGB (255,218,185)},
508 {"navajo white" , PALETTERGB (255,222,173)},
509 {"NavajoWhite" , PALETTERGB (255,222,173)},
510 {"moccasin" , PALETTERGB (255,228,181)},
511 {"cornsilk" , PALETTERGB (255,248,220)},
512 {"ivory" , PALETTERGB (255,255,240)},
513 {"lemon chiffon" , PALETTERGB (255,250,205)},
514 {"LemonChiffon" , PALETTERGB (255,250,205)},
515 {"seashell" , PALETTERGB (255,245,238)},
516 {"honeydew" , PALETTERGB (240,255,240)},
517 {"mint cream" , PALETTERGB (245,255,250)},
518 {"MintCream" , PALETTERGB (245,255,250)},
519 {"azure" , PALETTERGB (240,255,255)},
520 {"alice blue" , PALETTERGB (240,248,255)},
521 {"AliceBlue" , PALETTERGB (240,248,255)},
522 {"lavender" , PALETTERGB (230,230,250)},
523 {"lavender blush" , PALETTERGB (255,240,245)},
524 {"LavenderBlush" , PALETTERGB (255,240,245)},
525 {"misty rose" , PALETTERGB (255,228,225)},
526 {"MistyRose" , PALETTERGB (255,228,225)},
527 {"white" , PALETTERGB (255,255,255)},
528 {"black" , PALETTERGB ( 0, 0, 0)},
529 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
530 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
531 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
532 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
533 {"dim gray" , PALETTERGB (105,105,105)},
534 {"DimGray" , PALETTERGB (105,105,105)},
535 {"dim grey" , PALETTERGB (105,105,105)},
536 {"DimGrey" , PALETTERGB (105,105,105)},
537 {"slate gray" , PALETTERGB (112,128,144)},
538 {"SlateGray" , PALETTERGB (112,128,144)},
539 {"slate grey" , PALETTERGB (112,128,144)},
540 {"SlateGrey" , PALETTERGB (112,128,144)},
541 {"light slate gray" , PALETTERGB (119,136,153)},
542 {"LightSlateGray" , PALETTERGB (119,136,153)},
543 {"light slate grey" , PALETTERGB (119,136,153)},
544 {"LightSlateGrey" , PALETTERGB (119,136,153)},
545 {"gray" , PALETTERGB (190,190,190)},
546 {"grey" , PALETTERGB (190,190,190)},
547 {"light grey" , PALETTERGB (211,211,211)},
548 {"LightGrey" , PALETTERGB (211,211,211)},
549 {"light gray" , PALETTERGB (211,211,211)},
550 {"LightGray" , PALETTERGB (211,211,211)},
551 {"midnight blue" , PALETTERGB ( 25, 25,112)},
552 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
553 {"navy" , PALETTERGB ( 0, 0,128)},
554 {"navy blue" , PALETTERGB ( 0, 0,128)},
555 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
556 {"cornflower blue" , PALETTERGB (100,149,237)},
557 {"CornflowerBlue" , PALETTERGB (100,149,237)},
558 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
559 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
560 {"slate blue" , PALETTERGB (106, 90,205)},
561 {"SlateBlue" , PALETTERGB (106, 90,205)},
562 {"medium slate blue" , PALETTERGB (123,104,238)},
563 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
564 {"light slate blue" , PALETTERGB (132,112,255)},
565 {"LightSlateBlue" , PALETTERGB (132,112,255)},
566 {"medium blue" , PALETTERGB ( 0, 0,205)},
567 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
568 {"royal blue" , PALETTERGB ( 65,105,225)},
569 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
570 {"blue" , PALETTERGB ( 0, 0,255)},
571 {"dodger blue" , PALETTERGB ( 30,144,255)},
572 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
573 {"deep sky blue" , PALETTERGB ( 0,191,255)},
574 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
575 {"sky blue" , PALETTERGB (135,206,235)},
576 {"SkyBlue" , PALETTERGB (135,206,235)},
577 {"light sky blue" , PALETTERGB (135,206,250)},
578 {"LightSkyBlue" , PALETTERGB (135,206,250)},
579 {"steel blue" , PALETTERGB ( 70,130,180)},
580 {"SteelBlue" , PALETTERGB ( 70,130,180)},
581 {"light steel blue" , PALETTERGB (176,196,222)},
582 {"LightSteelBlue" , PALETTERGB (176,196,222)},
583 {"light blue" , PALETTERGB (173,216,230)},
584 {"LightBlue" , PALETTERGB (173,216,230)},
585 {"powder blue" , PALETTERGB (176,224,230)},
586 {"PowderBlue" , PALETTERGB (176,224,230)},
587 {"pale turquoise" , PALETTERGB (175,238,238)},
588 {"PaleTurquoise" , PALETTERGB (175,238,238)},
589 {"dark turquoise" , PALETTERGB ( 0,206,209)},
590 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
591 {"medium turquoise" , PALETTERGB ( 72,209,204)},
592 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
593 {"turquoise" , PALETTERGB ( 64,224,208)},
594 {"cyan" , PALETTERGB ( 0,255,255)},
595 {"light cyan" , PALETTERGB (224,255,255)},
596 {"LightCyan" , PALETTERGB (224,255,255)},
597 {"cadet blue" , PALETTERGB ( 95,158,160)},
598 {"CadetBlue" , PALETTERGB ( 95,158,160)},
599 {"medium aquamarine" , PALETTERGB (102,205,170)},
600 {"MediumAquamarine" , PALETTERGB (102,205,170)},
601 {"aquamarine" , PALETTERGB (127,255,212)},
602 {"dark green" , PALETTERGB ( 0,100, 0)},
603 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
604 {"dark olive green" , PALETTERGB ( 85,107, 47)},
605 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
606 {"dark sea green" , PALETTERGB (143,188,143)},
607 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
608 {"sea green" , PALETTERGB ( 46,139, 87)},
609 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
610 {"medium sea green" , PALETTERGB ( 60,179,113)},
611 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
612 {"light sea green" , PALETTERGB ( 32,178,170)},
613 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
614 {"pale green" , PALETTERGB (152,251,152)},
615 {"PaleGreen" , PALETTERGB (152,251,152)},
616 {"spring green" , PALETTERGB ( 0,255,127)},
617 {"SpringGreen" , PALETTERGB ( 0,255,127)},
618 {"lawn green" , PALETTERGB (124,252, 0)},
619 {"LawnGreen" , PALETTERGB (124,252, 0)},
620 {"green" , PALETTERGB ( 0,255, 0)},
621 {"chartreuse" , PALETTERGB (127,255, 0)},
622 {"medium spring green" , PALETTERGB ( 0,250,154)},
623 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
624 {"green yellow" , PALETTERGB (173,255, 47)},
625 {"GreenYellow" , PALETTERGB (173,255, 47)},
626 {"lime green" , PALETTERGB ( 50,205, 50)},
627 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
628 {"yellow green" , PALETTERGB (154,205, 50)},
629 {"YellowGreen" , PALETTERGB (154,205, 50)},
630 {"forest green" , PALETTERGB ( 34,139, 34)},
631 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
632 {"olive drab" , PALETTERGB (107,142, 35)},
633 {"OliveDrab" , PALETTERGB (107,142, 35)},
634 {"dark khaki" , PALETTERGB (189,183,107)},
635 {"DarkKhaki" , PALETTERGB (189,183,107)},
636 {"khaki" , PALETTERGB (240,230,140)},
637 {"pale goldenrod" , PALETTERGB (238,232,170)},
638 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
639 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
640 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
641 {"light yellow" , PALETTERGB (255,255,224)},
642 {"LightYellow" , PALETTERGB (255,255,224)},
643 {"yellow" , PALETTERGB (255,255, 0)},
644 {"gold" , PALETTERGB (255,215, 0)},
645 {"light goldenrod" , PALETTERGB (238,221,130)},
646 {"LightGoldenrod" , PALETTERGB (238,221,130)},
647 {"goldenrod" , PALETTERGB (218,165, 32)},
648 {"dark goldenrod" , PALETTERGB (184,134, 11)},
649 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
650 {"rosy brown" , PALETTERGB (188,143,143)},
651 {"RosyBrown" , PALETTERGB (188,143,143)},
652 {"indian red" , PALETTERGB (205, 92, 92)},
653 {"IndianRed" , PALETTERGB (205, 92, 92)},
654 {"saddle brown" , PALETTERGB (139, 69, 19)},
655 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
656 {"sienna" , PALETTERGB (160, 82, 45)},
657 {"peru" , PALETTERGB (205,133, 63)},
658 {"burlywood" , PALETTERGB (222,184,135)},
659 {"beige" , PALETTERGB (245,245,220)},
660 {"wheat" , PALETTERGB (245,222,179)},
661 {"sandy brown" , PALETTERGB (244,164, 96)},
662 {"SandyBrown" , PALETTERGB (244,164, 96)},
663 {"tan" , PALETTERGB (210,180,140)},
664 {"chocolate" , PALETTERGB (210,105, 30)},
665 {"firebrick" , PALETTERGB (178,34, 34)},
666 {"brown" , PALETTERGB (165,42, 42)},
667 {"dark salmon" , PALETTERGB (233,150,122)},
668 {"DarkSalmon" , PALETTERGB (233,150,122)},
669 {"salmon" , PALETTERGB (250,128,114)},
670 {"light salmon" , PALETTERGB (255,160,122)},
671 {"LightSalmon" , PALETTERGB (255,160,122)},
672 {"orange" , PALETTERGB (255,165, 0)},
673 {"dark orange" , PALETTERGB (255,140, 0)},
674 {"DarkOrange" , PALETTERGB (255,140, 0)},
675 {"coral" , PALETTERGB (255,127, 80)},
676 {"light coral" , PALETTERGB (240,128,128)},
677 {"LightCoral" , PALETTERGB (240,128,128)},
678 {"tomato" , PALETTERGB (255, 99, 71)},
679 {"orange red" , PALETTERGB (255, 69, 0)},
680 {"OrangeRed" , PALETTERGB (255, 69, 0)},
681 {"red" , PALETTERGB (255, 0, 0)},
682 {"hot pink" , PALETTERGB (255,105,180)},
683 {"HotPink" , PALETTERGB (255,105,180)},
684 {"deep pink" , PALETTERGB (255, 20,147)},
685 {"DeepPink" , PALETTERGB (255, 20,147)},
686 {"pink" , PALETTERGB (255,192,203)},
687 {"light pink" , PALETTERGB (255,182,193)},
688 {"LightPink" , PALETTERGB (255,182,193)},
689 {"pale violet red" , PALETTERGB (219,112,147)},
690 {"PaleVioletRed" , PALETTERGB (219,112,147)},
691 {"maroon" , PALETTERGB (176, 48, 96)},
692 {"medium violet red" , PALETTERGB (199, 21,133)},
693 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
694 {"violet red" , PALETTERGB (208, 32,144)},
695 {"VioletRed" , PALETTERGB (208, 32,144)},
696 {"magenta" , PALETTERGB (255, 0,255)},
697 {"violet" , PALETTERGB (238,130,238)},
698 {"plum" , PALETTERGB (221,160,221)},
699 {"orchid" , PALETTERGB (218,112,214)},
700 {"medium orchid" , PALETTERGB (186, 85,211)},
701 {"MediumOrchid" , PALETTERGB (186, 85,211)},
702 {"dark orchid" , PALETTERGB (153, 50,204)},
703 {"DarkOrchid" , PALETTERGB (153, 50,204)},
704 {"dark violet" , PALETTERGB (148, 0,211)},
705 {"DarkViolet" , PALETTERGB (148, 0,211)},
706 {"blue violet" , PALETTERGB (138, 43,226)},
707 {"BlueViolet" , PALETTERGB (138, 43,226)},
708 {"purple" , PALETTERGB (160, 32,240)},
709 {"medium purple" , PALETTERGB (147,112,219)},
710 {"MediumPurple" , PALETTERGB (147,112,219)},
711 {"thistle" , PALETTERGB (216,191,216)},
712 {"gray0" , PALETTERGB ( 0, 0, 0)},
713 {"grey0" , PALETTERGB ( 0, 0, 0)},
714 {"dark grey" , PALETTERGB (169,169,169)},
715 {"DarkGrey" , PALETTERGB (169,169,169)},
716 {"dark gray" , PALETTERGB (169,169,169)},
717 {"DarkGray" , PALETTERGB (169,169,169)},
718 {"dark blue" , PALETTERGB ( 0, 0,139)},
719 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
720 {"dark cyan" , PALETTERGB ( 0,139,139)},
721 {"DarkCyan" , PALETTERGB ( 0,139,139)},
722 {"dark magenta" , PALETTERGB (139, 0,139)},
723 {"DarkMagenta" , PALETTERGB (139, 0,139)},
724 {"dark red" , PALETTERGB (139, 0, 0)},
725 {"DarkRed" , PALETTERGB (139, 0, 0)},
726 {"light green" , PALETTERGB (144,238,144)},
727 {"LightGreen" , PALETTERGB (144,238,144)},
728 };
729
730 static Lisp_Object
731 w32_default_color_map (void)
732 {
733 int i;
734 colormap_t *pc = w32_color_map;
735 Lisp_Object cmap;
736
737 block_input ();
738
739 cmap = Qnil;
740
741 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
742 cmap = Fcons (Fcons (build_string (pc->name),
743 make_number (pc->colorref)),
744 cmap);
745
746 unblock_input ();
747
748 return (cmap);
749 }
750
751 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
752 0, 0, 0, doc: /* Return the default color map. */)
753 (void)
754 {
755 return w32_default_color_map ();
756 }
757
758 static Lisp_Object
759 w32_color_map_lookup (const char *colorname)
760 {
761 Lisp_Object tail, ret = Qnil;
762
763 block_input ();
764
765 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
766 {
767 register Lisp_Object elt, tem;
768
769 elt = XCAR (tail);
770 if (!CONSP (elt)) continue;
771
772 tem = XCAR (elt);
773
774 if (lstrcmpi (SSDATA (tem), colorname) == 0)
775 {
776 ret = Fcdr (elt);
777 break;
778 }
779
780 QUIT;
781 }
782
783 unblock_input ();
784
785 return ret;
786 }
787
788
789 static void
790 add_system_logical_colors_to_map (Lisp_Object *system_colors)
791 {
792 HKEY colors_key;
793
794 /* Other registry operations are done with input blocked. */
795 block_input ();
796
797 /* Look for "Control Panel/Colors" under User and Machine registry
798 settings. */
799 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
800 KEY_READ, &colors_key) == ERROR_SUCCESS
801 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
802 KEY_READ, &colors_key) == ERROR_SUCCESS)
803 {
804 /* List all keys. */
805 char color_buffer[64];
806 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
807 int index = 0;
808 DWORD name_size, color_size;
809 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
810
811 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
812 color_size = sizeof (color_buffer);
813
814 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
815
816 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
817 NULL, NULL, (LPBYTE)color_buffer, &color_size)
818 == ERROR_SUCCESS)
819 {
820 unsigned r, g, b;
821 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
822 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
823 make_number (RGB (r, g, b))),
824 *system_colors);
825
826 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
827 color_size = sizeof (color_buffer);
828 index++;
829 }
830 RegCloseKey (colors_key);
831 }
832
833 unblock_input ();
834 }
835
836
837 static Lisp_Object
838 x_to_w32_color (const char * colorname)
839 {
840 register Lisp_Object ret = Qnil;
841
842 block_input ();
843
844 if (colorname[0] == '#')
845 {
846 /* Could be an old-style RGB Device specification. */
847 int size = strlen (colorname + 1);
848 char *color = alloca (size + 1);
849
850 strcpy (color, colorname + 1);
851 if (size == 3 || size == 6 || size == 9 || size == 12)
852 {
853 UINT colorval;
854 int i, pos;
855 pos = 0;
856 size /= 3;
857 colorval = 0;
858
859 for (i = 0; i < 3; i++)
860 {
861 char *end;
862 char t;
863 unsigned long value;
864
865 /* The check for 'x' in the following conditional takes into
866 account the fact that strtol allows a "0x" in front of
867 our numbers, and we don't. */
868 if (!isxdigit (color[0]) || color[1] == 'x')
869 break;
870 t = color[size];
871 color[size] = '\0';
872 value = strtoul (color, &end, 16);
873 color[size] = t;
874 if (errno == ERANGE || end - color != size)
875 break;
876 switch (size)
877 {
878 case 1:
879 value = value * 0x10;
880 break;
881 case 2:
882 break;
883 case 3:
884 value /= 0x10;
885 break;
886 case 4:
887 value /= 0x100;
888 break;
889 }
890 colorval |= (value << pos);
891 pos += 0x8;
892 if (i == 2)
893 {
894 unblock_input ();
895 XSETINT (ret, colorval);
896 return ret;
897 }
898 color = end;
899 }
900 }
901 }
902 else if (strnicmp (colorname, "rgb:", 4) == 0)
903 {
904 const char *color;
905 UINT colorval;
906 int i, pos;
907 pos = 0;
908
909 colorval = 0;
910 color = colorname + 4;
911 for (i = 0; i < 3; i++)
912 {
913 char *end;
914 unsigned long value;
915
916 /* The check for 'x' in the following conditional takes into
917 account the fact that strtol allows a "0x" in front of
918 our numbers, and we don't. */
919 if (!isxdigit (color[0]) || color[1] == 'x')
920 break;
921 value = strtoul (color, &end, 16);
922 if (errno == ERANGE)
923 break;
924 switch (end - color)
925 {
926 case 1:
927 value = value * 0x10 + value;
928 break;
929 case 2:
930 break;
931 case 3:
932 value /= 0x10;
933 break;
934 case 4:
935 value /= 0x100;
936 break;
937 default:
938 value = ULONG_MAX;
939 }
940 if (value == ULONG_MAX)
941 break;
942 colorval |= (value << pos);
943 pos += 0x8;
944 if (i == 2)
945 {
946 if (*end != '\0')
947 break;
948 unblock_input ();
949 XSETINT (ret, colorval);
950 return ret;
951 }
952 if (*end != '/')
953 break;
954 color = end + 1;
955 }
956 }
957 else if (strnicmp (colorname, "rgbi:", 5) == 0)
958 {
959 /* This is an RGB Intensity specification. */
960 const char *color;
961 UINT colorval;
962 int i, pos;
963 pos = 0;
964
965 colorval = 0;
966 color = colorname + 5;
967 for (i = 0; i < 3; i++)
968 {
969 char *end;
970 double value;
971 UINT val;
972
973 value = strtod (color, &end);
974 if (errno == ERANGE)
975 break;
976 if (value < 0.0 || value > 1.0)
977 break;
978 val = (UINT)(0x100 * value);
979 /* We used 0x100 instead of 0xFF to give a continuous
980 range between 0.0 and 1.0 inclusive. The next statement
981 fixes the 1.0 case. */
982 if (val == 0x100)
983 val = 0xFF;
984 colorval |= (val << pos);
985 pos += 0x8;
986 if (i == 2)
987 {
988 if (*end != '\0')
989 break;
990 unblock_input ();
991 XSETINT (ret, colorval);
992 return ret;
993 }
994 if (*end != '/')
995 break;
996 color = end + 1;
997 }
998 }
999 /* I am not going to attempt to handle any of the CIE color schemes
1000 or TekHVC, since I don't know the algorithms for conversion to
1001 RGB. */
1002
1003 /* If we fail to lookup the color name in w32_color_map, then check the
1004 colorname to see if it can be crudely approximated: If the X color
1005 ends in a number (e.g., "darkseagreen2"), strip the number and
1006 return the result of looking up the base color name. */
1007 ret = w32_color_map_lookup (colorname);
1008 if (NILP (ret))
1009 {
1010 int len = strlen (colorname);
1011
1012 if (isdigit (colorname[len - 1]))
1013 {
1014 char *ptr, *approx = alloca (len + 1);
1015
1016 strcpy (approx, colorname);
1017 ptr = &approx[len - 1];
1018 while (ptr > approx && isdigit (*ptr))
1019 *ptr-- = '\0';
1020
1021 ret = w32_color_map_lookup (approx);
1022 }
1023 }
1024
1025 unblock_input ();
1026 return ret;
1027 }
1028
1029 void
1030 w32_regenerate_palette (struct frame *f)
1031 {
1032 struct w32_palette_entry * list;
1033 LOGPALETTE * log_palette;
1034 HPALETTE new_palette;
1035 int i;
1036
1037 /* don't bother trying to create palette if not supported */
1038 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1039 return;
1040
1041 log_palette = (LOGPALETTE *)
1042 alloca (sizeof (LOGPALETTE) +
1043 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1044 log_palette->palVersion = 0x300;
1045 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1046
1047 list = FRAME_DISPLAY_INFO (f)->color_list;
1048 for (i = 0;
1049 i < FRAME_DISPLAY_INFO (f)->num_colors;
1050 i++, list = list->next)
1051 log_palette->palPalEntry[i] = list->entry;
1052
1053 new_palette = CreatePalette (log_palette);
1054
1055 enter_crit ();
1056
1057 if (FRAME_DISPLAY_INFO (f)->palette)
1058 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1059 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1060
1061 /* Realize display palette and garbage all frames. */
1062 release_frame_dc (f, get_frame_dc (f));
1063
1064 leave_crit ();
1065 }
1066
1067 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1068 #define SET_W32_COLOR(pe, color) \
1069 do \
1070 { \
1071 pe.peRed = GetRValue (color); \
1072 pe.peGreen = GetGValue (color); \
1073 pe.peBlue = GetBValue (color); \
1074 pe.peFlags = 0; \
1075 } while (0)
1076
1077 #if 0
1078 /* Keep these around in case we ever want to track color usage. */
1079 void
1080 w32_map_color (struct frame *f, COLORREF color)
1081 {
1082 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1083
1084 if (NILP (Vw32_enable_palette))
1085 return;
1086
1087 /* check if color is already mapped */
1088 while (list)
1089 {
1090 if (W32_COLOR (list->entry) == color)
1091 {
1092 ++list->refcount;
1093 return;
1094 }
1095 list = list->next;
1096 }
1097
1098 /* not already mapped, so add to list and recreate Windows palette */
1099 list = xmalloc (sizeof (struct w32_palette_entry));
1100 SET_W32_COLOR (list->entry, color);
1101 list->refcount = 1;
1102 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1103 FRAME_DISPLAY_INFO (f)->color_list = list;
1104 FRAME_DISPLAY_INFO (f)->num_colors++;
1105
1106 /* set flag that palette must be regenerated */
1107 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1108 }
1109
1110 void
1111 w32_unmap_color (struct frame *f, COLORREF color)
1112 {
1113 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1114 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1115
1116 if (NILP (Vw32_enable_palette))
1117 return;
1118
1119 /* check if color is already mapped */
1120 while (list)
1121 {
1122 if (W32_COLOR (list->entry) == color)
1123 {
1124 if (--list->refcount == 0)
1125 {
1126 *prev = list->next;
1127 xfree (list);
1128 FRAME_DISPLAY_INFO (f)->num_colors--;
1129 break;
1130 }
1131 else
1132 return;
1133 }
1134 prev = &list->next;
1135 list = list->next;
1136 }
1137
1138 /* set flag that palette must be regenerated */
1139 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1140 }
1141 #endif
1142
1143
1144 /* Gamma-correct COLOR on frame F. */
1145
1146 void
1147 gamma_correct (struct frame *f, COLORREF *color)
1148 {
1149 if (f->gamma)
1150 {
1151 *color = PALETTERGB (
1152 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1153 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1154 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1155 }
1156 }
1157
1158
1159 /* Decide if color named COLOR is valid for the display associated with
1160 the selected frame; if so, return the rgb values in COLOR_DEF.
1161 If ALLOC is nonzero, allocate a new colormap cell. */
1162
1163 int
1164 w32_defined_color (struct frame *f, const char *color, XColor *color_def,
1165 bool alloc_p)
1166 {
1167 register Lisp_Object tem;
1168 COLORREF w32_color_ref;
1169
1170 tem = x_to_w32_color (color);
1171
1172 if (!NILP (tem))
1173 {
1174 if (f)
1175 {
1176 /* Apply gamma correction. */
1177 w32_color_ref = XUINT (tem);
1178 gamma_correct (f, &w32_color_ref);
1179 XSETINT (tem, w32_color_ref);
1180 }
1181
1182 /* Map this color to the palette if it is enabled. */
1183 if (!NILP (Vw32_enable_palette))
1184 {
1185 struct w32_palette_entry * entry =
1186 one_w32_display_info.color_list;
1187 struct w32_palette_entry ** prev =
1188 &one_w32_display_info.color_list;
1189
1190 /* check if color is already mapped */
1191 while (entry)
1192 {
1193 if (W32_COLOR (entry->entry) == XUINT (tem))
1194 break;
1195 prev = &entry->next;
1196 entry = entry->next;
1197 }
1198
1199 if (entry == NULL && alloc_p)
1200 {
1201 /* not already mapped, so add to list */
1202 entry = xmalloc (sizeof (struct w32_palette_entry));
1203 SET_W32_COLOR (entry->entry, XUINT (tem));
1204 entry->next = NULL;
1205 *prev = entry;
1206 one_w32_display_info.num_colors++;
1207
1208 /* set flag that palette must be regenerated */
1209 one_w32_display_info.regen_palette = TRUE;
1210 }
1211 }
1212 /* Ensure COLORREF value is snapped to nearest color in (default)
1213 palette by simulating the PALETTERGB macro. This works whether
1214 or not the display device has a palette. */
1215 w32_color_ref = XUINT (tem) | 0x2000000;
1216
1217 color_def->pixel = w32_color_ref;
1218 color_def->red = GetRValue (w32_color_ref) * 256;
1219 color_def->green = GetGValue (w32_color_ref) * 256;
1220 color_def->blue = GetBValue (w32_color_ref) * 256;
1221
1222 return 1;
1223 }
1224 else
1225 {
1226 return 0;
1227 }
1228 }
1229
1230 /* Given a string ARG naming a color, compute a pixel value from it
1231 suitable for screen F.
1232 If F is not a color screen, return DEF (default) regardless of what
1233 ARG says. */
1234
1235 static int
1236 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1237 {
1238 XColor cdef;
1239
1240 CHECK_STRING (arg);
1241
1242 if (strcmp (SSDATA (arg), "black") == 0)
1243 return BLACK_PIX_DEFAULT (f);
1244 else if (strcmp (SSDATA (arg), "white") == 0)
1245 return WHITE_PIX_DEFAULT (f);
1246
1247 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1248 return def;
1249
1250 /* w32_defined_color is responsible for coping with failures
1251 by looking for a near-miss. */
1252 if (w32_defined_color (f, SSDATA (arg), &cdef, true))
1253 return cdef.pixel;
1254
1255 /* defined_color failed; return an ultimate default. */
1256 return def;
1257 }
1258 \f
1259
1260
1261 /* Functions called only from `x_set_frame_param'
1262 to set individual parameters.
1263
1264 If FRAME_W32_WINDOW (f) is 0,
1265 the frame is being created and its window does not exist yet.
1266 In that case, just record the parameter's new value
1267 in the standard place; do not attempt to change the window. */
1268
1269 void
1270 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1271 {
1272 struct w32_output *x = f->output_data.w32;
1273 PIX_TYPE fg, old_fg;
1274
1275 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1276 old_fg = FRAME_FOREGROUND_PIXEL (f);
1277 FRAME_FOREGROUND_PIXEL (f) = fg;
1278
1279 if (FRAME_W32_WINDOW (f) != 0)
1280 {
1281 if (x->cursor_pixel == old_fg)
1282 {
1283 x->cursor_pixel = fg;
1284 x->cursor_gc->background = fg;
1285 }
1286
1287 update_face_from_frame_parameter (f, Qforeground_color, arg);
1288 if (FRAME_VISIBLE_P (f))
1289 redraw_frame (f);
1290 }
1291 }
1292
1293 void
1294 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1295 {
1296 FRAME_BACKGROUND_PIXEL (f)
1297 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1298
1299 if (FRAME_W32_WINDOW (f) != 0)
1300 {
1301 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1302 FRAME_BACKGROUND_PIXEL (f));
1303
1304 update_face_from_frame_parameter (f, Qbackground_color, arg);
1305
1306 if (FRAME_VISIBLE_P (f))
1307 redraw_frame (f);
1308 }
1309 }
1310
1311 void
1312 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1313 {
1314 #if 0
1315 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1316 int count;
1317 #endif
1318 int mask_color;
1319
1320 if (!EQ (Qnil, arg))
1321 f->output_data.w32->mouse_pixel
1322 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1323 mask_color = FRAME_BACKGROUND_PIXEL (f);
1324
1325 /* Don't let pointers be invisible. */
1326 if (mask_color == f->output_data.w32->mouse_pixel
1327 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1328 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1329
1330 #if 0 /* TODO : Mouse cursor customization. */
1331 block_input ();
1332
1333 /* It's not okay to crash if the user selects a screwy cursor. */
1334 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1335
1336 if (!EQ (Qnil, Vx_pointer_shape))
1337 {
1338 CHECK_NUMBER (Vx_pointer_shape);
1339 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1340 }
1341 else
1342 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1343 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1344
1345 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1346 {
1347 CHECK_NUMBER (Vx_nontext_pointer_shape);
1348 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1349 XINT (Vx_nontext_pointer_shape));
1350 }
1351 else
1352 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1353 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1354
1355 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1356 {
1357 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1358 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1359 XINT (Vx_hourglass_pointer_shape));
1360 }
1361 else
1362 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1363 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1364
1365 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1366 if (!EQ (Qnil, Vx_mode_pointer_shape))
1367 {
1368 CHECK_NUMBER (Vx_mode_pointer_shape);
1369 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1370 XINT (Vx_mode_pointer_shape));
1371 }
1372 else
1373 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1374 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1375
1376 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1377 {
1378 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1379 hand_cursor
1380 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1381 XINT (Vx_sensitive_text_pointer_shape));
1382 }
1383 else
1384 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1385
1386 if (!NILP (Vx_window_horizontal_drag_shape))
1387 {
1388 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1389 horizontal_drag_cursor
1390 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1391 XINT (Vx_window_horizontal_drag_shape));
1392 }
1393 else
1394 horizontal_drag_cursor
1395 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1396
1397 if (!NILP (Vx_window_vertical_drag_shape))
1398 {
1399 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1400 vertical_drag_cursor
1401 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1402 XINT (Vx_window_vertical_drag_shape));
1403 }
1404 else
1405 vertical_drag_cursor
1406 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1407
1408 /* Check and report errors with the above calls. */
1409 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1410 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1411
1412 {
1413 XColor fore_color, back_color;
1414
1415 fore_color.pixel = f->output_data.w32->mouse_pixel;
1416 back_color.pixel = mask_color;
1417 XQueryColor (FRAME_W32_DISPLAY (f),
1418 DefaultColormap (FRAME_W32_DISPLAY (f),
1419 DefaultScreen (FRAME_W32_DISPLAY (f))),
1420 &fore_color);
1421 XQueryColor (FRAME_W32_DISPLAY (f),
1422 DefaultColormap (FRAME_W32_DISPLAY (f),
1423 DefaultScreen (FRAME_W32_DISPLAY (f))),
1424 &back_color);
1425 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1426 &fore_color, &back_color);
1427 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1428 &fore_color, &back_color);
1429 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1430 &fore_color, &back_color);
1431 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1432 &fore_color, &back_color);
1433 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1434 &fore_color, &back_color);
1435 }
1436
1437 if (FRAME_W32_WINDOW (f) != 0)
1438 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1439
1440 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1441 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1442 f->output_data.w32->text_cursor = cursor;
1443
1444 if (nontext_cursor != f->output_data.w32->nontext_cursor
1445 && f->output_data.w32->nontext_cursor != 0)
1446 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1447 f->output_data.w32->nontext_cursor = nontext_cursor;
1448
1449 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1450 && f->output_data.w32->hourglass_cursor != 0)
1451 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1452 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1453
1454 if (mode_cursor != f->output_data.w32->modeline_cursor
1455 && f->output_data.w32->modeline_cursor != 0)
1456 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1457 f->output_data.w32->modeline_cursor = mode_cursor;
1458
1459 if (hand_cursor != f->output_data.w32->hand_cursor
1460 && f->output_data.w32->hand_cursor != 0)
1461 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1462 f->output_data.w32->hand_cursor = hand_cursor;
1463
1464 XFlush (FRAME_W32_DISPLAY (f));
1465 unblock_input ();
1466
1467 update_face_from_frame_parameter (f, Qmouse_color, arg);
1468 #endif /* TODO */
1469 }
1470
1471 void
1472 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1473 {
1474 unsigned long fore_pixel, pixel;
1475
1476 if (!NILP (Vx_cursor_fore_pixel))
1477 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1478 WHITE_PIX_DEFAULT (f));
1479 else
1480 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1481
1482 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1483
1484 /* Make sure that the cursor color differs from the background color. */
1485 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1486 {
1487 pixel = f->output_data.w32->mouse_pixel;
1488 if (pixel == fore_pixel)
1489 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1490 }
1491
1492 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1493 f->output_data.w32->cursor_pixel = pixel;
1494
1495 if (FRAME_W32_WINDOW (f) != 0)
1496 {
1497 block_input ();
1498 /* Update frame's cursor_gc. */
1499 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1500 f->output_data.w32->cursor_gc->background = pixel;
1501
1502 unblock_input ();
1503
1504 if (FRAME_VISIBLE_P (f))
1505 {
1506 x_update_cursor (f, 0);
1507 x_update_cursor (f, 1);
1508 }
1509 }
1510
1511 update_face_from_frame_parameter (f, Qcursor_color, arg);
1512 }
1513
1514 /* Set the border-color of frame F to pixel value PIX.
1515 Note that this does not fully take effect if done before
1516 F has a window. */
1517
1518 static void
1519 x_set_border_pixel (struct frame *f, int pix)
1520 {
1521
1522 f->output_data.w32->border_pixel = pix;
1523
1524 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1525 {
1526 if (FRAME_VISIBLE_P (f))
1527 redraw_frame (f);
1528 }
1529 }
1530
1531 /* Set the border-color of frame F to value described by ARG.
1532 ARG can be a string naming a color.
1533 The border-color is used for the border that is drawn by the server.
1534 Note that this does not fully take effect if done before
1535 F has a window; it must be redone when the window is created. */
1536
1537 void
1538 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1539 {
1540 int pix;
1541
1542 CHECK_STRING (arg);
1543 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1544 x_set_border_pixel (f, pix);
1545 update_face_from_frame_parameter (f, Qborder_color, arg);
1546 }
1547
1548
1549 void
1550 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1551 {
1552 set_frame_cursor_types (f, arg);
1553 }
1554
1555 void
1556 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1557 {
1558 bool result;
1559
1560 if (NILP (arg) && NILP (oldval))
1561 return;
1562
1563 if (STRINGP (arg) && STRINGP (oldval)
1564 && EQ (Fstring_equal (oldval, arg), Qt))
1565 return;
1566
1567 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1568 return;
1569
1570 block_input ();
1571
1572 result = x_bitmap_icon (f, arg);
1573 if (result)
1574 {
1575 unblock_input ();
1576 error ("No icon window available");
1577 }
1578
1579 unblock_input ();
1580 }
1581
1582 void
1583 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1584 {
1585 if (STRINGP (arg))
1586 {
1587 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1588 return;
1589 }
1590 else if (!NILP (arg) || NILP (oldval))
1591 return;
1592
1593 fset_icon_name (f, arg);
1594
1595 #if 0
1596 if (f->output_data.w32->icon_bitmap != 0)
1597 return;
1598
1599 block_input ();
1600
1601 result = x_text_icon (f,
1602 SSDATA ((!NILP (f->icon_name)
1603 ? f->icon_name
1604 : !NILP (f->title)
1605 ? f->title
1606 : f->name)));
1607
1608 if (result)
1609 {
1610 unblock_input ();
1611 error ("No icon window available");
1612 }
1613
1614 /* If the window was unmapped (and its icon was mapped),
1615 the new icon is not mapped, so map the window in its stead. */
1616 if (FRAME_VISIBLE_P (f))
1617 {
1618 #ifdef USE_X_TOOLKIT
1619 XtPopup (f->output_data.w32->widget, XtGrabNone);
1620 #endif
1621 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1622 }
1623
1624 XFlush (FRAME_W32_DISPLAY (f));
1625 unblock_input ();
1626 #endif
1627 }
1628 \f
1629 static void
1630 x_clear_under_internal_border (struct frame *f)
1631 {
1632 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1633
1634 /* Clear border if it's larger than before. */
1635 if (border != 0)
1636 {
1637 HDC hdc = get_frame_dc (f);
1638 int width = FRAME_PIXEL_WIDTH (f);
1639 int height = FRAME_PIXEL_HEIGHT (f);
1640
1641 block_input ();
1642 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1643 w32_clear_area (f, hdc, 0, 0, border, height);
1644 w32_clear_area (f, hdc, width - border, 0, border, height);
1645 w32_clear_area (f, hdc, 0, height - border, width, border);
1646 release_frame_dc (f, hdc);
1647 unblock_input ();
1648 }
1649 }
1650
1651
1652 void
1653 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1654 {
1655 int border;
1656
1657 CHECK_TYPE_RANGED_INTEGER (int, arg);
1658 border = max (XINT (arg), 0);
1659
1660 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1661 {
1662 f->internal_border_width = border;
1663
1664 if (FRAME_X_WINDOW (f) != 0)
1665 {
1666 adjust_frame_size (f, -1, -1, 3, false, Qinternal_border_width);
1667
1668 if (FRAME_VISIBLE_P (f))
1669 x_clear_under_internal_border (f);
1670 }
1671 }
1672 }
1673
1674
1675 void
1676 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1677 {
1678 int nlines;
1679
1680 /* Right now, menu bars don't work properly in minibuf-only frames;
1681 most of the commands try to apply themselves to the minibuffer
1682 frame itself, and get an error because you can't switch buffers
1683 in or split the minibuffer window. */
1684 if (FRAME_MINIBUF_ONLY_P (f))
1685 return;
1686
1687 if (INTEGERP (value))
1688 nlines = XINT (value);
1689 else
1690 nlines = 0;
1691
1692 FRAME_MENU_BAR_LINES (f) = 0;
1693 FRAME_MENU_BAR_HEIGHT (f) = 0;
1694 if (nlines)
1695 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1696 else
1697 {
1698 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1699 free_frame_menubar (f);
1700 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1701
1702 /* Adjust the frame size so that the client (text) dimensions
1703 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1704 set correctly. Note that we resize twice: The first time upon
1705 a request from the window manager who wants to keep the height
1706 of the outer rectangle (including decorations) unchanged, and a
1707 second time because we want to keep the height of the inner
1708 rectangle (without the decorations unchanged). */
1709 adjust_frame_size (f, -1, -1, 2, true, Qmenu_bar_lines);
1710
1711 /* Not sure whether this is needed. */
1712 x_clear_under_internal_border (f);
1713 }
1714 }
1715
1716
1717 /* Set the number of lines used for the tool bar of frame F to VALUE.
1718 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1719 the old number of tool bar lines (and is unused). This function may
1720 change the height of all windows on frame F to match the new tool bar
1721 height. By design, the frame's height doesn't change (but maybe it
1722 should if we don't get enough space otherwise). */
1723
1724 void
1725 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1726 {
1727 int nlines;
1728
1729 /* Treat tool bars like menu bars. */
1730 if (FRAME_MINIBUF_ONLY_P (f))
1731 return;
1732
1733 /* Use VALUE only if an integer >= 0. */
1734 if (INTEGERP (value) && XINT (value) >= 0)
1735 nlines = XFASTINT (value);
1736 else
1737 nlines = 0;
1738
1739 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1740 }
1741
1742
1743 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1744 void
1745 x_change_tool_bar_height (struct frame *f, int height)
1746 {
1747 int unit = FRAME_LINE_HEIGHT (f);
1748 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1749 int lines = (height + unit - 1) / unit;
1750 Lisp_Object fullscreen;
1751
1752 /* Make sure we redisplay all windows in this frame. */
1753 windows_or_buffers_changed = 23;
1754
1755 /* Recalculate tool bar and frame text sizes. */
1756 FRAME_TOOL_BAR_HEIGHT (f) = height;
1757 FRAME_TOOL_BAR_LINES (f) = lines;
1758 /* Store `tool-bar-lines' and `height' frame parameters. */
1759 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1760 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1761
1762 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1763 {
1764 clear_frame (f);
1765 clear_current_matrices (f);
1766 }
1767
1768 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1769 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1770
1771 /* Recalculate toolbar height. */
1772 f->n_tool_bar_rows = 0;
1773 if (old_height == 0
1774 && (!f->after_make_frame
1775 || NILP (frame_inhibit_implied_resize)
1776 || (CONSP (frame_inhibit_implied_resize)
1777 && NILP (Fmemq (Qtool_bar_lines, frame_inhibit_implied_resize)))))
1778 f->tool_bar_redisplayed = f->tool_bar_resized = false;
1779
1780 adjust_frame_size (f, -1, -1,
1781 ((!f->tool_bar_resized
1782 && (NILP (fullscreen =
1783 get_frame_param (f, Qfullscreen))
1784 || EQ (fullscreen, Qfullwidth))) ? 1
1785 : (old_height == 0 || height == 0) ? 2
1786 : 4),
1787 false, Qtool_bar_lines);
1788
1789 f->tool_bar_resized = f->tool_bar_redisplayed;
1790
1791 /* adjust_frame_size might not have done anything, garbage frame
1792 here. */
1793 adjust_frame_glyphs (f);
1794 SET_FRAME_GARBAGED (f);
1795 if (FRAME_X_WINDOW (f))
1796 x_clear_under_internal_border (f);
1797 }
1798
1799 static void
1800 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1801 {
1802 if (FRAME_W32_WINDOW (f))
1803 {
1804 block_input ();
1805 #ifdef __CYGWIN__
1806 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1807 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1808 #else
1809 /* The frame's title many times shows the name of the file
1810 visited in the selected window's buffer, so it makes sense to
1811 support non-ASCII characters outside of the current system
1812 codepage in the title. */
1813 if (w32_unicode_filenames)
1814 {
1815 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1816 wchar_t *title_w;
1817 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1818 -1, NULL, 0);
1819
1820 if (tlen > 0)
1821 {
1822 /* Windows truncates the title text beyond what fits on
1823 a single line, so we can limit the length to some
1824 reasonably large value, and use alloca. */
1825 if (tlen > 10000)
1826 tlen = 10000;
1827 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1828 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1829 title_w, tlen);
1830 title_w[tlen] = L'\0';
1831 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1832 }
1833 else /* Conversion to UTF-16 failed, so we punt. */
1834 SetWindowTextA (FRAME_W32_WINDOW (f),
1835 SSDATA (ENCODE_SYSTEM (name)));
1836 }
1837 else
1838 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1839 #endif
1840 unblock_input ();
1841 }
1842 }
1843
1844 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1845 w32_id_name.
1846
1847 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1848 name; if NAME is a string, set F's name to NAME and set
1849 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1850
1851 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1852 suggesting a new name, which lisp code should override; if
1853 F->explicit_name is set, ignore the new name; otherwise, set it. */
1854
1855 static void
1856 x_set_name (struct frame *f, Lisp_Object name, bool explicit)
1857 {
1858 /* Make sure that requests from lisp code override requests from
1859 Emacs redisplay code. */
1860 if (explicit)
1861 {
1862 /* If we're switching from explicit to implicit, we had better
1863 update the mode lines and thereby update the title. */
1864 if (f->explicit_name && NILP (name))
1865 update_mode_lines = 25;
1866
1867 f->explicit_name = ! NILP (name);
1868 }
1869 else if (f->explicit_name)
1870 return;
1871
1872 /* If NAME is nil, set the name to the w32_id_name. */
1873 if (NILP (name))
1874 {
1875 /* Check for no change needed in this very common case
1876 before we do any consing. */
1877 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1878 SSDATA (f->name)))
1879 return;
1880 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1881 }
1882 else
1883 CHECK_STRING (name);
1884
1885 /* Don't change the name if it's already NAME. */
1886 if (! NILP (Fstring_equal (name, f->name)))
1887 return;
1888
1889 fset_name (f, name);
1890
1891 /* For setting the frame title, the title parameter should override
1892 the name parameter. */
1893 if (! NILP (f->title))
1894 name = f->title;
1895
1896 w32_set_title_bar_text (f, name);
1897 }
1898
1899 /* This function should be called when the user's lisp code has
1900 specified a name for the frame; the name will override any set by the
1901 redisplay code. */
1902 void
1903 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1904 {
1905 x_set_name (f, arg, true);
1906 }
1907
1908 /* This function should be called by Emacs redisplay code to set the
1909 name; names set this way will never override names set by the user's
1910 lisp code. */
1911 void
1912 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1913 {
1914 x_set_name (f, arg, false);
1915 }
1916 \f
1917 /* Change the title of frame F to NAME.
1918 If NAME is nil, use the frame name as the title. */
1919
1920 void
1921 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1922 {
1923 /* Don't change the title if it's already NAME. */
1924 if (EQ (name, f->title))
1925 return;
1926
1927 update_mode_lines = 26;
1928
1929 fset_title (f, name);
1930
1931 if (NILP (name))
1932 name = f->name;
1933
1934 w32_set_title_bar_text (f, name);
1935 }
1936
1937 void
1938 x_set_scroll_bar_default_width (struct frame *f)
1939 {
1940 int unit = FRAME_COLUMN_WIDTH (f);
1941
1942 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1943 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1944 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1945 }
1946
1947
1948 void
1949 x_set_scroll_bar_default_height (struct frame *f)
1950 {
1951 int unit = FRAME_LINE_HEIGHT (f);
1952
1953 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
1954 FRAME_CONFIG_SCROLL_BAR_LINES (f)
1955 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
1956 }
1957 \f
1958 /* Subroutines for creating a frame. */
1959
1960 Cursor w32_load_cursor (LPCTSTR);
1961
1962 Cursor
1963 w32_load_cursor (LPCTSTR name)
1964 {
1965 /* Try first to load cursor from application resource. */
1966 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1967 name, IMAGE_CURSOR, 0, 0,
1968 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1969 if (!cursor)
1970 {
1971 /* Then try to load a shared predefined cursor. */
1972 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1973 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1974 }
1975 return cursor;
1976 }
1977
1978 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1979
1980 #define INIT_WINDOW_CLASS(WC) \
1981 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1982 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1983 (WC).cbClsExtra = 0; \
1984 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1985 (WC).hInstance = hinst; \
1986 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1987 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1988 (WC).hbrBackground = NULL; \
1989 (WC).lpszMenuName = NULL; \
1990
1991 static BOOL
1992 w32_init_class (HINSTANCE hinst)
1993 {
1994 if (w32_unicode_gui)
1995 {
1996 WNDCLASSW uwc;
1997 INIT_WINDOW_CLASS(uwc);
1998 uwc.lpszClassName = L"Emacs";
1999
2000 return RegisterClassW (&uwc);
2001 }
2002 else
2003 {
2004 WNDCLASS wc;
2005 INIT_WINDOW_CLASS(wc);
2006 wc.lpszClassName = EMACS_CLASS;
2007
2008 return RegisterClassA (&wc);
2009 }
2010 }
2011
2012 static HWND
2013 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
2014 {
2015 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2016 /* Position and size of scroll bar. */
2017 bar->left, bar->top, bar->width, bar->height,
2018 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2019 }
2020
2021 static HWND
2022 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
2023 {
2024 return CreateWindow ("SCROLLBAR", "", SBS_HORZ | WS_CHILD | WS_VISIBLE,
2025 /* Position and size of scroll bar. */
2026 bar->left, bar->top, bar->width, bar->height,
2027 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2028 }
2029
2030 static void
2031 w32_createwindow (struct frame *f, int *coords)
2032 {
2033 HWND hwnd;
2034 RECT rect;
2035 int top;
2036 int left;
2037
2038 rect.left = rect.top = 0;
2039 rect.right = FRAME_PIXEL_WIDTH (f);
2040 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2041
2042 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2043 FRAME_EXTERNAL_MENU_BAR (f));
2044
2045 /* Do first time app init */
2046
2047 w32_init_class (hinst);
2048
2049 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2050 {
2051 left = f->left_pos;
2052 top = f->top_pos;
2053 }
2054 else
2055 {
2056 left = coords[0];
2057 top = coords[1];
2058 }
2059
2060 FRAME_W32_WINDOW (f) = hwnd
2061 = CreateWindow (EMACS_CLASS,
2062 f->namebuf,
2063 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2064 left, top,
2065 rect.right - rect.left, rect.bottom - rect.top,
2066 NULL,
2067 NULL,
2068 hinst,
2069 NULL);
2070
2071 if (hwnd)
2072 {
2073 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2074 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2075 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2076 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2077 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2078 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2079
2080 /* Enable drag-n-drop. */
2081 DragAcceptFiles (hwnd, TRUE);
2082
2083 /* Do this to discard the default setting specified by our parent. */
2084 ShowWindow (hwnd, SW_HIDE);
2085
2086 /* Update frame positions. */
2087 GetWindowRect (hwnd, &rect);
2088 f->left_pos = rect.left;
2089 f->top_pos = rect.top;
2090 }
2091 }
2092
2093 static void
2094 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2095 {
2096 wmsg->msg.hwnd = hwnd;
2097 wmsg->msg.message = msg;
2098 wmsg->msg.wParam = wParam;
2099 wmsg->msg.lParam = lParam;
2100 wmsg->msg.time = GetMessageTime ();
2101
2102 post_msg (wmsg);
2103 }
2104
2105 #ifdef WINDOWSNT
2106 /* The Windows keyboard hook callback. */
2107 static LRESULT CALLBACK
2108 funhook (int code, WPARAM w, LPARAM l)
2109 {
2110 INPUT inputs[2];
2111 HWND focus = GetFocus ();
2112 int console = 0;
2113 KBDLLHOOKSTRUCT const *hs = (KBDLLHOOKSTRUCT*)l;
2114
2115 if (code < 0 || (hs->flags & LLKHF_INJECTED))
2116 return CallNextHookEx (0, code, w, l);
2117
2118 /* The keyboard hook sees keyboard input on all processes (except
2119 elevated ones, when Emacs itself is not elevated). As such,
2120 care must be taken to only filter out keyboard input when Emacs
2121 itself is on the foreground.
2122
2123 GetFocus returns a non-NULL window if another application is active,
2124 and always for a console Emacs process. For a console Emacs, determine
2125 focus by checking if the current foreground window is the process's
2126 console window. */
2127 if (focus == NULL && kbdhook.console != NULL)
2128 {
2129 if (GetForegroundWindow () == kbdhook.console)
2130 {
2131 focus = kbdhook.console;
2132 console = 1;
2133 }
2134 }
2135
2136 /* First, check hooks for the left and right Windows keys. */
2137 if (hs->vkCode == VK_LWIN || hs->vkCode == VK_RWIN)
2138 {
2139 if (focus != NULL && (w == WM_KEYDOWN || w == WM_SYSKEYDOWN))
2140 {
2141 /* The key is being pressed in an Emacs window. */
2142 if (hs->vkCode == VK_LWIN && !kbdhook.lwindown)
2143 {
2144 kbdhook.lwindown = 1;
2145 kbdhook.winseen = 1;
2146 kbdhook.winsdown++;
2147 }
2148 else if (hs->vkCode == VK_RWIN && !kbdhook.rwindown)
2149 {
2150 kbdhook.rwindown = 1;
2151 kbdhook.winseen = 1;
2152 kbdhook.winsdown++;
2153 }
2154 /* Returning 1 here drops the keypress without further processing.
2155 If the keypress was allowed to go through, the normal Windows
2156 hotkeys would take over. */
2157 return 1;
2158 }
2159 else if (kbdhook.winsdown > 0 && (w == WM_KEYUP || w == WM_SYSKEYUP))
2160 {
2161 /* A key that has been captured earlier is being released now. */
2162 if (hs->vkCode == VK_LWIN && kbdhook.lwindown)
2163 {
2164 kbdhook.lwindown = 0;
2165 kbdhook.winsdown--;
2166 }
2167 else if (hs->vkCode == VK_RWIN && kbdhook.rwindown)
2168 {
2169 kbdhook.rwindown = 0;
2170 kbdhook.winsdown--;
2171 }
2172 if (kbdhook.winsdown == 0 && kbdhook.winseen)
2173 {
2174 if (!kbdhook.suppress_lone)
2175 {
2176 /* The Windows key was pressed, then released,
2177 without any other key pressed simultaneously.
2178 Normally, this opens the Start menu, but the user
2179 can prevent this by setting the
2180 w32-pass-[lr]window-to-system variable to
2181 NIL. */
2182 if ((hs->vkCode == VK_LWIN && !NILP (Vw32_pass_lwindow_to_system)) ||
2183 (hs->vkCode == VK_RWIN && !NILP (Vw32_pass_rwindow_to_system)))
2184 {
2185 /* Not prevented - Simulate the keypress to the system. */
2186 memset (inputs, 0, sizeof (inputs));
2187 inputs[0].type = INPUT_KEYBOARD;
2188 inputs[0].ki.wVk = hs->vkCode;
2189 inputs[0].ki.wScan = hs->vkCode;
2190 inputs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
2191 inputs[0].ki.time = 0;
2192 inputs[1].type = INPUT_KEYBOARD;
2193 inputs[1].ki.wVk = hs->vkCode;
2194 inputs[1].ki.wScan = hs->vkCode;
2195 inputs[1].ki.dwFlags
2196 = KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP;
2197 inputs[1].ki.time = 0;
2198 SendInput (2, inputs, sizeof (INPUT));
2199 }
2200 else if (focus != NULL)
2201 {
2202 /* When not passed to system, must simulate privately to Emacs. */
2203 PostMessage (focus, WM_SYSKEYDOWN, hs->vkCode, 0);
2204 PostMessage (focus, WM_SYSKEYUP, hs->vkCode, 0);
2205 }
2206 }
2207 }
2208 if (kbdhook.winsdown == 0)
2209 {
2210 /* No Windows keys pressed anymore - clear the state flags. */
2211 kbdhook.suppress_lone = 0;
2212 kbdhook.winseen = 0;
2213 }
2214 if (!kbdhook.send_win_up)
2215 {
2216 /* Swallow this release message, as not to confuse
2217 applications who did not get to see the original
2218 WM_KEYDOWN message either. */
2219 return 1;
2220 }
2221 kbdhook.send_win_up = 0;
2222 }
2223 }
2224 else if (kbdhook.winsdown > 0)
2225 {
2226 /* Some other key was pressed while a captured Win key is down.
2227 This is either an Emacs registered hotkey combination, or a
2228 system hotkey. */
2229 if ((kbdhook.lwindown && kbdhook.lwin_hooked[hs->vkCode]) ||
2230 (kbdhook.rwindown && kbdhook.rwin_hooked[hs->vkCode]))
2231 {
2232 /* Hooked Win-x combination, do not pass the keypress to Windows. */
2233 kbdhook.suppress_lone = 1;
2234 }
2235 else if (!kbdhook.suppress_lone)
2236 {
2237 /* Unhooked S-x combination; simulate the combination now
2238 (will be seen by the system). */
2239 memset (inputs, 0, sizeof (inputs));
2240 inputs[0].type = INPUT_KEYBOARD;
2241 inputs[0].ki.wVk = kbdhook.lwindown ? VK_LWIN : VK_RWIN;
2242 inputs[0].ki.wScan = kbdhook.lwindown ? VK_LWIN : VK_RWIN;
2243 inputs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
2244 inputs[0].ki.time = 0;
2245 inputs[1].type = INPUT_KEYBOARD;
2246 inputs[1].ki.wVk = hs->vkCode;
2247 inputs[1].ki.wScan = hs->scanCode;
2248 inputs[1].ki.dwFlags =
2249 (hs->flags & LLKHF_EXTENDED) ? KEYEVENTF_EXTENDEDKEY : 0;
2250 inputs[1].ki.time = 0;
2251 SendInput (2, inputs, sizeof (INPUT));
2252 /* Stop processing of this Win sequence here; the
2253 corresponding keyup messages will come through the normal
2254 channel when the keys are released. */
2255 kbdhook.suppress_lone = 1;
2256 kbdhook.send_win_up = 1;
2257 /* Swallow the original keypress (as we want the Win key
2258 down message simulated above to precede this real message). */
2259 return 1;
2260 }
2261 }
2262
2263 /* Next, handle the registered Alt-* combinations. */
2264 if ((w == WM_SYSKEYDOWN || w == WM_KEYDOWN)
2265 && kbdhook.alt_hooked[hs->vkCode]
2266 && focus != NULL
2267 && (GetAsyncKeyState (VK_MENU) & 0x8000))
2268 {
2269 /* Prevent the system from getting this Alt-* key - suppress the
2270 message and post as a normal keypress to Emacs. */
2271 if (console)
2272 {
2273 INPUT_RECORD rec;
2274 DWORD n;
2275 rec.EventType = KEY_EVENT;
2276 rec.Event.KeyEvent.bKeyDown = TRUE;
2277 rec.Event.KeyEvent.wVirtualKeyCode = hs->vkCode;
2278 rec.Event.KeyEvent.wVirtualScanCode = hs->scanCode;
2279 rec.Event.KeyEvent.uChar.UnicodeChar = 0;
2280 rec.Event.KeyEvent.dwControlKeyState =
2281 ((GetAsyncKeyState (VK_LMENU) & 0x8000) ? LEFT_ALT_PRESSED : 0)
2282 | ((GetAsyncKeyState (VK_RMENU) & 0x8000) ? RIGHT_ALT_PRESSED : 0)
2283 | ((GetAsyncKeyState (VK_LCONTROL) & 0x8000) ? LEFT_CTRL_PRESSED : 0)
2284 | ((GetAsyncKeyState (VK_RCONTROL) & 0x8000) ? RIGHT_CTRL_PRESSED : 0)
2285 | ((GetAsyncKeyState (VK_SHIFT) & 0x8000) ? SHIFT_PRESSED : 0)
2286 | ((hs->flags & LLKHF_EXTENDED) ? ENHANCED_KEY : 0);
2287 if (w32_console_unicode_input)
2288 WriteConsoleInputW (keyboard_handle, &rec, 1, &n);
2289 else
2290 WriteConsoleInputA (keyboard_handle, &rec, 1, &n);
2291 }
2292 else
2293 PostMessage (focus, w, hs->vkCode, 1 | (1<<29));
2294 return 1;
2295 }
2296
2297 /* The normal case - pass the message through. */
2298 return CallNextHookEx (0, code, w, l);
2299 }
2300
2301 /* Set up the hook; can be called several times, with matching
2302 remove_w32_kbdhook calls. */
2303 void
2304 setup_w32_kbdhook (void)
2305 {
2306 kbdhook.hook_count++;
2307
2308 /* This hook gets in the way of debugging, since when Emacs stops,
2309 its input thread stops, and there's nothing to process keyboard
2310 events, whereas this hook is global, and is invoked in the
2311 context of the thread that installed it. So we don't install the
2312 hook if the process is being debugged. */
2313 if (w32_kbdhook_active)
2314 {
2315 IsDebuggerPresent_Proc is_debugger_present = (IsDebuggerPresent_Proc)
2316 GetProcAddress (GetModuleHandle ("kernel32.dll"), "IsDebuggerPresent");
2317 if (is_debugger_present && is_debugger_present ())
2318 return;
2319 }
2320
2321 /* Hooking is only available on NT architecture systems, as
2322 indicated by the w32_kbdhook_active variable. */
2323 if (kbdhook.hook_count == 1 && w32_kbdhook_active)
2324 {
2325 /* Get the handle of the Emacs console window. As the
2326 GetConsoleWindow function is only available on Win2000+, a
2327 hackish workaround described in Microsoft KB article 124103
2328 (https://support.microsoft.com/en-us/kb/124103) is used for
2329 NT 4 systems. */
2330 GetConsoleWindow_Proc get_console = (GetConsoleWindow_Proc)
2331 GetProcAddress (GetModuleHandle ("kernel32.dll"), "GetConsoleWindow");
2332
2333 if (get_console != NULL)
2334 kbdhook.console = get_console ();
2335 else
2336 {
2337 GUID guid;
2338 wchar_t *oldTitle = malloc (1024 * sizeof(wchar_t));
2339 wchar_t newTitle[64];
2340 int i;
2341
2342 CoCreateGuid (&guid);
2343 StringFromGUID2 (&guid, newTitle, 64);
2344 if (newTitle != NULL)
2345 {
2346 GetConsoleTitleW (oldTitle, 1024);
2347 SetConsoleTitleW (newTitle);
2348 for (i = 0; i < 25; i++)
2349 {
2350 Sleep (40);
2351 kbdhook.console = FindWindowW (NULL, newTitle);
2352 if (kbdhook.console != NULL)
2353 break;
2354 }
2355 SetConsoleTitleW (oldTitle);
2356 }
2357 free (oldTitle);
2358 }
2359
2360 /* Set the hook. */
2361 kbdhook.hook = SetWindowsHookEx (WH_KEYBOARD_LL, funhook,
2362 GetModuleHandle (NULL), 0);
2363 }
2364 }
2365
2366 /* Remove the hook. */
2367 void
2368 remove_w32_kbdhook (void)
2369 {
2370 kbdhook.hook_count--;
2371 if (kbdhook.hook_count == 0 && w32_kbdhook_active)
2372 {
2373 UnhookWindowsHookEx (kbdhook.hook);
2374 kbdhook.hook = NULL;
2375 }
2376 }
2377 #endif /* WINDOWSNT */
2378
2379 /* Mark a specific key combination as hooked, preventing it to be
2380 handled by the system. */
2381 static void
2382 hook_w32_key (int hook, int modifier, int vkey)
2383 {
2384 char *tbl = NULL;
2385
2386 switch (modifier)
2387 {
2388 case VK_MENU:
2389 tbl = kbdhook.alt_hooked;
2390 break;
2391 case VK_LWIN:
2392 tbl = kbdhook.lwin_hooked;
2393 break;
2394 case VK_RWIN:
2395 tbl = kbdhook.rwin_hooked;
2396 break;
2397 }
2398
2399 if (tbl != NULL && vkey >= 0 && vkey <= 255)
2400 {
2401 /* VK_ANY hooks all keys for this modifier */
2402 if (vkey == VK_ANY)
2403 memset (tbl, (char)hook, 256);
2404 else
2405 tbl[vkey] = (char)hook;
2406 /* Alt-<modifier>s should go through */
2407 kbdhook.alt_hooked[VK_MENU] = 0;
2408 kbdhook.alt_hooked[VK_LMENU] = 0;
2409 kbdhook.alt_hooked[VK_RMENU] = 0;
2410 kbdhook.alt_hooked[VK_CONTROL] = 0;
2411 kbdhook.alt_hooked[VK_LCONTROL] = 0;
2412 kbdhook.alt_hooked[VK_RCONTROL] = 0;
2413 kbdhook.alt_hooked[VK_SHIFT] = 0;
2414 kbdhook.alt_hooked[VK_LSHIFT] = 0;
2415 kbdhook.alt_hooked[VK_RSHIFT] = 0;
2416 }
2417 }
2418
2419 #ifdef WINDOWSNT
2420 /* Check the current Win key pressed state. */
2421 int
2422 check_w32_winkey_state (int vkey)
2423 {
2424 /* The hook code handles grabbing of the Windows keys and Alt-* key
2425 combinations reserved by the system. Handling Alt is a bit
2426 easier, as Windows intends Alt-* shortcuts for application use in
2427 Windows; hotkeys such as Alt-tab and Alt-escape are special
2428 cases. Win-* hotkeys, on the other hand, are primarily meant for
2429 system use.
2430
2431 As a result, when we want Emacs to be able to grab the Win-*
2432 keys, we must swallow all Win key presses in a low-level keyboard
2433 hook. Unfortunately, this means that the Emacs window procedure
2434 (and console input handler) never see the keypresses either.
2435 Thus, to check the modifier states properly, Emacs code must use
2436 the check_w32_winkey_state function that uses the flags directly
2437 updated by the hook callback. */
2438 switch (vkey)
2439 {
2440 case VK_LWIN:
2441 return kbdhook.lwindown;
2442 case VK_RWIN:
2443 return kbdhook.rwindown;
2444 }
2445 return 0;
2446 }
2447 #endif /* WINDOWSNT */
2448
2449 /* Reset the keyboard hook state. Locking the workstation with Win-L
2450 leaves the Win key(s) "down" from the hook's point of view - the
2451 keyup event is never seen. Thus, this function must be called when
2452 the system is locked. */
2453 static void
2454 reset_w32_kbdhook_state (void)
2455 {
2456 kbdhook.lwindown = 0;
2457 kbdhook.rwindown = 0;
2458 kbdhook.winsdown = 0;
2459 kbdhook.send_win_up = 0;
2460 kbdhook.suppress_lone = 0;
2461 kbdhook.winseen = 0;
2462 }
2463
2464 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2465 between left and right keys as advertised. We test for this
2466 support dynamically, and set a flag when the support is absent. If
2467 absent, we keep track of the left and right control and alt keys
2468 ourselves. This is particularly necessary on keyboards that rely
2469 upon the AltGr key, which is represented as having the left control
2470 and right alt keys pressed. For these keyboards, we need to know
2471 when the left alt key has been pressed in addition to the AltGr key
2472 so that we can properly support M-AltGr-key sequences (such as M-@
2473 on Swedish keyboards). */
2474
2475 #define EMACS_LCONTROL 0
2476 #define EMACS_RCONTROL 1
2477 #define EMACS_LMENU 2
2478 #define EMACS_RMENU 3
2479
2480 static int modifiers[4];
2481 static int modifiers_recorded;
2482 static int modifier_key_support_tested;
2483
2484 static void
2485 test_modifier_support (unsigned int wparam)
2486 {
2487 unsigned int l, r;
2488
2489 if (wparam != VK_CONTROL && wparam != VK_MENU)
2490 return;
2491 if (wparam == VK_CONTROL)
2492 {
2493 l = VK_LCONTROL;
2494 r = VK_RCONTROL;
2495 }
2496 else
2497 {
2498 l = VK_LMENU;
2499 r = VK_RMENU;
2500 }
2501 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2502 modifiers_recorded = 1;
2503 else
2504 modifiers_recorded = 0;
2505 modifier_key_support_tested = 1;
2506 }
2507
2508 static void
2509 record_keydown (unsigned int wparam, unsigned int lparam)
2510 {
2511 int i;
2512
2513 if (!modifier_key_support_tested)
2514 test_modifier_support (wparam);
2515
2516 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2517 return;
2518
2519 if (wparam == VK_CONTROL)
2520 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2521 else
2522 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2523
2524 modifiers[i] = 1;
2525 }
2526
2527 static void
2528 record_keyup (unsigned int wparam, unsigned int lparam)
2529 {
2530 int i;
2531
2532 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2533 return;
2534
2535 if (wparam == VK_CONTROL)
2536 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2537 else
2538 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2539
2540 modifiers[i] = 0;
2541 }
2542
2543 /* Emacs can lose focus while a modifier key has been pressed. When
2544 it regains focus, be conservative and clear all modifiers since
2545 we cannot reconstruct the left and right modifier state. */
2546 static void
2547 reset_modifiers (void)
2548 {
2549 SHORT ctrl, alt;
2550
2551 if (GetFocus () == NULL)
2552 /* Emacs doesn't have keyboard focus. Do nothing. */
2553 return;
2554
2555 ctrl = GetAsyncKeyState (VK_CONTROL);
2556 alt = GetAsyncKeyState (VK_MENU);
2557
2558 if (!(ctrl & 0x08000))
2559 /* Clear any recorded control modifier state. */
2560 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2561
2562 if (!(alt & 0x08000))
2563 /* Clear any recorded alt modifier state. */
2564 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2565
2566 /* Update the state of all modifier keys, because modifiers used in
2567 hot-key combinations can get stuck on if Emacs loses focus as a
2568 result of a hot-key being pressed. */
2569 {
2570 BYTE keystate[256];
2571
2572 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2573
2574 memset (keystate, 0, sizeof (keystate));
2575 GetKeyboardState (keystate);
2576 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2577 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2578 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2579 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2580 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2581 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2582 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2583 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2584 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2585 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2586 SetKeyboardState (keystate);
2587 }
2588 }
2589
2590 /* Synchronize modifier state with what is reported with the current
2591 keystroke. Even if we cannot distinguish between left and right
2592 modifier keys, we know that, if no modifiers are set, then neither
2593 the left or right modifier should be set. */
2594 static void
2595 sync_modifiers (void)
2596 {
2597 if (!modifiers_recorded)
2598 return;
2599
2600 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2601 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2602
2603 if (!(GetKeyState (VK_MENU) & 0x8000))
2604 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2605 }
2606
2607 static int
2608 modifier_set (int vkey)
2609 {
2610 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2611 toggle keys is not an omission! If you want to add it, you will
2612 have to make changes in the default sub-case of the WM_KEYDOWN
2613 switch, because if the NUMLOCK modifier is set, the code there
2614 will directly convert any key that looks like an ASCII letter,
2615 and also downcase those that look like upper-case ASCII. */
2616 if (vkey == VK_CAPITAL)
2617 {
2618 if (NILP (Vw32_enable_caps_lock))
2619 return 0;
2620 else
2621 return (GetKeyState (vkey) & 0x1);
2622 }
2623 if (vkey == VK_SCROLL)
2624 {
2625 if (NILP (Vw32_scroll_lock_modifier)
2626 /* w32-scroll-lock-modifier can be any non-nil value that is
2627 not one of the modifiers, in which case it shall be ignored. */
2628 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2629 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2630 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2631 || EQ (Vw32_scroll_lock_modifier, Qalt)
2632 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2633 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2634 return 0;
2635 else
2636 return (GetKeyState (vkey) & 0x1);
2637 }
2638 #ifdef WINDOWSNT
2639 if (w32_kbdhook_active && (vkey == VK_LWIN || vkey == VK_RWIN))
2640 return check_w32_winkey_state (vkey);
2641 #endif
2642
2643 if (!modifiers_recorded)
2644 return (GetKeyState (vkey) & 0x8000);
2645
2646 switch (vkey)
2647 {
2648 case VK_LCONTROL:
2649 return modifiers[EMACS_LCONTROL];
2650 case VK_RCONTROL:
2651 return modifiers[EMACS_RCONTROL];
2652 case VK_LMENU:
2653 return modifiers[EMACS_LMENU];
2654 case VK_RMENU:
2655 return modifiers[EMACS_RMENU];
2656 }
2657 return (GetKeyState (vkey) & 0x8000);
2658 }
2659
2660 /* Convert between the modifier bits W32 uses and the modifier bits
2661 Emacs uses. */
2662 unsigned int w32_key_to_modifier (int);
2663
2664 unsigned int
2665 w32_key_to_modifier (int key)
2666 {
2667 Lisp_Object key_mapping;
2668
2669 switch (key)
2670 {
2671 case VK_LWIN:
2672 key_mapping = Vw32_lwindow_modifier;
2673 break;
2674 case VK_RWIN:
2675 key_mapping = Vw32_rwindow_modifier;
2676 break;
2677 case VK_APPS:
2678 key_mapping = Vw32_apps_modifier;
2679 break;
2680 case VK_SCROLL:
2681 key_mapping = Vw32_scroll_lock_modifier;
2682 break;
2683 default:
2684 key_mapping = Qnil;
2685 }
2686
2687 /* NB. This code runs in the input thread, asynchronously to the lisp
2688 thread, so we must be careful to ensure access to lisp data is
2689 thread-safe. The following code is safe because the modifier
2690 variable values are updated atomically from lisp and symbols are
2691 not relocated by GC. Also, we don't have to worry about seeing GC
2692 markbits here. */
2693 if (EQ (key_mapping, Qhyper))
2694 return hyper_modifier;
2695 if (EQ (key_mapping, Qsuper))
2696 return super_modifier;
2697 if (EQ (key_mapping, Qmeta))
2698 return meta_modifier;
2699 if (EQ (key_mapping, Qalt))
2700 return alt_modifier;
2701 if (EQ (key_mapping, Qctrl))
2702 return ctrl_modifier;
2703 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2704 return ctrl_modifier;
2705 if (EQ (key_mapping, Qshift))
2706 return shift_modifier;
2707
2708 /* Don't generate any modifier if not explicitly requested. */
2709 return 0;
2710 }
2711
2712 static unsigned int
2713 w32_get_modifiers (void)
2714 {
2715 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2716 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2717 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2718 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2719 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2720 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2721 (modifier_set (VK_MENU) ?
2722 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2723 }
2724
2725 /* We map the VK_* modifiers into console modifier constants
2726 so that we can use the same routines to handle both console
2727 and window input. */
2728
2729 static int
2730 construct_console_modifiers (void)
2731 {
2732 int mods;
2733
2734 mods = 0;
2735 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2736 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2737 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2738 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2739 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2740 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2741 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2742 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2743 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2744 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2745 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2746
2747 return mods;
2748 }
2749
2750 static int
2751 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2752 {
2753 int mods;
2754
2755 /* Convert to emacs modifiers. */
2756 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2757
2758 return mods;
2759 }
2760
2761 unsigned int map_keypad_keys (unsigned int, unsigned int);
2762
2763 unsigned int
2764 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2765 {
2766 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2767 return virt_key;
2768
2769 if (virt_key == VK_RETURN)
2770 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2771
2772 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2773 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2774
2775 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2776 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2777
2778 if (virt_key == VK_CLEAR)
2779 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2780
2781 return virt_key;
2782 }
2783
2784 /* List of special key combinations which w32 would normally capture,
2785 but Emacs should grab instead. Not directly visible to lisp, to
2786 simplify synchronization. Each item is an integer encoding a virtual
2787 key code and modifier combination to capture.
2788 Note: This code is not used if keyboard hooks are active
2789 (Windows 2000 and later). */
2790 static Lisp_Object w32_grabbed_keys;
2791
2792 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2793 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2794 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2795 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2796
2797 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2798 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2799 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2800
2801 /* Register hot-keys for reserved key combinations when Emacs has
2802 keyboard focus, since this is the only way Emacs can receive key
2803 combinations like Alt-Tab which are used by the system. */
2804
2805 static void
2806 register_hot_keys (HWND hwnd)
2807 {
2808 Lisp_Object keylist;
2809
2810 /* Use CONSP, since we are called asynchronously. */
2811 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2812 {
2813 Lisp_Object key = XCAR (keylist);
2814
2815 /* Deleted entries get set to nil. */
2816 if (!INTEGERP (key))
2817 continue;
2818
2819 RegisterHotKey (hwnd, HOTKEY_ID (key),
2820 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2821 }
2822 }
2823
2824 static void
2825 unregister_hot_keys (HWND hwnd)
2826 {
2827 Lisp_Object keylist;
2828
2829 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2830 {
2831 Lisp_Object key = XCAR (keylist);
2832
2833 if (!INTEGERP (key))
2834 continue;
2835
2836 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2837 }
2838 }
2839
2840 #if EMACSDEBUG
2841 const char*
2842 w32_name_of_message (UINT msg)
2843 {
2844 unsigned i;
2845 static char buf[64];
2846 static const struct {
2847 UINT msg;
2848 const char* name;
2849 } msgnames[] = {
2850 #define M(msg) { msg, # msg }
2851 M (WM_PAINT),
2852 M (WM_TIMER),
2853 M (WM_USER),
2854 M (WM_MOUSEMOVE),
2855 M (WM_LBUTTONUP),
2856 M (WM_KEYDOWN),
2857 M (WM_EMACS_KILL),
2858 M (WM_EMACS_CREATEWINDOW),
2859 M (WM_EMACS_DONE),
2860 M (WM_EMACS_CREATEVSCROLLBAR),
2861 M (WM_EMACS_CREATEHSCROLLBAR),
2862 M (WM_EMACS_SHOWWINDOW),
2863 M (WM_EMACS_SETWINDOWPOS),
2864 M (WM_EMACS_DESTROYWINDOW),
2865 M (WM_EMACS_TRACKPOPUPMENU),
2866 M (WM_EMACS_SETFOCUS),
2867 M (WM_EMACS_SETFOREGROUND),
2868 M (WM_EMACS_SETLOCALE),
2869 M (WM_EMACS_SETKEYBOARDLAYOUT),
2870 M (WM_EMACS_REGISTER_HOT_KEY),
2871 M (WM_EMACS_UNREGISTER_HOT_KEY),
2872 M (WM_EMACS_TOGGLE_LOCK_KEY),
2873 M (WM_EMACS_TRACK_CARET),
2874 M (WM_EMACS_DESTROY_CARET),
2875 M (WM_EMACS_SHOW_CARET),
2876 M (WM_EMACS_HIDE_CARET),
2877 M (WM_EMACS_SETCURSOR),
2878 M (WM_EMACS_SHOWCURSOR),
2879 M (WM_EMACS_PAINT),
2880 M (WM_CHAR),
2881 #undef M
2882 { 0, 0 }
2883 };
2884
2885 for (i = 0; msgnames[i].name; ++i)
2886 if (msgnames[i].msg == msg)
2887 return msgnames[i].name;
2888
2889 sprintf (buf, "message 0x%04x", (unsigned)msg);
2890 return buf;
2891 }
2892 #endif /* EMACSDEBUG */
2893
2894 /* Here's an overview of how Emacs input works in GUI sessions on
2895 MS-Windows. (For description of non-GUI input, see the commentary
2896 before w32_console_read_socket in w32inevt.c.)
2897
2898 System messages are read and processed by w32_msg_pump below. This
2899 function runs in a separate thread. It handles a small number of
2900 custom WM_EMACS_* messages (posted by the main thread, look for
2901 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2902 is the main window procedure for the entire Emacs application.
2903
2904 w32_wnd_proc also runs in the same separate input thread. It
2905 handles some messages, mostly those that need GDI calls, by itself.
2906 For the others, it calls my_post_msg, which inserts the messages
2907 into the input queue serviced by w32_read_socket.
2908
2909 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2910 called synchronously from keyboard.c when it is known or suspected
2911 that some input is available. w32_read_socket either handles
2912 messages immediately, or converts them into Emacs input events and
2913 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2914 them and process them when read_char and its callers require
2915 input.
2916
2917 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2918 select(2) takes the place of w32_read_socket.
2919
2920 */
2921
2922 /* Main message dispatch loop. */
2923
2924 static void
2925 w32_msg_pump (deferred_msg * msg_buf)
2926 {
2927 MSG msg;
2928 WPARAM result;
2929 HWND focus_window;
2930
2931 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2932
2933 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2934 {
2935
2936 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2937 /* w32_name_of_message (msg.message), msg.time)); */
2938
2939 if (msg.hwnd == NULL)
2940 {
2941 switch (msg.message)
2942 {
2943 case WM_NULL:
2944 /* Produced by complete_deferred_msg; just ignore. */
2945 break;
2946 case WM_EMACS_CREATEWINDOW:
2947 /* Initialize COM for this window. Even though we don't use it,
2948 some third party shell extensions can cause it to be used in
2949 system dialogs, which causes a crash if it is not initialized.
2950 This is a known bug in Windows, which was fixed long ago, but
2951 the patch for XP is not publicly available until XP SP3,
2952 and older versions will never be patched. */
2953 CoInitialize (NULL);
2954 w32_createwindow ((struct frame *) msg.wParam,
2955 (int *) msg.lParam);
2956 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2957 emacs_abort ();
2958 break;
2959 case WM_EMACS_SETLOCALE:
2960 SetThreadLocale (msg.wParam);
2961 /* Reply is not expected. */
2962 break;
2963 case WM_EMACS_SETKEYBOARDLAYOUT:
2964 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2965 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2966 result, 0))
2967 emacs_abort ();
2968 break;
2969 case WM_EMACS_REGISTER_HOT_KEY:
2970 focus_window = GetFocus ();
2971 if (focus_window != NULL)
2972 RegisterHotKey (focus_window,
2973 RAW_HOTKEY_ID (msg.wParam),
2974 RAW_HOTKEY_MODIFIERS (msg.wParam),
2975 RAW_HOTKEY_VK_CODE (msg.wParam));
2976 /* Reply is not expected. */
2977 break;
2978 case WM_EMACS_UNREGISTER_HOT_KEY:
2979 focus_window = GetFocus ();
2980 if (focus_window != NULL)
2981 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2982 /* Mark item as erased. NB: this code must be
2983 thread-safe. The next line is okay because the cons
2984 cell is never made into garbage and is not relocated by
2985 GC. */
2986 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
2987 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2988 emacs_abort ();
2989 break;
2990 case WM_EMACS_TOGGLE_LOCK_KEY:
2991 {
2992 int vk_code = (int) msg.wParam;
2993 int cur_state = (GetKeyState (vk_code) & 1);
2994 int new_state = msg.lParam;
2995
2996 if (new_state == -1
2997 || ((new_state & 1) != cur_state))
2998 {
2999 one_w32_display_info.faked_key = vk_code;
3000
3001 keybd_event ((BYTE) vk_code,
3002 (BYTE) MapVirtualKey (vk_code, 0),
3003 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3004 keybd_event ((BYTE) vk_code,
3005 (BYTE) MapVirtualKey (vk_code, 0),
3006 KEYEVENTF_EXTENDEDKEY | 0, 0);
3007 keybd_event ((BYTE) vk_code,
3008 (BYTE) MapVirtualKey (vk_code, 0),
3009 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3010 cur_state = !cur_state;
3011 }
3012 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3013 cur_state, 0))
3014 emacs_abort ();
3015 }
3016 break;
3017 #ifdef MSG_DEBUG
3018 /* Broadcast messages make it here, so you need to be looking
3019 for something in particular for this to be useful. */
3020 default:
3021 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3022 #endif
3023 }
3024 }
3025 else
3026 {
3027 if (w32_unicode_gui)
3028 DispatchMessageW (&msg);
3029 else
3030 DispatchMessageA (&msg);
3031 }
3032
3033 /* Exit nested loop when our deferred message has completed. */
3034 if (msg_buf->completed)
3035 break;
3036 }
3037 }
3038
3039 deferred_msg * deferred_msg_head;
3040
3041 static deferred_msg *
3042 find_deferred_msg (HWND hwnd, UINT msg)
3043 {
3044 deferred_msg * item;
3045
3046 /* Don't actually need synchronization for read access, since
3047 modification of single pointer is always atomic. */
3048 /* enter_crit (); */
3049
3050 for (item = deferred_msg_head; item != NULL; item = item->next)
3051 if (item->w32msg.msg.hwnd == hwnd
3052 && item->w32msg.msg.message == msg)
3053 break;
3054
3055 /* leave_crit (); */
3056
3057 return item;
3058 }
3059
3060 static LRESULT
3061 send_deferred_msg (deferred_msg * msg_buf,
3062 HWND hwnd,
3063 UINT msg,
3064 WPARAM wParam,
3065 LPARAM lParam)
3066 {
3067 /* Only input thread can send deferred messages. */
3068 if (GetCurrentThreadId () != dwWindowsThreadId)
3069 emacs_abort ();
3070
3071 /* It is an error to send a message that is already deferred. */
3072 if (find_deferred_msg (hwnd, msg) != NULL)
3073 emacs_abort ();
3074
3075 /* Enforced synchronization is not needed because this is the only
3076 function that alters deferred_msg_head, and the following critical
3077 section is guaranteed to only be serially reentered (since only the
3078 input thread can call us). */
3079
3080 /* enter_crit (); */
3081
3082 msg_buf->completed = 0;
3083 msg_buf->next = deferred_msg_head;
3084 deferred_msg_head = msg_buf;
3085 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3086
3087 /* leave_crit (); */
3088
3089 /* Start a new nested message loop to process other messages until
3090 this one is completed. */
3091 w32_msg_pump (msg_buf);
3092
3093 deferred_msg_head = msg_buf->next;
3094
3095 return msg_buf->result;
3096 }
3097
3098 void
3099 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3100 {
3101 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3102
3103 if (msg_buf == NULL)
3104 /* Message may have been canceled, so don't abort. */
3105 return;
3106
3107 msg_buf->result = result;
3108 msg_buf->completed = 1;
3109
3110 /* Ensure input thread is woken so it notices the completion. */
3111 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3112 }
3113
3114 static void
3115 cancel_all_deferred_msgs (void)
3116 {
3117 deferred_msg * item;
3118
3119 /* Don't actually need synchronization for read access, since
3120 modification of single pointer is always atomic. */
3121 /* enter_crit (); */
3122
3123 for (item = deferred_msg_head; item != NULL; item = item->next)
3124 {
3125 item->result = 0;
3126 item->completed = 1;
3127 }
3128
3129 /* leave_crit (); */
3130
3131 /* Ensure input thread is woken so it notices the completion. */
3132 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3133 }
3134
3135 DWORD WINAPI w32_msg_worker (void *);
3136
3137 DWORD WINAPI
3138 w32_msg_worker (void *arg)
3139 {
3140 MSG msg;
3141 deferred_msg dummy_buf;
3142
3143 /* Ensure our message queue is created */
3144
3145 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3146
3147 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3148 emacs_abort ();
3149
3150 memset (&dummy_buf, 0, sizeof (dummy_buf));
3151 dummy_buf.w32msg.msg.hwnd = NULL;
3152 dummy_buf.w32msg.msg.message = WM_NULL;
3153
3154 /* This is the initial message loop which should only exit when the
3155 application quits. */
3156 w32_msg_pump (&dummy_buf);
3157
3158 return 0;
3159 }
3160
3161 static void
3162 signal_user_input (void)
3163 {
3164 /* Interrupt any lisp that wants to be interrupted by input. */
3165 if (!NILP (Vthrow_on_input))
3166 {
3167 Vquit_flag = Vthrow_on_input;
3168 /* Doing a QUIT from this thread is a bad idea, since this
3169 unwinds the stack of the Lisp thread, and the Windows runtime
3170 rightfully barfs. Disabled. */
3171 #if 0
3172 /* If we're inside a function that wants immediate quits,
3173 do it now. */
3174 if (immediate_quit && NILP (Vinhibit_quit))
3175 {
3176 immediate_quit = 0;
3177 QUIT;
3178 }
3179 #endif
3180 }
3181 }
3182
3183
3184 static void
3185 post_character_message (HWND hwnd, UINT msg,
3186 WPARAM wParam, LPARAM lParam,
3187 DWORD modifiers)
3188 {
3189 W32Msg wmsg;
3190
3191 wmsg.dwModifiers = modifiers;
3192
3193 /* Detect quit_char and set quit-flag directly. Note that we
3194 still need to post a message to ensure the main thread will be
3195 woken up if blocked in sys_select, but we do NOT want to post
3196 the quit_char message itself (because it will usually be as if
3197 the user had typed quit_char twice). Instead, we post a dummy
3198 message that has no particular effect. */
3199 {
3200 int c = wParam;
3201 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
3202 c = make_ctrl_char (c) & 0377;
3203 if (c == quit_char
3204 || (wmsg.dwModifiers == 0
3205 && w32_quit_key && wParam == w32_quit_key))
3206 {
3207 Vquit_flag = Qt;
3208
3209 /* The choice of message is somewhat arbitrary, as long as
3210 the main thread handler just ignores it. */
3211 msg = WM_NULL;
3212
3213 /* Interrupt any blocking system calls. */
3214 signal_quit ();
3215
3216 /* As a safety precaution, forcibly complete any deferred
3217 messages. This is a kludge, but I don't see any particularly
3218 clean way to handle the situation where a deferred message is
3219 "dropped" in the lisp thread, and will thus never be
3220 completed, eg. by the user trying to activate the menubar
3221 when the lisp thread is busy, and then typing C-g when the
3222 menubar doesn't open promptly (with the result that the
3223 menubar never responds at all because the deferred
3224 WM_INITMENU message is never completed). Another problem
3225 situation is when the lisp thread calls SendMessage (to send
3226 a window manager command) when a message has been deferred;
3227 the lisp thread gets blocked indefinitely waiting for the
3228 deferred message to be completed, which itself is waiting for
3229 the lisp thread to respond.
3230
3231 Note that we don't want to block the input thread waiting for
3232 a response from the lisp thread (although that would at least
3233 solve the deadlock problem above), because we want to be able
3234 to receive C-g to interrupt the lisp thread. */
3235 cancel_all_deferred_msgs ();
3236 }
3237 else
3238 signal_user_input ();
3239 }
3240
3241 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3242 }
3243
3244 static int
3245 get_wm_chars (HWND aWnd, int *buf, int buflen, int ignore_ctrl, int ctrl,
3246 int *ctrl_cnt, int *is_dead, int vk, int exp)
3247 {
3248 MSG msg;
3249 /* If doubled is at the end, ignore it. */
3250 int i = buflen, doubled = 0, code_unit;
3251
3252 if (ctrl_cnt)
3253 *ctrl_cnt = 0;
3254 if (is_dead)
3255 *is_dead = -1;
3256 eassert (w32_unicode_gui);
3257 while (buflen
3258 /* Should be called only when w32_unicode_gui: */
3259 && PeekMessageW (&msg, aWnd, WM_KEYFIRST, WM_KEYLAST,
3260 PM_NOREMOVE | PM_NOYIELD)
3261 && (msg.message == WM_CHAR || msg.message == WM_SYSCHAR
3262 || msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR
3263 || msg.message == WM_UNICHAR))
3264 {
3265 /* We extract character payload, but in this call we handle only the
3266 characters which come BEFORE the next keyup/keydown message. */
3267 int dead;
3268
3269 GetMessageW (&msg, aWnd, msg.message, msg.message);
3270 dead = (msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR);
3271 if (is_dead)
3272 *is_dead = (dead ? msg.wParam : -1);
3273 if (dead)
3274 continue;
3275 code_unit = msg.wParam;
3276 if (doubled)
3277 {
3278 /* Had surrogate. */
3279 if (msg.message == WM_UNICHAR
3280 || code_unit < 0xDC00 || code_unit > 0xDFFF)
3281 { /* Mismatched first surrogate.
3282 Pass both code units as if they were two characters. */
3283 *buf++ = doubled;
3284 if (!--buflen)
3285 return i; /* Drop the 2nd char if at the end of the buffer. */
3286 }
3287 else /* see https://en.wikipedia.org/wiki/UTF-16 */
3288 code_unit = (doubled << 10) + code_unit - 0x35FDC00;
3289 doubled = 0;
3290 }
3291 else if (code_unit >= 0xD800 && code_unit <= 0xDBFF)
3292 {
3293 /* Handle mismatched 2nd surrogate the same as a normal character. */
3294 doubled = code_unit;
3295 continue;
3296 }
3297
3298 /* The only "fake" characters delivered by ToUnicode() or
3299 TranslateMessage() are:
3300 0x01 .. 0x1a for Ctrl-letter, Enter, Tab, Ctrl-Break, Esc, Backspace
3301 0x00 and 0x1b .. 0x1f for Control- []\@^_
3302 0x7f for Control-BackSpace
3303 0x20 for Control-Space */
3304 if (ignore_ctrl
3305 && (code_unit < 0x20 || code_unit == 0x7f
3306 || (code_unit == 0x20 && ctrl)))
3307 {
3308 /* Non-character payload in a WM_CHAR
3309 (Ctrl-something pressed, see above). Ignore, and report. */
3310 if (ctrl_cnt)
3311 (*ctrl_cnt)++;
3312 continue;
3313 }
3314 /* Traditionally, Emacs would ignore the character payload of VK_NUMPAD*
3315 keys, and would treat them later via `function-key-map'. In addition
3316 to usual 102-key NUMPAD keys, this map also treats `kp-'-variants of
3317 space, tab, enter, separator, equal. TAB and EQUAL, apparently,
3318 cannot be generated on Win-GUI branch. ENTER is already handled
3319 by the code above. According to `lispy_function_keys', kp_space is
3320 generated by not-extended VK_CLEAR. (kp-tab != VK_OEM_NEC_EQUAL!).
3321
3322 We do similarly for backward-compatibility, but ignore only the
3323 characters restorable later by `function-key-map'. */
3324 if (code_unit < 0x7f
3325 && ((vk >= VK_NUMPAD0 && vk <= VK_DIVIDE)
3326 || (exp && ((vk >= VK_PRIOR && vk <= VK_DOWN) ||
3327 vk == VK_INSERT || vk == VK_DELETE || vk == VK_CLEAR)))
3328 && strchr ("0123456789/*-+.,", code_unit))
3329 continue;
3330 *buf++ = code_unit;
3331 buflen--;
3332 }
3333 return i - buflen;
3334 }
3335
3336 #ifdef DBG_WM_CHARS
3337 # define FPRINTF_WM_CHARS(ARG) fprintf ARG
3338 #else
3339 # define FPRINTF_WM_CHARS(ARG) (void)0
3340 #endif
3341
3342 /* This is a heuristic only. This is supposed to track the state of the
3343 finite automaton in the language environment of Windows.
3344
3345 However, separate windows (if with the same different language
3346 environments!) should have different values. Moreover, switching to a
3347 non-Emacs window with the same language environment, and using (dead)keys
3348 there would change the value stored in the kernel, but not this value. */
3349 /* A layout may emit deadkey=0. It looks like this would reset the state
3350 of the kernel's finite automaton (equivalent to emiting 0-length string,
3351 which is otherwise impossible in the dead-key map of a layout).
3352 Be ready to treat the case when this delivers WM_(SYS)DEADCHAR. */
3353 static int after_deadkey = -1;
3354
3355 static int
3356 deliver_wm_chars (int do_translate, HWND hwnd, UINT msg, UINT wParam,
3357 UINT lParam, int legacy_alt_meta)
3358 {
3359 /* An "old style" keyboard description may assign up to 125 UTF-16 code
3360 points to a keypress.
3361 (However, the "old style" TranslateMessage() would deliver at most 16 of
3362 them.) Be on a safe side, and prepare to treat many more. */
3363 int ctrl_cnt, buf[1024], count, is_dead, after_dead = (after_deadkey > 0);
3364
3365 /* Since the keypress processing logic of Windows has a lot of state, it
3366 is important to call TranslateMessage() for every keyup/keydown, AND
3367 do it exactly once. (The actual change of state is done by
3368 ToUnicode[Ex](), which is called by TranslateMessage(). So one can
3369 call ToUnicode[Ex]() instead.)
3370
3371 The "usual" message pump calls TranslateMessage() for EVERY event.
3372 Emacs calls TranslateMessage() very selectively (is it needed for doing
3373 some tricky stuff with Win95??? With newer Windows, selectiveness is,
3374 most probably, not needed -- and harms a lot).
3375
3376 So, with the usual message pump, the following call to TranslateMessage()
3377 is not needed (and is going to be VERY harmful). With Emacs' message
3378 pump, the call is needed. */
3379 if (do_translate)
3380 {
3381 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3382
3383 windows_msg.time = GetMessageTime ();
3384 TranslateMessage (&windows_msg);
3385 }
3386 count = get_wm_chars (hwnd, buf, sizeof (buf)/sizeof (*buf), 1,
3387 /* The message may have been synthesized by
3388 who knows what; be conservative. */
3389 modifier_set (VK_LCONTROL)
3390 || modifier_set (VK_RCONTROL)
3391 || modifier_set (VK_CONTROL),
3392 &ctrl_cnt, &is_dead, wParam,
3393 (lParam & 0x1000000L) != 0);
3394 if (count)
3395 {
3396 W32Msg wmsg;
3397 DWORD console_modifiers = construct_console_modifiers ();
3398 int *b = buf, strip_ExtraMods = 1, hairy = 0;
3399 const char *type_CtrlAlt = NULL;
3400
3401 /* XXXX In fact, there may be another case when we need to do the same:
3402 What happens if the string defined in the LIGATURES has length
3403 0? Probably, we will get count==0, but the state of the finite
3404 automaton would reset to 0??? */
3405 after_deadkey = -1;
3406
3407 /* wParam is checked when converting CapsLock to Shift; this is a clone
3408 of w32_get_key_modifiers (). */
3409 wmsg.dwModifiers = w32_kbd_mods_to_emacs (console_modifiers, wParam);
3410
3411 /* What follows is just heuristics; the correct treatement requires
3412 non-destructive ToUnicode():
3413 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Can_an_application_on_Windows_accept_keyboard_events?_Part_IV:_application-specific_modifiers
3414
3415 What one needs to find is:
3416 * which of the present modifiers AFFECT the resulting char(s)
3417 (so should be stripped, since their EFFECT is "already
3418 taken into account" in the string in buf), and
3419 * which modifiers are not affecting buf, so should be reported to
3420 the application for further treatment.
3421
3422 Example: assume that we know:
3423 (A) lCtrl+rCtrl+rAlt modifiers with VK_A key produce a Latin "f"
3424 ("may be logical" in JCUKEN-flavored Russian keyboard flavors);
3425 (B) removing any of lCtrl, rCtrl, rAlt changes the produced char;
3426 (C) Win-modifier is not affecting the produced character
3427 (this is the common case: happens with all "standard" layouts).
3428
3429 Suppose the user presses Win+lCtrl+rCtrl+rAlt modifiers with VK_A.
3430 What is the intent of the user? We need to guess the intent to decide
3431 which event to deliver to the application.
3432
3433 This looks like a reasonable logic: since Win- modifier doesn't affect
3434 the output string, the user was pressing Win for SOME OTHER purpose.
3435 So the user wanted to generate Win-SOMETHING event. Now, what is
3436 something? If one takes the mantra that "character payload is more
3437 important than the combination of keypresses which resulted in this
3438 payload", then one should ignore lCtrl+rCtrl+rAlt, ignore VK_A, and
3439 assume that the user wanted to generate Win-f.
3440
3441 Unfortunately, without non-destructive ToUnicode(), checking (B),(C)
3442 is out of question. So we use heuristics (hopefully, covering
3443 99.9999% of cases). */
3444
3445 /* Another thing to watch for is a possibility to use AltGr-* and
3446 Ctrl-Alt-* with different semantic.
3447
3448 Background: the layout defining the KLLF_ALTGR bit are treated
3449 specially by the kernel: when VK_RMENU (=rightAlt, =AltGr) is pressed
3450 (released), a press (release) of VK_LCONTROL is emulated (unless Ctrl
3451 is already down). As a result, any press/release of AltGr is seen
3452 by applications as a press/release of lCtrl AND rAlt. This is
3453 applicable, in particular, to ToUnicode[Ex](). (Keyrepeat is covered
3454 the same way!)
3455
3456 NOTE: it IS possible to see bare rAlt even with KLLF_ALTGR; but this
3457 requires a good finger coordination: doing (physically)
3458 Down-lCtrl Down-rAlt Up-lCtrl Down-a
3459 (doing quick enough, so that key repeat of rAlt [which would
3460 generate new "fake" Down-lCtrl events] does not happens before 'a'
3461 is down) results in no "fake" events, so the application will see
3462 only rAlt down when 'a' is pressed. (However, fake Up-lCtrl WILL
3463 be generated when rAlt goes UP.)
3464
3465 In fact, note also that KLLF_ALTGR does not prohibit construction of
3466 rCtrl-rAlt (just press them in this order!).
3467
3468 Moreover: "traditional" layouts do not define distinct modifier-masks
3469 for VK_LMENU and VK_RMENU (same for VK_L/RCONTROL). Instead, they
3470 rely on the KLLF_ALTGR bit to make the behavior of VK_LMENU and
3471 VK_RMENU distinct. As a corollary, for such layouts, the produced
3472 character is the same for AltGr-* (=rAlt-*) and Ctrl-Alt-* (in any
3473 combination of handedness). For description of masks, see
3474
3475 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Keyboard_input_on_Windows,_Part_I:_what_is_the_kernel_doing?
3476
3477 By default, Emacs was using these coincidences via the following
3478 heuristics: it was treating:
3479 (*) keypresses with lCtrl-rAlt modifiers as if they are carrying
3480 ONLY the character payload (no matter what the actual keyboard
3481 was defining: if lCtrl-lAlt-b was delivering U+05df=beta, then
3482 Emacs saw [beta]; if lCtrl-lAlt-b was undefined in the layout,
3483 the keypress was completely ignored), and
3484 (*) keypresses with the other combinations of handedness of Ctrl-Alt
3485 modifiers (e.g., lCtrl-lAlt) as if they NEVER carry a character
3486 payload (so they were reported "raw": if lCtrl-lAlt-b was
3487 delivering beta, then Emacs saw event [C-A-b], and not [beta]).
3488 This worked good for "traditional" layouts: users could type both
3489 AltGr-x and Ctrl-Alt-x, and one was a character, another a bindable
3490 event.
3491
3492 However, for layouts which deliver different characters for AltGr-x
3493 and lCtrl-lAlt-x, this scheme makes the latter character unaccessible
3494 in Emacs. While it is easy to access functionality of [C-M-x] in
3495 Emacs by other means (for example, by the `controlify' prefix, or
3496 using lCtrl-rCtrl-x, or rCtrl-rAlt-x [in this order]), missing
3497 characters cannot be reconstructed without a tedious manual work. */
3498
3499 /* These two cases are often going to be distinguishable, since at most
3500 one of these character is defined with KBDCTRL | KBDMENU modifier
3501 bitmap. (This heuristic breaks if both lCtrl-lAlt- AND lCtrl-rAlt-
3502 are translated to modifier bitmaps distinct from KBDCTRL | KBDMENU,
3503 or in the cases when lCtrl-lAlt-* and lCtrl-rAlt-* are generally
3504 different, but lCtrl-lAlt-x and lCtrl-rAlt-x happen to deliver the
3505 same character.)
3506
3507 So we have 2 chunks of info:
3508 (A) is it lCtrl-rAlt-, or lCtrl-lAlt, or some other combination?
3509 (B) is the delivered character defined with KBDCTRL | KBDMENU bits?
3510 Basing on (A) and (B), we should decide whether to ignore the
3511 delivered character. (Before, Emacs was completely ignoring (B), and
3512 was treating the 3-state of (A) as a bit.) This means that we have 6
3513 bits of customization.
3514
3515 Additionally, a presence of two Ctrl down may be AltGr-rCtrl-. */
3516
3517 /* Strip all non-Shift modifiers if:
3518 - more than one UTF-16 code point delivered (can't call VkKeyScanW ())
3519 - or the character is a result of combining with a prefix key. */
3520 if (!after_dead && count == 1 && *b < 0x10000)
3521 {
3522 if (console_modifiers & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
3523 && console_modifiers & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
3524 {
3525 type_CtrlAlt = "bB"; /* generic bindable Ctrl-Alt- modifiers */
3526 if ((console_modifiers & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3527 == (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3528 /* double-Ctrl:
3529 e.g. AltGr-rCtrl on some layouts (in this order!) */
3530 type_CtrlAlt = "dD";
3531 else if ((console_modifiers
3532 & (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3533 == (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3534 type_CtrlAlt = "lL"; /* Ctrl-Alt- modifiers on the left */
3535 else if (!NILP (Vw32_recognize_altgr)
3536 && ((console_modifiers
3537 & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)))
3538 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
3539 type_CtrlAlt = "gG"; /* modifiers as in AltGr */
3540 }
3541 else if (wmsg.dwModifiers & (alt_modifier | meta_modifier)
3542 || ((console_modifiers
3543 & (LEFT_WIN_PRESSED | RIGHT_WIN_PRESSED
3544 | APPS_PRESSED | SCROLLLOCK_ON))))
3545 {
3546 /* Pure Alt (or combination of Alt, Win, APPS, scrolllock. */
3547 type_CtrlAlt = "aA";
3548 }
3549 if (type_CtrlAlt)
3550 {
3551 /* Out of bound bitmap: */
3552 SHORT r = VkKeyScanW (*b), bitmap = 0x1FF;
3553
3554 FPRINTF_WM_CHARS((stderr, "VkKeyScanW %#06x %#04x\n", (int)r,
3555 wParam));
3556 if ((r & 0xFF) == wParam)
3557 bitmap = r>>8; /* *b is reachable via simple interface */
3558 else
3559 {
3560 /* VkKeyScanW() (essentially) returns the FIRST key with
3561 the specified character; so here the pressed key is the
3562 SECONDARY key producing the character.
3563
3564 Essentially, we have no information about the "role" of
3565 modifiers on this key: which contribute into the
3566 produced character (so "are consumed"), and which are
3567 "extra" (must attache to bindable events).
3568
3569 The default above would consume ALL modifiers, so the
3570 character is reported "as is". However, on many layouts
3571 the ordering of the keys (in the layout table) is not
3572 thought out well, so the "secondary" keys are often those
3573 which the users would prefer to use with Alt-CHAR.
3574 (Moreover - with e.g. Czech-QWERTY - the ASCII
3575 punctuation is accessible from two equally [nu]preferable
3576 AltGr-keys.)
3577
3578 SO: Heuristic: if the reported char is ASCII, AND Meta
3579 modifier is a candidate, behave as if Meta is present
3580 (fallback to the legacy branch; bug#23251).
3581
3582 (This would break layouts
3583 - delivering ASCII characters
3584 - on SECONDARY keys
3585 - with not Shift/AltGr-like modifier combinations.
3586 All 3 conditions together must be pretty exotic
3587 cases - and a workaround exists: use "primary" keys!) */
3588 if (*b < 0x80
3589 && (wmsg.dwModifiers
3590 & (alt_modifier | meta_modifier
3591 | super_modifier | hyper_modifier)))
3592 return 0;
3593 }
3594 if (*type_CtrlAlt == 'a') /* Simple Alt seen */
3595 {
3596 if ((bitmap & ~1) == 0) /* 1: KBDSHIFT */
3597 {
3598 /* In "traditional" layouts, Alt without Ctrl does not
3599 change the delivered character. This detects this
3600 situation; it is safe to report this as Alt-something
3601 -- as opposed to delivering the reported character
3602 without modifiers. */
3603 if (legacy_alt_meta
3604 && *b > 0x7f && ('A' <= wParam && wParam <= 'Z'))
3605 /* For backward-compatibility with older Emacsen, let
3606 this be processed by another branch below (which
3607 would convert it to Alt-Latin char via wParam). */
3608 return 0;
3609 }
3610 else
3611 hairy = 1;
3612 }
3613 /* Check whether the delivered character(s) is accessible via
3614 KBDCTRL | KBDALT ( | KBDSHIFT ) modifier mask (which is 7). */
3615 else if ((bitmap & ~1) != 6)
3616 {
3617 /* The character is not accessible via plain Ctrl-Alt(-Shift)
3618 (which is, probably, same as AltGr) modifiers.
3619 Either it was after a prefix key, or is combined with
3620 modifier keys which we don't see, or there is an asymmetry
3621 between left-hand and right-hand modifiers, or other hairy
3622 stuff. */
3623 hairy = 1;
3624 }
3625 /* The best solution is to delegate these tough (but rarely
3626 needed) choices to the user. Temporarily (???), it is
3627 implemented as C macros.
3628
3629 Essentially, there are 3 things to do: return 0 (handle to the
3630 legacy processing code [ignoring the character payload]; keep
3631 some modifiers (so that they will be processed by the binding
3632 system [on top of the character payload]; strip modifiers [so
3633 that `self-insert' is going to be triggered with the character
3634 payload]).
3635
3636 The default below should cover 99.9999% of cases:
3637 (a) strip Alt- in the hairy case only;
3638 (stripping = not ignoring)
3639 (l) for lAlt-lCtrl, ignore the char in simple cases only;
3640 (g) for what looks like AltGr, ignore the modifiers;
3641 (d) for what looks like lCtrl-rCtrl-Alt (probably
3642 AltGr-rCtrl), ignore the character in simple cases only;
3643 (b) for other cases of Ctrl-Alt, ignore the character in
3644 simple cases only.
3645
3646 Essentially, in all hairy cases, and in looks-like-AltGr case,
3647 we keep the character, ignoring the modifiers. In all the
3648 other cases, we ignore the delivered character. */
3649 #define S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD "aldb"
3650 #define S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS ""
3651 if (strchr (S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD,
3652 type_CtrlAlt[hairy]))
3653 return 0;
3654 /* If in neither list, report all the modifiers we see COMBINED
3655 WITH the reported character. */
3656 if (strchr (S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS,
3657 type_CtrlAlt[hairy]))
3658 strip_ExtraMods = 0;
3659 }
3660 }
3661 if (strip_ExtraMods)
3662 wmsg.dwModifiers = wmsg.dwModifiers & shift_modifier;
3663
3664 signal_user_input ();
3665 while (count--)
3666 {
3667 FPRINTF_WM_CHARS((stderr, "unichar %#06x\n", *b));
3668 my_post_msg (&wmsg, hwnd, WM_UNICHAR, *b++, lParam);
3669 }
3670 if (!ctrl_cnt) /* Process ALSO as ctrl */
3671 return 1;
3672 else
3673 FPRINTF_WM_CHARS((stderr, "extra ctrl char\n"));
3674 return -1;
3675 }
3676 else if (is_dead >= 0)
3677 {
3678 FPRINTF_WM_CHARS((stderr, "dead %#06x\n", is_dead));
3679 after_deadkey = is_dead;
3680 return 1;
3681 }
3682 return 0;
3683 }
3684
3685 /* Main window procedure */
3686
3687 static LRESULT CALLBACK
3688 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
3689 {
3690 struct frame *f;
3691 struct w32_display_info *dpyinfo = &one_w32_display_info;
3692 W32Msg wmsg;
3693 int windows_translate;
3694 int key;
3695
3696 /* Note that it is okay to call x_window_to_frame, even though we are
3697 not running in the main lisp thread, because frame deletion
3698 requires the lisp thread to synchronize with this thread. Thus, if
3699 a frame struct is returned, it can be used without concern that the
3700 lisp thread might make it disappear while we are using it.
3701
3702 NB. Walking the frame list in this thread is safe (as long as
3703 writes of Lisp_Object slots are atomic, which they are on Windows).
3704 Although delete-frame can destructively modify the frame list while
3705 we are walking it, a garbage collection cannot occur until after
3706 delete-frame has synchronized with this thread.
3707
3708 It is also safe to use functions that make GDI calls, such as
3709 w32_clear_rect, because these functions must obtain a DC handle
3710 from the frame struct using get_frame_dc which is thread-aware. */
3711
3712 switch (msg)
3713 {
3714 case WM_ERASEBKGND:
3715 f = x_window_to_frame (dpyinfo, hwnd);
3716 if (f)
3717 {
3718 HDC hdc = get_frame_dc (f);
3719 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
3720 w32_clear_rect (f, hdc, &wmsg.rect);
3721 release_frame_dc (f, hdc);
3722
3723 #if defined (W32_DEBUG_DISPLAY)
3724 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
3725 f,
3726 wmsg.rect.left, wmsg.rect.top,
3727 wmsg.rect.right, wmsg.rect.bottom));
3728 #endif /* W32_DEBUG_DISPLAY */
3729 }
3730 return 1;
3731 case WM_PALETTECHANGED:
3732 /* ignore our own changes */
3733 if ((HWND)wParam != hwnd)
3734 {
3735 f = x_window_to_frame (dpyinfo, hwnd);
3736 if (f)
3737 /* get_frame_dc will realize our palette and force all
3738 frames to be redrawn if needed. */
3739 release_frame_dc (f, get_frame_dc (f));
3740 }
3741 return 0;
3742 case WM_PAINT:
3743 {
3744 PAINTSTRUCT paintStruct;
3745 RECT update_rect;
3746 memset (&update_rect, 0, sizeof (update_rect));
3747
3748 f = x_window_to_frame (dpyinfo, hwnd);
3749 if (f == 0)
3750 {
3751 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
3752 return 0;
3753 }
3754
3755 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
3756 fails. Apparently this can happen under some
3757 circumstances. */
3758 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
3759 {
3760 enter_crit ();
3761 BeginPaint (hwnd, &paintStruct);
3762
3763 /* The rectangles returned by GetUpdateRect and BeginPaint
3764 do not always match. Play it safe by assuming both areas
3765 are invalid. */
3766 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
3767
3768 #if defined (W32_DEBUG_DISPLAY)
3769 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
3770 f,
3771 wmsg.rect.left, wmsg.rect.top,
3772 wmsg.rect.right, wmsg.rect.bottom));
3773 DebPrint ((" [update region is %d,%d-%d,%d]\n",
3774 update_rect.left, update_rect.top,
3775 update_rect.right, update_rect.bottom));
3776 #endif
3777 EndPaint (hwnd, &paintStruct);
3778 leave_crit ();
3779
3780 /* Change the message type to prevent Windows from
3781 combining WM_PAINT messages in the Lisp thread's queue,
3782 since Windows assumes that each message queue is
3783 dedicated to one frame and does not bother checking
3784 that hwnd matches before combining them. */
3785 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
3786
3787 return 0;
3788 }
3789
3790 /* If GetUpdateRect returns 0 (meaning there is no update
3791 region), assume the whole window needs to be repainted. */
3792 GetClientRect (hwnd, &wmsg.rect);
3793 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3794 return 0;
3795 }
3796
3797 case WM_INPUTLANGCHANGE:
3798 /* Inform lisp thread of keyboard layout changes. */
3799 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3800
3801 /* The state of the finite automaton is separate per every input
3802 language environment (so it does not change when one switches
3803 to a different window with the same environment). Moreover,
3804 the experiments show that the state is not remembered when
3805 one switches back to the pre-previous environment. */
3806 after_deadkey = -1;
3807
3808 /* XXXX??? What follows is a COMPLETE misunderstanding of Windows! */
3809
3810 /* Clear dead keys in the keyboard state; for simplicity only
3811 preserve modifier key states. */
3812 {
3813 int i;
3814 BYTE keystate[256];
3815
3816 GetKeyboardState (keystate);
3817 for (i = 0; i < 256; i++)
3818 if (1
3819 && i != VK_SHIFT
3820 && i != VK_LSHIFT
3821 && i != VK_RSHIFT
3822 && i != VK_CAPITAL
3823 && i != VK_NUMLOCK
3824 && i != VK_SCROLL
3825 && i != VK_CONTROL
3826 && i != VK_LCONTROL
3827 && i != VK_RCONTROL
3828 && i != VK_MENU
3829 && i != VK_LMENU
3830 && i != VK_RMENU
3831 && i != VK_LWIN
3832 && i != VK_RWIN)
3833 keystate[i] = 0;
3834 SetKeyboardState (keystate);
3835 }
3836 goto dflt;
3837
3838 case WM_HOTKEY:
3839 /* Synchronize hot keys with normal input. */
3840 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3841 return (0);
3842
3843 case WM_KEYUP:
3844 case WM_SYSKEYUP:
3845 record_keyup (wParam, lParam);
3846 goto dflt;
3847
3848 case WM_KEYDOWN:
3849 case WM_SYSKEYDOWN:
3850 /* Ignore keystrokes we fake ourself; see below. */
3851 if (dpyinfo->faked_key == wParam)
3852 {
3853 dpyinfo->faked_key = 0;
3854 /* Make sure TranslateMessage sees them though (as long as
3855 they don't produce WM_CHAR messages). This ensures that
3856 indicator lights are toggled promptly on Windows 9x, for
3857 example. */
3858 if (wParam < 256 && lispy_function_keys[wParam])
3859 {
3860 windows_translate = 1;
3861 goto translate;
3862 }
3863 return 0;
3864 }
3865
3866 /* Synchronize modifiers with current keystroke. */
3867 sync_modifiers ();
3868 record_keydown (wParam, lParam);
3869 if (w32_use_fallback_wm_chars_method)
3870 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3871
3872 windows_translate = 0;
3873
3874 switch (wParam)
3875 {
3876 case VK_LWIN:
3877 if (!w32_kbdhook_active && NILP (Vw32_pass_lwindow_to_system))
3878 {
3879 /* Prevent system from acting on keyup (which opens the
3880 Start menu if no other key was pressed) by simulating a
3881 press of Space which we will ignore. */
3882 if (GetAsyncKeyState (wParam) & 1)
3883 {
3884 if (NUMBERP (Vw32_phantom_key_code))
3885 key = XUINT (Vw32_phantom_key_code) & 255;
3886 else
3887 key = VK_SPACE;
3888 dpyinfo->faked_key = key;
3889 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3890 }
3891 }
3892 if (!NILP (Vw32_lwindow_modifier))
3893 return 0;
3894 break;
3895 case VK_RWIN:
3896 if (!w32_kbdhook_active && NILP (Vw32_pass_rwindow_to_system))
3897 {
3898 if (GetAsyncKeyState (wParam) & 1)
3899 {
3900 if (NUMBERP (Vw32_phantom_key_code))
3901 key = XUINT (Vw32_phantom_key_code) & 255;
3902 else
3903 key = VK_SPACE;
3904 dpyinfo->faked_key = key;
3905 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3906 }
3907 }
3908 if (!NILP (Vw32_rwindow_modifier))
3909 return 0;
3910 break;
3911 case VK_APPS:
3912 if (!NILP (Vw32_apps_modifier))
3913 return 0;
3914 break;
3915 case VK_MENU:
3916 if (NILP (Vw32_pass_alt_to_system))
3917 /* Prevent DefWindowProc from activating the menu bar if an
3918 Alt key is pressed and released by itself. */
3919 return 0;
3920 windows_translate = 1;
3921 break;
3922 case VK_CAPITAL:
3923 /* Decide whether to treat as modifier or function key. */
3924 if (NILP (Vw32_enable_caps_lock))
3925 goto disable_lock_key;
3926 windows_translate = 1;
3927 break;
3928 case VK_NUMLOCK:
3929 /* Decide whether to treat as modifier or function key. */
3930 if (NILP (Vw32_enable_num_lock))
3931 goto disable_lock_key;
3932 windows_translate = 1;
3933 break;
3934 case VK_SCROLL:
3935 /* Decide whether to treat as modifier or function key. */
3936 if (NILP (Vw32_scroll_lock_modifier))
3937 goto disable_lock_key;
3938 windows_translate = 1;
3939 break;
3940 disable_lock_key:
3941 /* Ensure the appropriate lock key state (and indicator light)
3942 remains in the same state. We do this by faking another
3943 press of the relevant key. Apparently, this really is the
3944 only way to toggle the state of the indicator lights. */
3945 dpyinfo->faked_key = wParam;
3946 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3947 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3948 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3949 KEYEVENTF_EXTENDEDKEY | 0, 0);
3950 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3951 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3952 /* Ensure indicator lights are updated promptly on Windows 9x
3953 (TranslateMessage apparently does this), after forwarding
3954 input event. */
3955 post_character_message (hwnd, msg, wParam, lParam,
3956 w32_get_key_modifiers (wParam, lParam));
3957 windows_translate = 1;
3958 break;
3959 case VK_CONTROL:
3960 case VK_SHIFT:
3961 case VK_PROCESSKEY: /* Generated by IME. */
3962 windows_translate = 1;
3963 break;
3964 case VK_CANCEL:
3965 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3966 which is confusing for purposes of key binding; convert
3967 VK_CANCEL events into VK_PAUSE events. */
3968 wParam = VK_PAUSE;
3969 break;
3970 case VK_PAUSE:
3971 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3972 for purposes of key binding; convert these back into
3973 VK_NUMLOCK events, at least when we want to see NumLock key
3974 presses. (Note that there is never any possibility that
3975 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3976 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3977 wParam = VK_NUMLOCK;
3978 break;
3979 default:
3980 if (w32_unicode_gui && !w32_use_fallback_wm_chars_method)
3981 {
3982 /* If this event generates characters or deadkeys, do
3983 not interpret it as a "raw combination of modifiers
3984 and keysym". Hide deadkeys, and use the generated
3985 character(s) instead of the keysym. (Backward
3986 compatibility: exceptions for numpad keys generating
3987 0-9 . , / * - +, and for extra-Alt combined with a
3988 non-Latin char.)
3989
3990 Try to not report modifiers which have effect on
3991 which character or deadkey is generated.
3992
3993 Example (contrived): if rightAlt-? generates f (on a
3994 Cyrillic keyboard layout), and Ctrl, leftAlt do not
3995 affect the generated character, one wants to report
3996 Ctrl-leftAlt-f if the user presses
3997 Ctrl-leftAlt-rightAlt-?. */
3998 int res;
3999 #if 0
4000 /* Some of WM_CHAR may be fed to us directly, some are
4001 results of TranslateMessage(). Using 0 as the first
4002 argument (in a separate call) might help us
4003 distinguish these two cases.
4004
4005 However, the keypress feeders would most probably
4006 expect the "standard" message pump, when
4007 TranslateMessage() is called on EVERY KeyDown/KeyUp
4008 event. So they may feed us Down-Ctrl Down-FAKE
4009 Char-o and expect us to recognize it as Ctrl-o.
4010 Using 0 as the first argument would interfere with
4011 this. */
4012 deliver_wm_chars (0, hwnd, msg, wParam, lParam, 1);
4013 #endif
4014 /* Processing the generated WM_CHAR messages *WHILE* we
4015 handle KEYDOWN/UP event is the best choice, since
4016 without any fuss, we know all 3 of: scancode, virtual
4017 keycode, and expansion. (Additionally, one knows
4018 boundaries of expansion of different keypresses.) */
4019 res = deliver_wm_chars (1, hwnd, msg, wParam, lParam, 1);
4020 windows_translate = -(res != 0);
4021 if (res > 0) /* Bound to character(s) or a deadkey */
4022 break;
4023 /* deliver_wm_chars may make some branches after this vestigal. */
4024 }
4025 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4026 /* If not defined as a function key, change it to a WM_CHAR message. */
4027 if (wParam > 255 || !lispy_function_keys[wParam])
4028 {
4029 DWORD modifiers = construct_console_modifiers ();
4030
4031 if (!NILP (Vw32_recognize_altgr)
4032 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4033 {
4034 /* Always let TranslateMessage handle AltGr key chords;
4035 for some reason, ToAscii doesn't always process AltGr
4036 chords correctly. */
4037 windows_translate = 1;
4038 }
4039 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4040 {
4041 /* Handle key chords including any modifiers other
4042 than shift directly, in order to preserve as much
4043 modifier information as possible. */
4044 if ('A' <= wParam && wParam <= 'Z')
4045 {
4046 /* Don't translate modified alphabetic keystrokes,
4047 so the user doesn't need to constantly switch
4048 layout to type control or meta keystrokes when
4049 the normal layout translates alphabetic
4050 characters to non-ascii characters. */
4051 if (!modifier_set (VK_SHIFT))
4052 wParam += ('a' - 'A');
4053 msg = WM_CHAR;
4054 }
4055 else
4056 {
4057 /* Try to handle other keystrokes by determining the
4058 base character (ie. translating the base key plus
4059 shift modifier). */
4060 int add;
4061 KEY_EVENT_RECORD key;
4062
4063 key.bKeyDown = TRUE;
4064 key.wRepeatCount = 1;
4065 key.wVirtualKeyCode = wParam;
4066 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4067 key.uChar.AsciiChar = 0;
4068 key.dwControlKeyState = modifiers;
4069
4070 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
4071 /* 0 means an unrecognized keycode, negative means
4072 dead key. Ignore both. */
4073 while (--add >= 0)
4074 {
4075 /* Forward asciified character sequence. */
4076 post_character_message
4077 (hwnd, WM_CHAR,
4078 (unsigned char) key.uChar.AsciiChar, lParam,
4079 w32_get_key_modifiers (wParam, lParam));
4080 w32_kbd_patch_key (&key, w32_keyboard_codepage);
4081 }
4082 return 0;
4083 }
4084 }
4085 else
4086 {
4087 /* Let TranslateMessage handle everything else. */
4088 windows_translate = 1;
4089 }
4090 }
4091 }
4092
4093 if (windows_translate == -1)
4094 break;
4095 translate:
4096 if (windows_translate)
4097 {
4098 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4099 windows_msg.time = GetMessageTime ();
4100 TranslateMessage (&windows_msg);
4101 goto dflt;
4102 }
4103
4104 /* Fall through */
4105
4106 case WM_SYSCHAR:
4107 case WM_CHAR:
4108 if (wParam > 255 )
4109 {
4110 W32Msg wmsg;
4111
4112 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4113 signal_user_input ();
4114 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
4115
4116 }
4117 else
4118 post_character_message (hwnd, msg, wParam, lParam,
4119 w32_get_key_modifiers (wParam, lParam));
4120 break;
4121
4122 case WM_UNICHAR:
4123 /* WM_UNICHAR looks promising from the docs, but the exact
4124 circumstances in which TranslateMessage sends it is one of those
4125 Microsoft secret API things that EU and US courts are supposed
4126 to have put a stop to already. Spy++ shows it being sent to Notepad
4127 and other MS apps, but never to Emacs.
4128
4129 Some third party IMEs send it in accordance with the official
4130 documentation though, so handle it here.
4131
4132 UNICODE_NOCHAR is used to test for support for this message.
4133 TRUE indicates that the message is supported. */
4134 if (wParam == UNICODE_NOCHAR)
4135 return TRUE;
4136
4137 {
4138 W32Msg wmsg;
4139 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4140 signal_user_input ();
4141 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4142 }
4143 break;
4144
4145 case WM_IME_CHAR:
4146 /* If we can't get the IME result as Unicode, use default processing,
4147 which will at least allow characters decodable in the system locale
4148 get through. */
4149 if (!get_composition_string_fn)
4150 goto dflt;
4151
4152 else if (!ignore_ime_char)
4153 {
4154 wchar_t * buffer;
4155 int size, i;
4156 W32Msg wmsg;
4157 HIMC context = get_ime_context_fn (hwnd);
4158 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4159 /* Get buffer size. */
4160 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
4161 buffer = alloca (size);
4162 size = get_composition_string_fn (context, GCS_RESULTSTR,
4163 buffer, size);
4164 release_ime_context_fn (hwnd, context);
4165
4166 signal_user_input ();
4167 for (i = 0; i < size / sizeof (wchar_t); i++)
4168 {
4169 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
4170 lParam);
4171 }
4172 /* Ignore the messages for the rest of the
4173 characters in the string that was output above. */
4174 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
4175 }
4176 else
4177 ignore_ime_char--;
4178
4179 break;
4180
4181 case WM_IME_STARTCOMPOSITION:
4182 if (!set_ime_composition_window_fn)
4183 goto dflt;
4184 else
4185 {
4186 COMPOSITIONFORM form;
4187 HIMC context;
4188 struct window *w;
4189
4190 /* Implementation note: The code below does something that
4191 one shouldn't do: it accesses the window object from a
4192 separate thread, while the main (a.k.a. "Lisp") thread
4193 runs and can legitimately delete and even GC it. That is
4194 why we are extra careful not to futz with a window that
4195 is different from the one recorded when the system caret
4196 coordinates were last modified. That is also why we are
4197 careful not to move the IME window if the window
4198 described by W was deleted, as indicated by its buffer
4199 field being reset to nil. */
4200 f = x_window_to_frame (dpyinfo, hwnd);
4201 if (!(f && FRAME_LIVE_P (f)))
4202 goto dflt;
4203 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
4204 /* Punt if someone changed the frame's selected window
4205 behind our back. */
4206 if (w != w32_system_caret_window)
4207 goto dflt;
4208
4209 form.dwStyle = CFS_RECT;
4210 form.ptCurrentPos.x = w32_system_caret_x;
4211 form.ptCurrentPos.y = w32_system_caret_y;
4212
4213 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
4214 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
4215 + w32_system_caret_hdr_height);
4216 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
4217 - WINDOW_RIGHT_MARGIN_WIDTH (w)
4218 - WINDOW_RIGHT_FRINGE_WIDTH (w));
4219 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
4220 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
4221 - w32_system_caret_mode_height);
4222
4223 /* Punt if the window was deleted behind our back. */
4224 if (!BUFFERP (w->contents))
4225 goto dflt;
4226
4227 context = get_ime_context_fn (hwnd);
4228
4229 if (!context)
4230 goto dflt;
4231
4232 set_ime_composition_window_fn (context, &form);
4233 release_ime_context_fn (hwnd, context);
4234 }
4235 /* We should "goto dflt" here to pass WM_IME_STARTCOMPOSITION to
4236 DefWindowProc, so that the composition window will actually
4237 be displayed. But doing so causes trouble with displaying
4238 dialog boxes, such as the file selection dialog or font
4239 selection dialog. So something else is needed to fix the
4240 former without breaking the latter. See bug#11732. */
4241 break;
4242
4243 case WM_IME_ENDCOMPOSITION:
4244 ignore_ime_char = 0;
4245 goto dflt;
4246
4247 /* Simulate middle mouse button events when left and right buttons
4248 are used together, but only if user has two button mouse. */
4249 case WM_LBUTTONDOWN:
4250 case WM_RBUTTONDOWN:
4251 if (w32_num_mouse_buttons > 2)
4252 goto handle_plain_button;
4253
4254 {
4255 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4256 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4257
4258 if (button_state & this)
4259 return 0;
4260
4261 if (button_state == 0)
4262 SetCapture (hwnd);
4263
4264 button_state |= this;
4265
4266 if (button_state & other)
4267 {
4268 if (mouse_button_timer)
4269 {
4270 KillTimer (hwnd, mouse_button_timer);
4271 mouse_button_timer = 0;
4272
4273 /* Generate middle mouse event instead. */
4274 msg = WM_MBUTTONDOWN;
4275 button_state |= MMOUSE;
4276 }
4277 else if (button_state & MMOUSE)
4278 {
4279 /* Ignore button event if we've already generated a
4280 middle mouse down event. This happens if the
4281 user releases and press one of the two buttons
4282 after we've faked a middle mouse event. */
4283 return 0;
4284 }
4285 else
4286 {
4287 /* Flush out saved message. */
4288 post_msg (&saved_mouse_button_msg);
4289 }
4290 wmsg.dwModifiers = w32_get_modifiers ();
4291 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4292 signal_user_input ();
4293
4294 /* Clear message buffer. */
4295 saved_mouse_button_msg.msg.hwnd = 0;
4296 }
4297 else
4298 {
4299 /* Hold onto message for now. */
4300 mouse_button_timer =
4301 SetTimer (hwnd, MOUSE_BUTTON_ID,
4302 w32_mouse_button_tolerance, NULL);
4303 saved_mouse_button_msg.msg.hwnd = hwnd;
4304 saved_mouse_button_msg.msg.message = msg;
4305 saved_mouse_button_msg.msg.wParam = wParam;
4306 saved_mouse_button_msg.msg.lParam = lParam;
4307 saved_mouse_button_msg.msg.time = GetMessageTime ();
4308 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4309 }
4310 }
4311 return 0;
4312
4313 case WM_LBUTTONUP:
4314 case WM_RBUTTONUP:
4315 if (w32_num_mouse_buttons > 2)
4316 goto handle_plain_button;
4317
4318 {
4319 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4320 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4321
4322 if ((button_state & this) == 0)
4323 return 0;
4324
4325 button_state &= ~this;
4326
4327 if (button_state & MMOUSE)
4328 {
4329 /* Only generate event when second button is released. */
4330 if ((button_state & other) == 0)
4331 {
4332 msg = WM_MBUTTONUP;
4333 button_state &= ~MMOUSE;
4334
4335 if (button_state) emacs_abort ();
4336 }
4337 else
4338 return 0;
4339 }
4340 else
4341 {
4342 /* Flush out saved message if necessary. */
4343 if (saved_mouse_button_msg.msg.hwnd)
4344 {
4345 post_msg (&saved_mouse_button_msg);
4346 }
4347 }
4348 wmsg.dwModifiers = w32_get_modifiers ();
4349 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4350 signal_user_input ();
4351
4352 /* Always clear message buffer and cancel timer. */
4353 saved_mouse_button_msg.msg.hwnd = 0;
4354 KillTimer (hwnd, mouse_button_timer);
4355 mouse_button_timer = 0;
4356
4357 if (button_state == 0)
4358 ReleaseCapture ();
4359 }
4360 return 0;
4361
4362 case WM_XBUTTONDOWN:
4363 case WM_XBUTTONUP:
4364 if (w32_pass_extra_mouse_buttons_to_system)
4365 goto dflt;
4366 /* else fall through and process them. */
4367 case WM_MBUTTONDOWN:
4368 case WM_MBUTTONUP:
4369 handle_plain_button:
4370 {
4371 BOOL up;
4372 int button;
4373
4374 /* Ignore middle and extra buttons as long as the menu is active. */
4375 f = x_window_to_frame (dpyinfo, hwnd);
4376 if (f && f->output_data.w32->menubar_active)
4377 return 0;
4378
4379 if (parse_button (msg, HIWORD (wParam), &button, &up))
4380 {
4381 if (up) ReleaseCapture ();
4382 else SetCapture (hwnd);
4383 button = (button == 0) ? LMOUSE :
4384 ((button == 1) ? MMOUSE : RMOUSE);
4385 if (up)
4386 button_state &= ~button;
4387 else
4388 button_state |= button;
4389 }
4390 }
4391
4392 wmsg.dwModifiers = w32_get_modifiers ();
4393 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4394 signal_user_input ();
4395
4396 /* Need to return true for XBUTTON messages, false for others,
4397 to indicate that we processed the message. */
4398 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4399
4400 case WM_MOUSEMOVE:
4401 f = x_window_to_frame (dpyinfo, hwnd);
4402 if (f)
4403 {
4404 /* Ignore mouse movements as long as the menu is active.
4405 These movements are processed by the window manager
4406 anyway, and it's wrong to handle them as if they happened
4407 on the underlying frame. */
4408 if (f->output_data.w32->menubar_active)
4409 return 0;
4410
4411 /* If the mouse moved, and the mouse pointer is invisible,
4412 make it visible again. We do this here so as to be able
4413 to show the mouse pointer even when the main
4414 (a.k.a. "Lisp") thread is busy doing something. */
4415 static int last_x, last_y;
4416 int x = GET_X_LPARAM (lParam);
4417 int y = GET_Y_LPARAM (lParam);
4418
4419 if (f->pointer_invisible
4420 && (x != last_x || y != last_y))
4421 f->pointer_invisible = false;
4422
4423 last_x = x;
4424 last_y = y;
4425 }
4426
4427 /* If the mouse has just moved into the frame, start tracking
4428 it, so we will be notified when it leaves the frame. Mouse
4429 tracking only works under W98 and NT4 and later. On earlier
4430 versions, there is no way of telling when the mouse leaves the
4431 frame, so we just have to put up with help-echo and mouse
4432 highlighting remaining while the frame is not active. */
4433 if (track_mouse_event_fn && !track_mouse_window
4434 /* If the menu bar is active, turning on tracking of mouse
4435 movement events might send these events to the tooltip
4436 frame, if the user happens to move the mouse pointer over
4437 the tooltip. But since we don't process events for
4438 tooltip frames, this causes Windows to present a
4439 hourglass cursor, which is ugly and unexpected. So don't
4440 enable tracking mouse events in this case; they will be
4441 restarted when the menu pops down. (Confusingly, the
4442 menubar_active member of f->output_data.w32, tested
4443 above, is only set when a menu was popped up _not_ from
4444 the frame's menu bar, but via x-popup-menu.) */
4445 && !menubar_in_use)
4446 {
4447 TRACKMOUSEEVENT tme;
4448 tme.cbSize = sizeof (tme);
4449 tme.dwFlags = TME_LEAVE;
4450 tme.hwndTrack = hwnd;
4451 tme.dwHoverTime = HOVER_DEFAULT;
4452
4453 track_mouse_event_fn (&tme);
4454 track_mouse_window = hwnd;
4455 }
4456 case WM_HSCROLL:
4457 case WM_VSCROLL:
4458 if (w32_mouse_move_interval <= 0
4459 || (msg == WM_MOUSEMOVE && button_state == 0))
4460 {
4461 wmsg.dwModifiers = w32_get_modifiers ();
4462 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4463 return 0;
4464 }
4465
4466 /* Hang onto mouse move and scroll messages for a bit, to avoid
4467 sending such events to Emacs faster than it can process them.
4468 If we get more events before the timer from the first message
4469 expires, we just replace the first message. */
4470
4471 if (saved_mouse_move_msg.msg.hwnd == 0)
4472 mouse_move_timer =
4473 SetTimer (hwnd, MOUSE_MOVE_ID,
4474 w32_mouse_move_interval, NULL);
4475
4476 /* Hold onto message for now. */
4477 saved_mouse_move_msg.msg.hwnd = hwnd;
4478 saved_mouse_move_msg.msg.message = msg;
4479 saved_mouse_move_msg.msg.wParam = wParam;
4480 saved_mouse_move_msg.msg.lParam = lParam;
4481 saved_mouse_move_msg.msg.time = GetMessageTime ();
4482 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4483
4484 return 0;
4485
4486 case WM_MOUSEWHEEL:
4487 case WM_DROPFILES:
4488 wmsg.dwModifiers = w32_get_modifiers ();
4489 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4490 signal_user_input ();
4491 return 0;
4492
4493 case WM_APPCOMMAND:
4494 if (w32_pass_multimedia_buttons_to_system)
4495 goto dflt;
4496 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
4497 case WM_MOUSEHWHEEL:
4498 wmsg.dwModifiers = w32_get_modifiers ();
4499 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4500 signal_user_input ();
4501 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
4502 handled, to prevent the system trying to handle it by faking
4503 scroll bar events. */
4504 return 1;
4505
4506 case WM_TIMER:
4507 /* Flush out saved messages if necessary. */
4508 if (wParam == mouse_button_timer)
4509 {
4510 if (saved_mouse_button_msg.msg.hwnd)
4511 {
4512 post_msg (&saved_mouse_button_msg);
4513 signal_user_input ();
4514 saved_mouse_button_msg.msg.hwnd = 0;
4515 }
4516 KillTimer (hwnd, mouse_button_timer);
4517 mouse_button_timer = 0;
4518 }
4519 else if (wParam == mouse_move_timer)
4520 {
4521 if (saved_mouse_move_msg.msg.hwnd)
4522 {
4523 post_msg (&saved_mouse_move_msg);
4524 saved_mouse_move_msg.msg.hwnd = 0;
4525 }
4526 KillTimer (hwnd, mouse_move_timer);
4527 mouse_move_timer = 0;
4528 }
4529 else if (wParam == menu_free_timer)
4530 {
4531 KillTimer (hwnd, menu_free_timer);
4532 menu_free_timer = 0;
4533 f = x_window_to_frame (dpyinfo, hwnd);
4534 /* If a popup menu is active, don't wipe its strings. */
4535 if (menubar_in_use
4536 && current_popup_menu == NULL)
4537 {
4538 /* Free memory used by owner-drawn and help-echo strings. */
4539 w32_free_menu_strings (hwnd);
4540 if (f)
4541 f->output_data.w32->menubar_active = 0;
4542 menubar_in_use = 0;
4543 }
4544 }
4545 return 0;
4546
4547 case WM_NCACTIVATE:
4548 /* Windows doesn't send us focus messages when putting up and
4549 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4550 The only indication we get that something happened is receiving
4551 this message afterwards. So this is a good time to reset our
4552 keyboard modifiers' state. */
4553 reset_modifiers ();
4554 goto dflt;
4555
4556 case WM_INITMENU:
4557 button_state = 0;
4558 ReleaseCapture ();
4559 /* We must ensure menu bar is fully constructed and up to date
4560 before allowing user interaction with it. To achieve this
4561 we send this message to the lisp thread and wait for a
4562 reply (whose value is not actually needed) to indicate that
4563 the menu bar is now ready for use, so we can now return.
4564
4565 To remain responsive in the meantime, we enter a nested message
4566 loop that can process all other messages.
4567
4568 However, we skip all this if the message results from calling
4569 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4570 thread a message because it is blocked on us at this point. We
4571 set menubar_active before calling TrackPopupMenu to indicate
4572 this (there is no possibility of confusion with real menubar
4573 being active). */
4574
4575 f = x_window_to_frame (dpyinfo, hwnd);
4576 if (f
4577 && (f->output_data.w32->menubar_active
4578 /* We can receive this message even in the absence of a
4579 menubar (ie. when the system menu is activated) - in this
4580 case we do NOT want to forward the message, otherwise it
4581 will cause the menubar to suddenly appear when the user
4582 had requested it to be turned off! */
4583 || f->output_data.w32->menubar_widget == NULL))
4584 return 0;
4585
4586 {
4587 deferred_msg msg_buf;
4588
4589 /* Detect if message has already been deferred; in this case
4590 we cannot return any sensible value to ignore this. */
4591 if (find_deferred_msg (hwnd, msg) != NULL)
4592 emacs_abort ();
4593
4594 menubar_in_use = 1;
4595
4596 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4597 }
4598
4599 case WM_EXITMENULOOP:
4600 f = x_window_to_frame (dpyinfo, hwnd);
4601
4602 /* If a menu is still active, check again after a short delay,
4603 since Windows often (always?) sends the WM_EXITMENULOOP
4604 before the corresponding WM_COMMAND message.
4605 Don't do this if a popup menu is active, since it is only
4606 menubar menus that require cleaning up in this way.
4607 */
4608 if (f && menubar_in_use && current_popup_menu == NULL)
4609 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4610
4611 /* If hourglass cursor should be displayed, display it now. */
4612 if (f && f->output_data.w32->hourglass_p)
4613 SetCursor (f->output_data.w32->hourglass_cursor);
4614
4615 goto dflt;
4616
4617 case WM_MENUSELECT:
4618 /* Direct handling of help_echo in menus. Should be safe now
4619 that we generate the help_echo by placing a help event in the
4620 keyboard buffer. */
4621 {
4622 HMENU menu = (HMENU) lParam;
4623 UINT menu_item = (UINT) LOWORD (wParam);
4624 UINT flags = (UINT) HIWORD (wParam);
4625
4626 w32_menu_display_help (hwnd, menu, menu_item, flags);
4627 }
4628 return 0;
4629
4630 case WM_MEASUREITEM:
4631 f = x_window_to_frame (dpyinfo, hwnd);
4632 if (f)
4633 {
4634 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4635
4636 if (pMis->CtlType == ODT_MENU)
4637 {
4638 /* Work out dimensions for popup menu titles. */
4639 char * title = (char *) pMis->itemData;
4640 HDC hdc = GetDC (hwnd);
4641 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4642 LOGFONT menu_logfont;
4643 HFONT old_font;
4644 SIZE size;
4645
4646 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4647 menu_logfont.lfWeight = FW_BOLD;
4648 menu_font = CreateFontIndirect (&menu_logfont);
4649 old_font = SelectObject (hdc, menu_font);
4650
4651 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4652 if (title)
4653 {
4654 if (unicode_append_menu)
4655 GetTextExtentPoint32W (hdc, (WCHAR *) title,
4656 wcslen ((WCHAR *) title),
4657 &size);
4658 else
4659 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4660
4661 pMis->itemWidth = size.cx;
4662 if (pMis->itemHeight < size.cy)
4663 pMis->itemHeight = size.cy;
4664 }
4665 else
4666 pMis->itemWidth = 0;
4667
4668 SelectObject (hdc, old_font);
4669 DeleteObject (menu_font);
4670 ReleaseDC (hwnd, hdc);
4671 return TRUE;
4672 }
4673 }
4674 return 0;
4675
4676 case WM_DRAWITEM:
4677 f = x_window_to_frame (dpyinfo, hwnd);
4678 if (f)
4679 {
4680 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4681
4682 if (pDis->CtlType == ODT_MENU)
4683 {
4684 /* Draw popup menu title. */
4685 char * title = (char *) pDis->itemData;
4686 if (title)
4687 {
4688 HDC hdc = pDis->hDC;
4689 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4690 LOGFONT menu_logfont;
4691 HFONT old_font;
4692
4693 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4694 menu_logfont.lfWeight = FW_BOLD;
4695 menu_font = CreateFontIndirect (&menu_logfont);
4696 old_font = SelectObject (hdc, menu_font);
4697
4698 /* Always draw title as if not selected. */
4699 if (unicode_append_menu)
4700 ExtTextOutW (hdc,
4701 pDis->rcItem.left
4702 + GetSystemMetrics (SM_CXMENUCHECK),
4703 pDis->rcItem.top,
4704 ETO_OPAQUE, &pDis->rcItem,
4705 (WCHAR *) title,
4706 wcslen ((WCHAR *) title), NULL);
4707 else
4708 ExtTextOut (hdc,
4709 pDis->rcItem.left
4710 + GetSystemMetrics (SM_CXMENUCHECK),
4711 pDis->rcItem.top,
4712 ETO_OPAQUE, &pDis->rcItem,
4713 title, strlen (title), NULL);
4714
4715 SelectObject (hdc, old_font);
4716 DeleteObject (menu_font);
4717 }
4718 return TRUE;
4719 }
4720 }
4721 return 0;
4722
4723 #if 0
4724 /* Still not right - can't distinguish between clicks in the
4725 client area of the frame from clicks forwarded from the scroll
4726 bars - may have to hook WM_NCHITTEST to remember the mouse
4727 position and then check if it is in the client area ourselves. */
4728 case WM_MOUSEACTIVATE:
4729 /* Discard the mouse click that activates a frame, allowing the
4730 user to click anywhere without changing point (or worse!).
4731 Don't eat mouse clicks on scrollbars though!! */
4732 if (LOWORD (lParam) == HTCLIENT )
4733 return MA_ACTIVATEANDEAT;
4734 goto dflt;
4735 #endif
4736
4737 case WM_MOUSELEAVE:
4738 /* No longer tracking mouse. */
4739 track_mouse_window = NULL;
4740
4741 case WM_ACTIVATEAPP:
4742 case WM_ACTIVATE:
4743 case WM_WINDOWPOSCHANGED:
4744 case WM_SHOWWINDOW:
4745 /* Inform lisp thread that a frame might have just been obscured
4746 or exposed, so should recheck visibility of all frames. */
4747 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4748 goto dflt;
4749
4750 case WM_SETFOCUS:
4751 dpyinfo->faked_key = 0;
4752 reset_modifiers ();
4753 if (!w32_kbdhook_active)
4754 register_hot_keys (hwnd);
4755 goto command;
4756 case WM_KILLFOCUS:
4757 if (!w32_kbdhook_active)
4758 unregister_hot_keys (hwnd);
4759 button_state = 0;
4760 ReleaseCapture ();
4761 /* Relinquish the system caret. */
4762 if (w32_system_caret_hwnd)
4763 {
4764 w32_visible_system_caret_hwnd = NULL;
4765 w32_system_caret_hwnd = NULL;
4766 DestroyCaret ();
4767 }
4768 goto command;
4769 case WM_COMMAND:
4770 menubar_in_use = 0;
4771 f = x_window_to_frame (dpyinfo, hwnd);
4772 if (f && HIWORD (wParam) == 0)
4773 {
4774 if (menu_free_timer)
4775 {
4776 KillTimer (hwnd, menu_free_timer);
4777 menu_free_timer = 0;
4778 }
4779 }
4780 case WM_MOVE:
4781 case WM_SIZE:
4782 command:
4783 wmsg.dwModifiers = w32_get_modifiers ();
4784 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4785 goto dflt;
4786
4787 #ifdef WINDOWSNT
4788 case WM_CREATE:
4789 setup_w32_kbdhook ();
4790 goto dflt;
4791 #endif
4792
4793 case WM_DESTROY:
4794 #ifdef WINDOWSNT
4795 remove_w32_kbdhook ();
4796 #endif
4797 CoUninitialize ();
4798 return 0;
4799
4800 case WM_WTSSESSION_CHANGE:
4801 if (wParam == WTS_SESSION_LOCK)
4802 reset_w32_kbdhook_state ();
4803 goto dflt;
4804
4805 case WM_CLOSE:
4806 wmsg.dwModifiers = w32_get_modifiers ();
4807 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4808 return 0;
4809
4810 case WM_ENDSESSION:
4811 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4812 /* If we return, the process will be terminated immediately. */
4813 sleep (1000);
4814
4815 case WM_WINDOWPOSCHANGING:
4816 /* Don't restrict the sizing of any kind of frames. If the window
4817 manager doesn't, there's no reason to do it ourselves. */
4818 return 0;
4819
4820 case WM_GETMINMAXINFO:
4821 /* Hack to allow resizing the Emacs frame above the screen size.
4822 Note that Windows 9x limits coordinates to 16-bits. */
4823 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
4824 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
4825 return 0;
4826
4827 case WM_SETCURSOR:
4828 if (LOWORD (lParam) == HTCLIENT)
4829 {
4830 f = x_window_to_frame (dpyinfo, hwnd);
4831 if (f)
4832 {
4833 if (f->output_data.w32->hourglass_p
4834 && !menubar_in_use && !current_popup_menu)
4835 SetCursor (f->output_data.w32->hourglass_cursor);
4836 else if (f->pointer_invisible)
4837 SetCursor (NULL);
4838 else
4839 SetCursor (f->output_data.w32->current_cursor);
4840 }
4841
4842 return 0;
4843 }
4844 goto dflt;
4845
4846 case WM_EMACS_SETCURSOR:
4847 {
4848 Cursor cursor = (Cursor) wParam;
4849 f = x_window_to_frame (dpyinfo, hwnd);
4850 if (f && cursor)
4851 {
4852 f->output_data.w32->current_cursor = cursor;
4853 /* Don't change the cursor while menu-bar menu is in use. */
4854 if (!f->output_data.w32->menubar_active
4855 && !f->output_data.w32->hourglass_p)
4856 {
4857 if (f->pointer_invisible)
4858 SetCursor (NULL);
4859 else
4860 SetCursor (cursor);
4861 }
4862 }
4863 return 0;
4864 }
4865
4866 case WM_EMACS_SHOWCURSOR:
4867 {
4868 ShowCursor ((BOOL) wParam);
4869
4870 return 0;
4871 }
4872
4873 case WM_EMACS_CREATEVSCROLLBAR:
4874 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
4875 (struct scroll_bar *) lParam);
4876
4877 case WM_EMACS_CREATEHSCROLLBAR:
4878 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
4879 (struct scroll_bar *) lParam);
4880
4881 case WM_EMACS_SHOWWINDOW:
4882 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4883
4884 case WM_EMACS_BRINGTOTOP:
4885 case WM_EMACS_SETFOREGROUND:
4886 {
4887 HWND foreground_window;
4888 DWORD foreground_thread, retval;
4889
4890 /* On NT 5.0, and apparently Windows 98, it is necessary to
4891 attach to the thread that currently has focus in order to
4892 pull the focus away from it. */
4893 foreground_window = GetForegroundWindow ();
4894 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4895 if (!foreground_window
4896 || foreground_thread == GetCurrentThreadId ()
4897 || !AttachThreadInput (GetCurrentThreadId (),
4898 foreground_thread, TRUE))
4899 foreground_thread = 0;
4900
4901 retval = SetForegroundWindow ((HWND) wParam);
4902 if (msg == WM_EMACS_BRINGTOTOP)
4903 retval = BringWindowToTop ((HWND) wParam);
4904
4905 /* Detach from the previous foreground thread. */
4906 if (foreground_thread)
4907 AttachThreadInput (GetCurrentThreadId (),
4908 foreground_thread, FALSE);
4909
4910 return retval;
4911 }
4912
4913 case WM_EMACS_SETWINDOWPOS:
4914 {
4915 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4916 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4917 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4918 }
4919
4920 case WM_EMACS_DESTROYWINDOW:
4921 DragAcceptFiles ((HWND) wParam, FALSE);
4922 return DestroyWindow ((HWND) wParam);
4923
4924 case WM_EMACS_HIDE_CARET:
4925 return HideCaret (hwnd);
4926
4927 case WM_EMACS_SHOW_CARET:
4928 return ShowCaret (hwnd);
4929
4930 case WM_EMACS_DESTROY_CARET:
4931 w32_system_caret_hwnd = NULL;
4932 w32_visible_system_caret_hwnd = NULL;
4933 return DestroyCaret ();
4934
4935 case WM_EMACS_TRACK_CARET:
4936 /* If there is currently no system caret, create one. */
4937 if (w32_system_caret_hwnd == NULL)
4938 {
4939 /* Use the default caret width, and avoid changing it
4940 unnecessarily, as it confuses screen reader software. */
4941 w32_system_caret_hwnd = hwnd;
4942 CreateCaret (hwnd, NULL, 0,
4943 w32_system_caret_height);
4944 }
4945
4946 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4947 return 0;
4948 /* Ensure visible caret gets turned on when requested. */
4949 else if (w32_use_visible_system_caret
4950 && w32_visible_system_caret_hwnd != hwnd)
4951 {
4952 w32_visible_system_caret_hwnd = hwnd;
4953 return ShowCaret (hwnd);
4954 }
4955 /* Ensure visible caret gets turned off when requested. */
4956 else if (!w32_use_visible_system_caret
4957 && w32_visible_system_caret_hwnd)
4958 {
4959 w32_visible_system_caret_hwnd = NULL;
4960 return HideCaret (hwnd);
4961 }
4962 else
4963 return 1;
4964
4965 case WM_EMACS_TRACKPOPUPMENU:
4966 {
4967 UINT flags;
4968 POINT *pos;
4969 int retval;
4970 pos = (POINT *)lParam;
4971 flags = TPM_CENTERALIGN;
4972 if (button_state & LMOUSE)
4973 flags |= TPM_LEFTBUTTON;
4974 else if (button_state & RMOUSE)
4975 flags |= TPM_RIGHTBUTTON;
4976
4977 /* Remember we did a SetCapture on the initial mouse down event,
4978 so for safety, we make sure the capture is canceled now. */
4979 ReleaseCapture ();
4980 button_state = 0;
4981
4982 /* Use menubar_active to indicate that WM_INITMENU is from
4983 TrackPopupMenu below, and should be ignored. */
4984 f = x_window_to_frame (dpyinfo, hwnd);
4985 if (f)
4986 f->output_data.w32->menubar_active = 1;
4987
4988 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4989 0, hwnd, NULL))
4990 {
4991 MSG amsg;
4992 /* Eat any mouse messages during popupmenu */
4993 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4994 PM_REMOVE));
4995 /* Get the menu selection, if any */
4996 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4997 {
4998 retval = LOWORD (amsg.wParam);
4999 }
5000 else
5001 {
5002 retval = 0;
5003 }
5004 }
5005 else
5006 {
5007 retval = -1;
5008 }
5009
5010 return retval;
5011 }
5012 case WM_EMACS_FILENOTIFY:
5013 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5014 return 1;
5015
5016 default:
5017 /* Check for messages registered at runtime. */
5018 if (msg == msh_mousewheel)
5019 {
5020 wmsg.dwModifiers = w32_get_modifiers ();
5021 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5022 signal_user_input ();
5023 return 0;
5024 }
5025
5026 dflt:
5027 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
5028 }
5029
5030 /* The most common default return code for handled messages is 0. */
5031 return 0;
5032 }
5033
5034 static void
5035 my_create_window (struct frame * f)
5036 {
5037 MSG msg;
5038 static int coords[2];
5039 Lisp_Object left, top;
5040 struct w32_display_info *dpyinfo = &one_w32_display_info;
5041
5042 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
5043 anything that is not a number and is not Qunbound. */
5044 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
5045 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
5046 if (EQ (left, Qunbound))
5047 coords[0] = CW_USEDEFAULT;
5048 else
5049 coords[0] = XINT (left);
5050 if (EQ (top, Qunbound))
5051 coords[1] = CW_USEDEFAULT;
5052 else
5053 coords[1] = XINT (top);
5054
5055 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
5056 (WPARAM)f, (LPARAM)coords))
5057 emacs_abort ();
5058 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5059 }
5060
5061
5062 /* Create a tooltip window. Unlike my_create_window, we do not do this
5063 indirectly via the Window thread, as we do not need to process Window
5064 messages for the tooltip. Creating tooltips indirectly also creates
5065 deadlocks when tooltips are created for menu items. */
5066 static void
5067 my_create_tip_window (struct frame *f)
5068 {
5069 RECT rect;
5070 Window tip_window;
5071
5072 rect.left = rect.top = 0;
5073 rect.right = FRAME_PIXEL_WIDTH (f);
5074 rect.bottom = FRAME_PIXEL_HEIGHT (f);
5075
5076 AdjustWindowRect (&rect, f->output_data.w32->dwStyle, false);
5077
5078 tip_window = FRAME_W32_WINDOW (f)
5079 = CreateWindow (EMACS_CLASS,
5080 f->namebuf,
5081 f->output_data.w32->dwStyle,
5082 f->left_pos,
5083 f->top_pos,
5084 rect.right - rect.left,
5085 rect.bottom - rect.top,
5086 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5087 NULL,
5088 hinst,
5089 NULL);
5090
5091 if (tip_window)
5092 {
5093 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
5094 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
5095 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
5096 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5097
5098 /* Tip frames have no scrollbars. */
5099 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
5100 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
5101
5102 /* Do this to discard the default setting specified by our parent. */
5103 ShowWindow (tip_window, SW_HIDE);
5104 }
5105 }
5106
5107
5108 /* Create and set up the w32 window for frame F. */
5109
5110 static void
5111 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
5112 {
5113 block_input ();
5114
5115 /* Use the resource name as the top-level window name
5116 for looking up resources. Make a non-Lisp copy
5117 for the window manager, so GC relocation won't bother it.
5118
5119 Elsewhere we specify the window name for the window manager. */
5120 f->namebuf = xlispstrdup (Vx_resource_name);
5121
5122 my_create_window (f);
5123
5124 validate_x_resource_name ();
5125
5126 /* x_set_name normally ignores requests to set the name if the
5127 requested name is the same as the current name. This is the one
5128 place where that assumption isn't correct; f->name is set, but
5129 the server hasn't been told. */
5130 {
5131 Lisp_Object name;
5132 int explicit = f->explicit_name;
5133
5134 f->explicit_name = 0;
5135 name = f->name;
5136 fset_name (f, Qnil);
5137 x_set_name (f, name, explicit);
5138 }
5139
5140 unblock_input ();
5141
5142 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5143 initialize_frame_menubar (f);
5144
5145 if (FRAME_W32_WINDOW (f) == 0)
5146 error ("Unable to create window");
5147 }
5148
5149 /* Handle the icon stuff for this window. Perhaps later we might
5150 want an x_set_icon_position which can be called interactively as
5151 well. */
5152
5153 static void
5154 x_icon (struct frame *f, Lisp_Object parms)
5155 {
5156 Lisp_Object icon_x, icon_y;
5157 struct w32_display_info *dpyinfo = &one_w32_display_info;
5158
5159 /* Set the position of the icon. Note that Windows 95 groups all
5160 icons in the tray. */
5161 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5162 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5163 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5164 {
5165 CHECK_NUMBER (icon_x);
5166 CHECK_NUMBER (icon_y);
5167 }
5168 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5169 error ("Both left and top icon corners of icon must be specified");
5170
5171 block_input ();
5172
5173 #if 0 /* TODO */
5174 /* Start up iconic or window? */
5175 x_wm_set_window_state
5176 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5177 ? IconicState
5178 : NormalState));
5179
5180 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
5181 ? f->icon_name
5182 : f->name)));
5183 #endif
5184
5185 unblock_input ();
5186 }
5187
5188
5189 static void
5190 x_make_gc (struct frame *f)
5191 {
5192 XGCValues gc_values;
5193
5194 block_input ();
5195
5196 /* Create the GC's of this frame.
5197 Note that many default values are used. */
5198
5199 /* Normal video */
5200 gc_values.font = FRAME_FONT (f);
5201
5202 /* Cursor has cursor-color background, background-color foreground. */
5203 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5204 gc_values.background = f->output_data.w32->cursor_pixel;
5205 f->output_data.w32->cursor_gc
5206 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5207 (GCFont | GCForeground | GCBackground),
5208 &gc_values);
5209
5210 /* Reliefs. */
5211 f->output_data.w32->white_relief.gc = 0;
5212 f->output_data.w32->black_relief.gc = 0;
5213
5214 unblock_input ();
5215 }
5216
5217
5218 /* Handler for signals raised during x_create_frame.
5219 FRAME is the frame which is partially constructed. */
5220
5221 static Lisp_Object
5222 unwind_create_frame (Lisp_Object frame)
5223 {
5224 struct frame *f = XFRAME (frame);
5225
5226 /* If frame is ``official'', nothing to do. */
5227 if (NILP (Fmemq (frame, Vframe_list)))
5228 {
5229 #ifdef GLYPH_DEBUG
5230 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5231
5232 /* If the frame's image cache refcount is still the same as our
5233 private shadow variable, it means we are unwinding a frame
5234 for which we didn't yet call init_frame_faces, where the
5235 refcount is incremented. Therefore, we increment it here, so
5236 that free_frame_faces, called in x_free_frame_resources
5237 below, will not mistakenly decrement the counter that was not
5238 incremented yet to account for this new frame. */
5239 if (FRAME_IMAGE_CACHE (f) != NULL
5240 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
5241 FRAME_IMAGE_CACHE (f)->refcount++;
5242 #endif
5243
5244 x_free_frame_resources (f);
5245 free_glyphs (f);
5246
5247 #ifdef GLYPH_DEBUG
5248 /* Check that reference counts are indeed correct. */
5249 eassert (dpyinfo->reference_count == dpyinfo_refcount);
5250 eassert ((dpyinfo->terminal->image_cache == NULL
5251 && image_cache_refcount == 0)
5252 || (dpyinfo->terminal->image_cache != NULL
5253 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
5254 #endif
5255 return Qt;
5256 }
5257
5258 return Qnil;
5259 }
5260
5261 static void
5262 do_unwind_create_frame (Lisp_Object frame)
5263 {
5264 unwind_create_frame (frame);
5265 }
5266
5267 static void
5268 x_default_font_parameter (struct frame *f, Lisp_Object parms)
5269 {
5270 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5271 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
5272 RES_TYPE_STRING);
5273 Lisp_Object font;
5274 if (EQ (font_param, Qunbound))
5275 font_param = Qnil;
5276 font = !NILP (font_param) ? font_param
5277 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
5278
5279 if (!STRINGP (font))
5280 {
5281 int i;
5282 static const char *names[]
5283 = { "Courier New-10",
5284 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
5285 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
5286 "Fixedsys",
5287 NULL };
5288
5289 for (i = 0; names[i]; i++)
5290 {
5291 font = font_open_by_name (f, build_unibyte_string (names[i]));
5292 if (! NILP (font))
5293 break;
5294 }
5295 if (NILP (font))
5296 error ("No suitable font was found");
5297 }
5298 else if (!NILP (font_param))
5299 {
5300 /* Remember the explicit font parameter, so we can re-apply it after
5301 we've applied the `default' face settings. */
5302 x_set_frame_parameters (f, Fcons (Fcons (Qfont_parameter, font_param),
5303 Qnil));
5304 }
5305 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
5306 }
5307
5308 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5309 1, 1, 0,
5310 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5311 Return an Emacs frame object.
5312 PARAMETERS is an alist of frame parameters.
5313 If the parameters specify that the frame should not have a minibuffer,
5314 and do not specify a specific minibuffer window to use,
5315 then `default-minibuffer-frame' must be a frame whose minibuffer can
5316 be shared by the new frame.
5317
5318 This function is an internal primitive--use `make-frame' instead. */)
5319 (Lisp_Object parameters)
5320 {
5321 struct frame *f;
5322 Lisp_Object frame, tem;
5323 Lisp_Object name;
5324 bool minibuffer_only = false;
5325 long window_prompting = 0;
5326 ptrdiff_t count = SPECPDL_INDEX ();
5327 Lisp_Object display;
5328 struct w32_display_info *dpyinfo = NULL;
5329 Lisp_Object parent;
5330 struct kboard *kb;
5331 int x_width = 0, x_height = 0;
5332
5333 if (!FRAME_W32_P (SELECTED_FRAME ())
5334 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
5335 error ("Cannot create a GUI frame in a -nw session");
5336
5337 /* Make copy of frame parameters because the original is in pure
5338 storage now. */
5339 parameters = Fcopy_alist (parameters);
5340
5341 /* Use this general default value to start with
5342 until we know if this frame has a specified name. */
5343 Vx_resource_name = Vinvocation_name;
5344
5345 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
5346 if (EQ (display, Qunbound))
5347 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
5348 if (EQ (display, Qunbound))
5349 display = Qnil;
5350 dpyinfo = check_x_display_info (display);
5351 kb = dpyinfo->terminal->kboard;
5352
5353 if (!dpyinfo->terminal->name)
5354 error ("Terminal is not live, can't create new frames on it");
5355
5356 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5357 if (!STRINGP (name)
5358 && ! EQ (name, Qunbound)
5359 && ! NILP (name))
5360 error ("Invalid frame name--not a string or nil");
5361
5362 if (STRINGP (name))
5363 Vx_resource_name = name;
5364
5365 /* See if parent window is specified. */
5366 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5367 if (EQ (parent, Qunbound))
5368 parent = Qnil;
5369 if (! NILP (parent))
5370 CHECK_NUMBER (parent);
5371
5372 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5373 /* No need to protect DISPLAY because that's not used after passing
5374 it to make_frame_without_minibuffer. */
5375 frame = Qnil;
5376 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5377 RES_TYPE_SYMBOL);
5378 if (EQ (tem, Qnone) || NILP (tem))
5379 f = make_frame_without_minibuffer (Qnil, kb, display);
5380 else if (EQ (tem, Qonly))
5381 {
5382 f = make_minibuffer_frame ();
5383 minibuffer_only = true;
5384 }
5385 else if (WINDOWP (tem))
5386 f = make_frame_without_minibuffer (tem, kb, display);
5387 else
5388 f = make_frame (true);
5389
5390 XSETFRAME (frame, f);
5391
5392 /* By default, make scrollbars the system standard width and height. */
5393 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5394 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5395
5396 f->terminal = dpyinfo->terminal;
5397
5398 f->output_method = output_w32;
5399 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5400 FRAME_FONTSET (f) = -1;
5401
5402 fset_icon_name
5403 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5404 RES_TYPE_STRING));
5405 if (! STRINGP (f->icon_name))
5406 fset_icon_name (f, Qnil);
5407
5408 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5409
5410 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5411 record_unwind_protect (do_unwind_create_frame, frame);
5412
5413 #ifdef GLYPH_DEBUG
5414 image_cache_refcount =
5415 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5416 dpyinfo_refcount = dpyinfo->reference_count;
5417 #endif /* GLYPH_DEBUG */
5418
5419 /* Specify the parent under which to make this window. */
5420 if (!NILP (parent))
5421 {
5422 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5423 pointer from integer of different size. */
5424 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5425 f->output_data.w32->explicit_parent = true;
5426 }
5427 else
5428 {
5429 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5430 f->output_data.w32->explicit_parent = false;
5431 }
5432
5433 /* Set the name; the functions to which we pass f expect the name to
5434 be set. */
5435 if (EQ (name, Qunbound) || NILP (name))
5436 {
5437 fset_name (f, build_string (dpyinfo->w32_id_name));
5438 f->explicit_name = false;
5439 }
5440 else
5441 {
5442 fset_name (f, name);
5443 f->explicit_name = true;
5444 /* Use the frame's title when getting resources for this frame. */
5445 specbind (Qx_resource_name, name);
5446 }
5447
5448 if (uniscribe_available)
5449 register_font_driver (&uniscribe_font_driver, f);
5450 register_font_driver (&w32font_driver, f);
5451
5452 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5453 "fontBackend", "FontBackend", RES_TYPE_STRING);
5454
5455 /* Extract the window parameters from the supplied values
5456 that are needed to determine window geometry. */
5457 x_default_font_parameter (f, parameters);
5458
5459 x_default_parameter (f, parameters, Qborder_width, make_number (2),
5460 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5461
5462 /* We recognize either internalBorderWidth or internalBorder
5463 (which is what xterm calls it). */
5464 if (NILP (Fassq (Qinternal_border_width, parameters)))
5465 {
5466 Lisp_Object value;
5467
5468 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5469 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5470 if (! EQ (value, Qunbound))
5471 parameters = Fcons (Fcons (Qinternal_border_width, value),
5472 parameters);
5473 }
5474 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5475 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5476 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5477 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5478 NULL, NULL, RES_TYPE_NUMBER);
5479 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5480 NULL, NULL, RES_TYPE_NUMBER);
5481 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5482 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5483 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5484 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5485
5486 /* Also do the stuff which must be set before the window exists. */
5487 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5488 "foreground", "Foreground", RES_TYPE_STRING);
5489 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5490 "background", "Background", RES_TYPE_STRING);
5491 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5492 "pointerColor", "Foreground", RES_TYPE_STRING);
5493 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5494 "borderColor", "BorderColor", RES_TYPE_STRING);
5495 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5496 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5497 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5498 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5499 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5500 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5501 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5502 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5503 /* Process alpha here (Bug#16619). */
5504 x_default_parameter (f, parameters, Qalpha, Qnil,
5505 "alpha", "Alpha", RES_TYPE_NUMBER);
5506
5507 /* Init faces first since we need the frame's column width/line
5508 height in various occasions. */
5509 init_frame_faces (f);
5510
5511 /* The following call of change_frame_size is needed since otherwise
5512 x_set_tool_bar_lines will already work with the character sizes
5513 installed by init_frame_faces while the frame's pixel size is
5514 still calculated from a character size of 1 and we subsequently
5515 hit the (height >= 0) assertion in window_box_height.
5516
5517 The non-pixelwise code apparently worked around this because it
5518 had one frame line vs one toolbar line which left us with a zero
5519 root window height which was obviously wrong as well ... */
5520 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5521 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5522 Qx_create_frame_1);
5523
5524 /* The X resources controlling the menu-bar and tool-bar are
5525 processed specially at startup, and reflected in the mode
5526 variables; ignore them here. */
5527 x_default_parameter (f, parameters, Qmenu_bar_lines,
5528 NILP (Vmenu_bar_mode)
5529 ? make_number (0) : make_number (1),
5530 NULL, NULL, RES_TYPE_NUMBER);
5531 x_default_parameter (f, parameters, Qtool_bar_lines,
5532 NILP (Vtool_bar_mode)
5533 ? make_number (0) : make_number (1),
5534 NULL, NULL, RES_TYPE_NUMBER);
5535
5536 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5537 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5538 x_default_parameter (f, parameters, Qtitle, Qnil,
5539 "title", "Title", RES_TYPE_STRING);
5540
5541 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5542 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5543
5544 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5545 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5546 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5547 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5548 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5549 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5550 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5551
5552 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5553
5554 window_prompting = x_figure_window_size (f, parameters, true, &x_width, &x_height);
5555
5556 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5557 f->no_split = minibuffer_only || EQ (tem, Qt);
5558
5559 w32_window (f, window_prompting, minibuffer_only);
5560 x_icon (f, parameters);
5561
5562 x_make_gc (f);
5563
5564 /* Now consider the frame official. */
5565 f->terminal->reference_count++;
5566 FRAME_DISPLAY_INFO (f)->reference_count++;
5567 Vframe_list = Fcons (frame, Vframe_list);
5568
5569 /* We need to do this after creating the window, so that the
5570 icon-creation functions can say whose icon they're describing. */
5571 x_default_parameter (f, parameters, Qicon_type, Qnil,
5572 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5573
5574 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5575 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5576 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5577 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5578 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5579 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5580 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5581 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5582 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
5583 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
5584
5585 /* Allow x_set_window_size, now. */
5586 f->can_x_set_window_size = true;
5587
5588 if (x_width > 0)
5589 SET_FRAME_WIDTH (f, x_width);
5590 if (x_height > 0)
5591 SET_FRAME_HEIGHT (f, x_height);
5592
5593 /* Tell the server what size and position, etc, we want, and how
5594 badly we want them. This should be done after we have the menu
5595 bar so that its size can be taken into account. */
5596 block_input ();
5597 x_wm_set_size_hint (f, window_prompting, false);
5598 unblock_input ();
5599
5600 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
5601 Qx_create_frame_2);
5602
5603 /* Process fullscreen parameter here in the hope that normalizing a
5604 fullheight/fullwidth frame will produce the size set by the last
5605 adjust_frame_size call. */
5606 x_default_parameter (f, parameters, Qfullscreen, Qnil,
5607 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5608
5609 /* Make the window appear on the frame and enable display, unless
5610 the caller says not to. However, with explicit parent, Emacs
5611 cannot control visibility, so don't try. */
5612 if (! f->output_data.w32->explicit_parent)
5613 {
5614 Lisp_Object visibility;
5615
5616 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5617 if (EQ (visibility, Qunbound))
5618 visibility = Qt;
5619
5620 if (EQ (visibility, Qicon))
5621 x_iconify_frame (f);
5622 else if (! NILP (visibility))
5623 x_make_frame_visible (f);
5624 else
5625 {
5626 /* Must have been Qnil. */
5627 ;
5628 }
5629 }
5630
5631 /* Initialize `default-minibuffer-frame' in case this is the first
5632 frame on this terminal. */
5633 if (FRAME_HAS_MINIBUF_P (f)
5634 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
5635 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
5636 kset_default_minibuffer_frame (kb, frame);
5637
5638 /* All remaining specified parameters, which have not been "used"
5639 by x_get_arg and friends, now go in the misc. alist of the frame. */
5640 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
5641 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
5642 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
5643
5644 /* Make sure windows on this frame appear in calls to next-window
5645 and similar functions. */
5646 Vwindow_list = Qnil;
5647
5648 return unbind_to (count, frame);
5649 }
5650
5651 /* FRAME is used only to get a handle on the X display. We don't pass the
5652 display info directly because we're called from frame.c, which doesn't
5653 know about that structure. */
5654 Lisp_Object
5655 x_get_focus_frame (struct frame *frame)
5656 {
5657 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
5658 Lisp_Object xfocus;
5659 if (! dpyinfo->w32_focus_frame)
5660 return Qnil;
5661
5662 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5663 return xfocus;
5664 }
5665
5666 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
5667 doc: /* Internal function called by `color-defined-p', which see.
5668 \(Note that the Nextstep version of this function ignores FRAME.) */)
5669 (Lisp_Object color, Lisp_Object frame)
5670 {
5671 XColor foo;
5672 struct frame *f = decode_window_system_frame (frame);
5673
5674 CHECK_STRING (color);
5675
5676 if (w32_defined_color (f, SSDATA (color), &foo, false))
5677 return Qt;
5678 else
5679 return Qnil;
5680 }
5681
5682 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
5683 doc: /* Internal function called by `color-values', which see. */)
5684 (Lisp_Object color, Lisp_Object frame)
5685 {
5686 XColor foo;
5687 struct frame *f = decode_window_system_frame (frame);
5688
5689 CHECK_STRING (color);
5690
5691 if (w32_defined_color (f, SSDATA (color), &foo, false))
5692 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
5693 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
5694 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
5695 else
5696 return Qnil;
5697 }
5698
5699 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
5700 doc: /* Internal function called by `display-color-p', which see. */)
5701 (Lisp_Object display)
5702 {
5703 struct w32_display_info *dpyinfo = check_x_display_info (display);
5704
5705 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
5706 return Qnil;
5707
5708 return Qt;
5709 }
5710
5711 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
5712 Sx_display_grayscale_p, 0, 1, 0,
5713 doc: /* Return t if DISPLAY supports shades of gray.
5714 Note that color displays do support shades of gray.
5715 The optional argument DISPLAY specifies which display to ask about.
5716 DISPLAY should be either a frame or a display name (a string).
5717 If omitted or nil, that stands for the selected frame's display. */)
5718 (Lisp_Object display)
5719 {
5720 struct w32_display_info *dpyinfo = check_x_display_info (display);
5721
5722 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
5723 return Qnil;
5724
5725 return Qt;
5726 }
5727
5728 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
5729 Sx_display_pixel_width, 0, 1, 0,
5730 doc: /* Return the width in pixels of DISPLAY.
5731 The optional argument DISPLAY specifies which display to ask about.
5732 DISPLAY should be either a frame or a display name (a string).
5733 If omitted or nil, that stands for the selected frame's display.
5734
5735 On \"multi-monitor\" setups this refers to the pixel width for all
5736 physical monitors associated with DISPLAY. To get information for
5737 each physical monitor, use `display-monitor-attributes-list'. */)
5738 (Lisp_Object display)
5739 {
5740 struct w32_display_info *dpyinfo = check_x_display_info (display);
5741
5742 return make_number (x_display_pixel_width (dpyinfo));
5743 }
5744
5745 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
5746 Sx_display_pixel_height, 0, 1, 0,
5747 doc: /* Return the height in pixels of DISPLAY.
5748 The optional argument DISPLAY specifies which display to ask about.
5749 DISPLAY should be either a frame or a display name (a string).
5750 If omitted or nil, that stands for the selected frame's display.
5751
5752 On \"multi-monitor\" setups this refers to the pixel height for all
5753 physical monitors associated with DISPLAY. To get information for
5754 each physical monitor, use `display-monitor-attributes-list'. */)
5755 (Lisp_Object display)
5756 {
5757 struct w32_display_info *dpyinfo = check_x_display_info (display);
5758
5759 return make_number (x_display_pixel_height (dpyinfo));
5760 }
5761
5762 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
5763 0, 1, 0,
5764 doc: /* Return the number of bitplanes of DISPLAY.
5765 The optional argument DISPLAY specifies which display to ask about.
5766 DISPLAY should be either a frame or a display name (a string).
5767 If omitted or nil, that stands for the selected frame's display. */)
5768 (Lisp_Object display)
5769 {
5770 struct w32_display_info *dpyinfo = check_x_display_info (display);
5771
5772 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
5773 }
5774
5775 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
5776 0, 1, 0,
5777 doc: /* Return the number of color cells of DISPLAY.
5778 The optional argument DISPLAY specifies which display to ask about.
5779 DISPLAY should be either a frame or a display name (a string).
5780 If omitted or nil, that stands for the selected frame's display. */)
5781 (Lisp_Object display)
5782 {
5783 struct w32_display_info *dpyinfo = check_x_display_info (display);
5784 int cap;
5785
5786 /* Don't use NCOLORS: it returns incorrect results under remote
5787 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
5788 * overflow and because probably is more meaningful on Windows
5789 * anyway. */
5790
5791 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
5792 return make_number (cap);
5793 }
5794
5795 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
5796 Sx_server_max_request_size,
5797 0, 1, 0,
5798 doc: /* Return the maximum request size of the server of DISPLAY.
5799 The optional argument DISPLAY specifies which display to ask about.
5800 DISPLAY should be either a frame or a display name (a string).
5801 If omitted or nil, that stands for the selected frame's display. */)
5802 (Lisp_Object display)
5803 {
5804 return make_number (1);
5805 }
5806
5807 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
5808 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
5809
5810 \(Labeling every distributor as a "vendor" embodies the false assumption
5811 that operating systems cannot be developed and distributed noncommercially.)
5812
5813 For GNU and Unix systems, this queries the X server software; for
5814 MS-Windows, this queries the OS.
5815
5816 The optional argument TERMINAL specifies which display to ask about.
5817 TERMINAL should be a terminal object, a frame or a display name (a string).
5818 If omitted or nil, that stands for the selected frame's display. */)
5819 (Lisp_Object terminal)
5820 {
5821 return build_string ("Microsoft Corp.");
5822 }
5823
5824 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
5825 doc: /* Return the version numbers of the GUI software on TERMINAL.
5826 The value is a list of three integers specifying the version of the GUI
5827 software in use.
5828
5829 For GNU and Unix system, the first 2 numbers are the version of the X
5830 Protocol used on TERMINAL and the 3rd number is the distributor-specific
5831 release number. For MS-Windows, the 3 numbers report the version and
5832 the build number of the OS.
5833
5834 See also the function `x-server-vendor'.
5835
5836 The optional argument TERMINAL specifies which display to ask about.
5837 TERMINAL should be a terminal object, a frame or a display name (a string).
5838 If omitted or nil, that stands for the selected frame's display. */)
5839 (Lisp_Object terminal)
5840 {
5841 return list3i (w32_major_version, w32_minor_version, w32_build_number);
5842 }
5843
5844 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
5845 doc: /* Return the number of screens on the server of DISPLAY.
5846 The optional argument DISPLAY specifies which display to ask about.
5847 DISPLAY should be either a frame or a display name (a string).
5848 If omitted or nil, that stands for the selected frame's display. */)
5849 (Lisp_Object display)
5850 {
5851 return make_number (1);
5852 }
5853
5854 DEFUN ("x-display-mm-height", Fx_display_mm_height,
5855 Sx_display_mm_height, 0, 1, 0,
5856 doc: /* Return the height in millimeters of DISPLAY.
5857 The optional argument DISPLAY specifies which display to ask about.
5858 DISPLAY should be either a frame or a display name (a string).
5859 If omitted or nil, that stands for the selected frame's display.
5860
5861 On \"multi-monitor\" setups this refers to the height in millimeters for
5862 all physical monitors associated with DISPLAY. To get information
5863 for each physical monitor, use `display-monitor-attributes-list'. */)
5864 (Lisp_Object display)
5865 {
5866 struct w32_display_info *dpyinfo = check_x_display_info (display);
5867 HDC hdc;
5868 double mm_per_pixel;
5869
5870 hdc = GetDC (NULL);
5871 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5872 / GetDeviceCaps (hdc, VERTRES));
5873 ReleaseDC (NULL, hdc);
5874
5875 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5876 }
5877
5878 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5879 doc: /* Return the width in millimeters of DISPLAY.
5880 The optional argument DISPLAY specifies which display to ask about.
5881 DISPLAY should be either a frame or a display name (a string).
5882 If omitted or nil, that stands for the selected frame's display.
5883
5884 On \"multi-monitor\" setups this refers to the width in millimeters for
5885 all physical monitors associated with TERMINAL. To get information
5886 for each physical monitor, use `display-monitor-attributes-list'. */)
5887 (Lisp_Object display)
5888 {
5889 struct w32_display_info *dpyinfo = check_x_display_info (display);
5890 HDC hdc;
5891 double mm_per_pixel;
5892
5893 hdc = GetDC (NULL);
5894 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5895 / GetDeviceCaps (hdc, HORZRES));
5896 ReleaseDC (NULL, hdc);
5897
5898 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5899 }
5900
5901 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5902 Sx_display_backing_store, 0, 1, 0,
5903 doc: /* Return an indication of whether DISPLAY does backing store.
5904 The value may be `always', `when-mapped', or `not-useful'.
5905 The optional argument DISPLAY specifies which display to ask about.
5906 DISPLAY should be either a frame or a display name (a string).
5907 If omitted or nil, that stands for the selected frame's display. */)
5908 (Lisp_Object display)
5909 {
5910 return intern ("not-useful");
5911 }
5912
5913 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5914 Sx_display_visual_class, 0, 1, 0,
5915 doc: /* Return the visual class of DISPLAY.
5916 The value is one of the symbols `static-gray', `gray-scale',
5917 `static-color', `pseudo-color', `true-color', or `direct-color'.
5918
5919 The optional argument DISPLAY specifies which display to ask about.
5920 DISPLAY should be either a frame or a display name (a string).
5921 If omitted or nil, that stands for the selected frame's display. */)
5922 (Lisp_Object display)
5923 {
5924 struct w32_display_info *dpyinfo = check_x_display_info (display);
5925 Lisp_Object result = Qnil;
5926
5927 if (dpyinfo->has_palette)
5928 result = intern ("pseudo-color");
5929 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5930 result = intern ("static-grey");
5931 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5932 result = intern ("static-color");
5933 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5934 result = intern ("true-color");
5935
5936 return result;
5937 }
5938
5939 DEFUN ("x-display-save-under", Fx_display_save_under,
5940 Sx_display_save_under, 0, 1, 0,
5941 doc: /* Return t if DISPLAY supports the save-under feature.
5942 The optional argument DISPLAY specifies which display to ask about.
5943 DISPLAY should be either a frame or a display name (a string).
5944 If omitted or nil, that stands for the selected frame's display. */)
5945 (Lisp_Object display)
5946 {
5947 return Qnil;
5948 }
5949
5950 static BOOL CALLBACK ALIGN_STACK
5951 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5952 {
5953 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5954
5955 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5956
5957 return TRUE;
5958 }
5959
5960 static Lisp_Object
5961 w32_display_monitor_attributes_list (void)
5962 {
5963 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5964 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5965 int i, n_monitors;
5966 HMONITOR *monitors;
5967
5968 if (!(enum_display_monitors_fn && get_monitor_info_fn
5969 && monitor_from_window_fn))
5970 return Qnil;
5971
5972 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5973 (LPARAM) &monitor_list)
5974 || NILP (monitor_list))
5975 return Qnil;
5976
5977 n_monitors = 0;
5978 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5979 n_monitors++;
5980
5981 monitors = xmalloc (n_monitors * sizeof (*monitors));
5982 for (i = 0; i < n_monitors; i++)
5983 {
5984 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5985 monitor_list = XCDR (monitor_list);
5986 }
5987
5988 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5989 FOR_EACH_FRAME (rest, frame)
5990 {
5991 struct frame *f = XFRAME (frame);
5992
5993 if (FRAME_W32_P (f) && !FRAME_TOOLTIP_P (f))
5994 {
5995 HMONITOR monitor =
5996 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5997 MONITOR_DEFAULT_TO_NEAREST);
5998
5999 for (i = 0; i < n_monitors; i++)
6000 if (monitors[i] == monitor)
6001 break;
6002
6003 if (i < n_monitors)
6004 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
6005 }
6006 }
6007
6008 for (i = 0; i < n_monitors; i++)
6009 {
6010 Lisp_Object geometry, workarea, name, attributes = Qnil;
6011 HDC hdc;
6012 int width_mm, height_mm;
6013 struct MONITOR_INFO_EX mi;
6014
6015 mi.cbSize = sizeof (mi);
6016 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
6017 continue;
6018
6019 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
6020 if (hdc == NULL)
6021 continue;
6022 width_mm = GetDeviceCaps (hdc, HORZSIZE);
6023 height_mm = GetDeviceCaps (hdc, VERTSIZE);
6024 DeleteDC (hdc);
6025
6026 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
6027 attributes);
6028
6029 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
6030
6031 attributes = Fcons (Fcons (Qname, name), attributes);
6032
6033 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6034 attributes);
6035
6036 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
6037 mi.rcWork.right - mi.rcWork.left,
6038 mi.rcWork.bottom - mi.rcWork.top);
6039 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6040
6041 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
6042 mi.rcMonitor.right - mi.rcMonitor.left,
6043 mi.rcMonitor.bottom - mi.rcMonitor.top);
6044 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6045
6046 if (mi.dwFlags & MONITORINFOF_PRIMARY)
6047 primary_monitor_attributes = attributes;
6048 else
6049 attributes_list = Fcons (attributes, attributes_list);
6050 }
6051
6052 if (!NILP (primary_monitor_attributes))
6053 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
6054
6055 xfree (monitors);
6056
6057 return attributes_list;
6058 }
6059
6060 static Lisp_Object
6061 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
6062 {
6063 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
6064 HDC hdc;
6065 double mm_per_pixel;
6066 int pixel_width, pixel_height, width_mm, height_mm;
6067 RECT workarea_rect;
6068
6069 /* Fallback: treat (possibly) multiple physical monitors as if they
6070 formed a single monitor as a whole. This should provide a
6071 consistent result at least on single monitor environments. */
6072 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
6073 attributes);
6074
6075 frames = Qnil;
6076 FOR_EACH_FRAME (rest, frame)
6077 {
6078 struct frame *f = XFRAME (frame);
6079
6080 if (FRAME_W32_P (f) && FRAME_TOOLTIP_P (f))
6081 frames = Fcons (frame, frames);
6082 }
6083 attributes = Fcons (Fcons (Qframes, frames), attributes);
6084
6085 pixel_width = x_display_pixel_width (dpyinfo);
6086 pixel_height = x_display_pixel_height (dpyinfo);
6087
6088 hdc = GetDC (NULL);
6089 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6090 / GetDeviceCaps (hdc, HORZRES));
6091 width_mm = pixel_width * mm_per_pixel + 0.5;
6092 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6093 / GetDeviceCaps (hdc, VERTRES));
6094 height_mm = pixel_height * mm_per_pixel + 0.5;
6095 ReleaseDC (NULL, hdc);
6096 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6097 attributes);
6098
6099 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
6100 we don't care. */
6101 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
6102 GetSystemMetrics (SM_YVIRTUALSCREEN),
6103 pixel_width, pixel_height);
6104 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
6105 workarea = list4i (workarea_rect.left, workarea_rect.top,
6106 workarea_rect.right - workarea_rect.left,
6107 workarea_rect.bottom - workarea_rect.top);
6108 else
6109 workarea = geometry;
6110 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6111
6112 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6113
6114 return list1 (attributes);
6115 }
6116
6117 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
6118 Sw32_display_monitor_attributes_list,
6119 0, 1, 0,
6120 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
6121
6122 The optional argument DISPLAY specifies which display to ask about.
6123 DISPLAY should be either a frame or a display name (a string).
6124 If omitted or nil, that stands for the selected frame's display.
6125
6126 Internal use only, use `display-monitor-attributes-list' instead. */)
6127 (Lisp_Object display)
6128 {
6129 struct w32_display_info *dpyinfo = check_x_display_info (display);
6130 Lisp_Object attributes_list;
6131
6132 block_input ();
6133 attributes_list = w32_display_monitor_attributes_list ();
6134 if (NILP (attributes_list))
6135 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
6136 unblock_input ();
6137
6138 return attributes_list;
6139 }
6140
6141 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
6142 doc: /* Set the sound generated when the bell is rung.
6143 SOUND is `asterisk', `exclamation', `hand', `question', `ok', or `silent'
6144 to use the corresponding system sound for the bell. The `silent' sound
6145 prevents Emacs from making any sound at all.
6146 SOUND is nil to use the normal beep. */)
6147 (Lisp_Object sound)
6148 {
6149 CHECK_SYMBOL (sound);
6150
6151 if (NILP (sound))
6152 sound_type = 0xFFFFFFFF;
6153 else if (EQ (sound, intern ("asterisk")))
6154 sound_type = MB_ICONASTERISK;
6155 else if (EQ (sound, intern ("exclamation")))
6156 sound_type = MB_ICONEXCLAMATION;
6157 else if (EQ (sound, intern ("hand")))
6158 sound_type = MB_ICONHAND;
6159 else if (EQ (sound, intern ("question")))
6160 sound_type = MB_ICONQUESTION;
6161 else if (EQ (sound, intern ("ok")))
6162 sound_type = MB_OK;
6163 else if (EQ (sound, intern ("silent")))
6164 sound_type = MB_EMACS_SILENT;
6165 else
6166 sound_type = 0xFFFFFFFF;
6167
6168 return sound;
6169 }
6170
6171 #if 0 /* unused */
6172 int
6173 x_screen_planes (register struct frame *f)
6174 {
6175 return FRAME_DISPLAY_INFO (f)->n_planes;
6176 }
6177 #endif
6178 \f
6179 /* Return the display structure for the display named NAME.
6180 Open a new connection if necessary. */
6181
6182 struct w32_display_info *
6183 x_display_info_for_name (Lisp_Object name)
6184 {
6185 struct w32_display_info *dpyinfo;
6186
6187 CHECK_STRING (name);
6188
6189 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
6190 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
6191 return dpyinfo;
6192
6193 /* Use this general default value to start with. */
6194 Vx_resource_name = Vinvocation_name;
6195
6196 validate_x_resource_name ();
6197
6198 dpyinfo = w32_term_init (name, NULL, SSDATA (Vx_resource_name));
6199
6200 if (dpyinfo == 0)
6201 error ("Cannot connect to server %s", SDATA (name));
6202
6203 XSETFASTINT (Vwindow_system_version, w32_major_version);
6204
6205 return dpyinfo;
6206 }
6207
6208 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6209 1, 3, 0, doc: /* Open a connection to a display server.
6210 DISPLAY is the name of the display to connect to.
6211 Optional second arg XRM-STRING is a string of resources in xrdb format.
6212 If the optional third arg MUST-SUCCEED is non-nil,
6213 terminate Emacs if we can't open the connection.
6214 \(In the Nextstep version, the last two arguments are currently ignored.) */)
6215 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
6216 {
6217 char *xrm_option;
6218 struct w32_display_info *dpyinfo;
6219
6220 CHECK_STRING (display);
6221
6222 /* Signal an error in order to encourage correct use from callers.
6223 * If we ever support multiple window systems in the same Emacs,
6224 * we'll need callers to be precise about what window system they
6225 * want. */
6226
6227 if (strcmp (SSDATA (display), "w32") != 0)
6228 error ("The name of the display in this Emacs must be \"w32\"");
6229
6230 /* If initialization has already been done, return now to avoid
6231 overwriting critical parts of one_w32_display_info. */
6232 if (window_system_available (NULL))
6233 return Qnil;
6234
6235 if (! NILP (xrm_string))
6236 CHECK_STRING (xrm_string);
6237
6238 /* Allow color mapping to be defined externally; first look in user's
6239 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6240 {
6241 Lisp_Object color_file;
6242
6243 color_file = build_string ("~/rgb.txt");
6244
6245 if (NILP (Ffile_readable_p (color_file)))
6246 color_file =
6247 Fexpand_file_name (build_string ("rgb.txt"),
6248 Fsymbol_value (intern ("data-directory")));
6249
6250 Vw32_color_map = Fx_load_color_file (color_file);
6251 }
6252 if (NILP (Vw32_color_map))
6253 Vw32_color_map = w32_default_color_map ();
6254
6255 /* Merge in system logical colors. */
6256 add_system_logical_colors_to_map (&Vw32_color_map);
6257
6258 if (! NILP (xrm_string))
6259 xrm_option = SSDATA (xrm_string);
6260 else
6261 xrm_option = NULL;
6262
6263 /* Use this general default value to start with. */
6264 /* First remove .exe suffix from invocation-name - it looks ugly. */
6265 {
6266 char basename[ MAX_PATH ], *str;
6267
6268 lispstpcpy (basename, Vinvocation_name);
6269 str = strrchr (basename, '.');
6270 if (str) *str = 0;
6271 Vinvocation_name = build_string (basename);
6272 }
6273 Vx_resource_name = Vinvocation_name;
6274
6275 validate_x_resource_name ();
6276
6277 /* This is what opens the connection and sets x_current_display.
6278 This also initializes many symbols, such as those used for input. */
6279 dpyinfo = w32_term_init (display, xrm_option, SSDATA (Vx_resource_name));
6280
6281 if (dpyinfo == 0)
6282 {
6283 if (!NILP (must_succeed))
6284 fatal ("Cannot connect to server %s.\n",
6285 SDATA (display));
6286 else
6287 error ("Cannot connect to server %s", SDATA (display));
6288 }
6289
6290 XSETFASTINT (Vwindow_system_version, w32_major_version);
6291 return Qnil;
6292 }
6293
6294 DEFUN ("x-close-connection", Fx_close_connection,
6295 Sx_close_connection, 1, 1, 0,
6296 doc: /* Close the connection to DISPLAY's server.
6297 For DISPLAY, specify either a frame or a display name (a string).
6298 If DISPLAY is nil, that stands for the selected frame's display. */)
6299 (Lisp_Object display)
6300 {
6301 struct w32_display_info *dpyinfo = check_x_display_info (display);
6302
6303 if (dpyinfo->reference_count > 0)
6304 error ("Display still has frames on it");
6305
6306 block_input ();
6307 x_destroy_all_bitmaps (dpyinfo);
6308
6309 x_delete_display (dpyinfo);
6310 unblock_input ();
6311
6312 return Qnil;
6313 }
6314
6315 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6316 doc: /* Return the list of display names that Emacs has connections to. */)
6317 (void)
6318 {
6319 Lisp_Object result = Qnil;
6320 struct w32_display_info *wdi;
6321
6322 for (wdi = x_display_list; wdi; wdi = wdi->next)
6323 result = Fcons (XCAR (wdi->name_list_element), result);
6324
6325 return result;
6326 }
6327
6328 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6329 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
6330 This function only has an effect on X Windows. With MS Windows, it is
6331 defined but does nothing.
6332
6333 If ON is nil, allow buffering of requests.
6334 Turning on synchronization prohibits the Xlib routines from buffering
6335 requests and seriously degrades performance, but makes debugging much
6336 easier.
6337 The optional second argument TERMINAL specifies which display to act on.
6338 TERMINAL should be a terminal object, a frame or a display name (a string).
6339 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
6340 (Lisp_Object on, Lisp_Object display)
6341 {
6342 return Qnil;
6343 }
6344
6345
6346 \f
6347 /***********************************************************************
6348 Window properties
6349 ***********************************************************************/
6350
6351 #if 0 /* TODO : port window properties to W32 */
6352
6353 DEFUN ("x-change-window-property", Fx_change_window_property,
6354 Sx_change_window_property, 2, 6, 0,
6355 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6356 PROP must be a string. VALUE may be a string or a list of conses,
6357 numbers and/or strings. If an element in the list is a string, it is
6358 converted to an atom and the value of the Atom is used. If an element
6359 is a cons, it is converted to a 32 bit number where the car is the 16
6360 top bits and the cdr is the lower 16 bits.
6361
6362 FRAME nil or omitted means use the selected frame.
6363 If TYPE is given and non-nil, it is the name of the type of VALUE.
6364 If TYPE is not given or nil, the type is STRING.
6365 FORMAT gives the size in bits of each element if VALUE is a list.
6366 It must be one of 8, 16 or 32.
6367 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6368 If OUTER-P is non-nil, the property is changed for the outer X window of
6369 FRAME. Default is to change on the edit X window. */)
6370 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6371 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6372 {
6373 struct frame *f = decode_window_system_frame (frame);
6374 Atom prop_atom;
6375
6376 CHECK_STRING (prop);
6377 CHECK_STRING (value);
6378
6379 block_input ();
6380 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6381 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6382 prop_atom, XA_STRING, 8, PropModeReplace,
6383 SDATA (value), SCHARS (value));
6384
6385 /* Make sure the property is set when we return. */
6386 XFlush (FRAME_W32_DISPLAY (f));
6387 unblock_input ();
6388
6389 return value;
6390 }
6391
6392
6393 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6394 Sx_delete_window_property, 1, 2, 0,
6395 doc: /* Remove window property PROP from X window of FRAME.
6396 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6397 (Lisp_Object prop, Lisp_Object frame)
6398 {
6399 struct frame *f = decode_window_system_frame (frame);
6400 Atom prop_atom;
6401
6402 CHECK_STRING (prop);
6403 block_input ();
6404 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6405 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6406
6407 /* Make sure the property is removed when we return. */
6408 XFlush (FRAME_W32_DISPLAY (f));
6409 unblock_input ();
6410
6411 return prop;
6412 }
6413
6414
6415 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6416 1, 6, 0,
6417 doc: /* Value is the value of window property PROP on FRAME.
6418 If FRAME is nil or omitted, use the selected frame.
6419
6420 On X Windows, the following optional arguments are also accepted:
6421 If TYPE is nil or omitted, get the property as a string.
6422 Otherwise TYPE is the name of the atom that denotes the type expected.
6423 If SOURCE is non-nil, get the property on that window instead of from
6424 FRAME. The number 0 denotes the root window.
6425 If DELETE-P is non-nil, delete the property after retrieving it.
6426 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6427
6428 On MS Windows, this function accepts but ignores those optional arguments.
6429
6430 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6431 no value of TYPE (always string in the MS Windows case). */)
6432 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6433 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6434 {
6435 struct frame *f = decode_window_system_frame (frame);
6436 Atom prop_atom;
6437 int rc;
6438 Lisp_Object prop_value = Qnil;
6439 char *tmp_data = NULL;
6440 Atom actual_type;
6441 int actual_format;
6442 unsigned long actual_size, bytes_remaining;
6443
6444 CHECK_STRING (prop);
6445 block_input ();
6446 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6447 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6448 prop_atom, 0, 0, False, XA_STRING,
6449 &actual_type, &actual_format, &actual_size,
6450 &bytes_remaining, (unsigned char **) &tmp_data);
6451 if (rc == Success)
6452 {
6453 int size = bytes_remaining;
6454
6455 XFree (tmp_data);
6456 tmp_data = NULL;
6457
6458 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6459 prop_atom, 0, bytes_remaining,
6460 False, XA_STRING,
6461 &actual_type, &actual_format,
6462 &actual_size, &bytes_remaining,
6463 (unsigned char **) &tmp_data);
6464 if (rc == Success)
6465 prop_value = make_string (tmp_data, size);
6466
6467 XFree (tmp_data);
6468 }
6469
6470 unblock_input ();
6471
6472 return prop_value;
6473
6474 return Qnil;
6475 }
6476
6477 #endif /* TODO */
6478
6479 /***********************************************************************
6480 Tool tips
6481 ***********************************************************************/
6482
6483 /* Create a frame for a tooltip on the display described by DPYINFO.
6484 PARMS is a list of frame parameters. Value is the frame.
6485
6486 Note that functions called here, esp. x_default_parameter can
6487 signal errors, for instance when a specified color name is
6488 undefined. We have to make sure that we're in a consistent state
6489 when this happens. */
6490
6491 static Lisp_Object
6492 x_create_tip_frame (struct w32_display_info *dpyinfo, Lisp_Object parms)
6493 {
6494 struct frame *f;
6495 Lisp_Object frame;
6496 Lisp_Object name;
6497 int width, height;
6498 ptrdiff_t count = SPECPDL_INDEX ();
6499 struct kboard *kb;
6500 bool face_change_before = face_change;
6501 int x_width = 0, x_height = 0;
6502
6503 /* Use this general default value to start with until we know if
6504 this frame has a specified name. */
6505 Vx_resource_name = Vinvocation_name;
6506
6507 kb = dpyinfo->terminal->kboard;
6508
6509 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6510 avoid destructive changes behind our caller's back. */
6511 parms = Fcopy_alist (parms);
6512
6513 /* Get the name of the frame to use for resource lookup. */
6514 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6515 if (!STRINGP (name)
6516 && !EQ (name, Qunbound)
6517 && !NILP (name))
6518 error ("Invalid frame name--not a string or nil");
6519 Vx_resource_name = name;
6520
6521 frame = Qnil;
6522 /* Make a frame without minibuffer nor mode-line. */
6523 f = make_frame (false);
6524 f->wants_modeline = false;
6525 XSETFRAME (frame, f);
6526
6527 record_unwind_protect (do_unwind_create_frame, frame);
6528
6529 /* By setting the output method, we're essentially saying that
6530 the frame is live, as per FRAME_LIVE_P. If we get a signal
6531 from this point on, x_destroy_window might screw up reference
6532 counts etc. */
6533 f->terminal = dpyinfo->terminal;
6534 f->output_method = output_w32;
6535 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6536
6537 FRAME_FONTSET (f) = -1;
6538 fset_icon_name (f, Qnil);
6539 f->tooltip = true;
6540
6541 #ifdef GLYPH_DEBUG
6542 image_cache_refcount =
6543 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6544 dpyinfo_refcount = dpyinfo->reference_count;
6545 #endif /* GLYPH_DEBUG */
6546 FRAME_KBOARD (f) = kb;
6547 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6548 f->output_data.w32->explicit_parent = false;
6549
6550 /* Set the name; the functions to which we pass f expect the name to
6551 be set. */
6552 if (EQ (name, Qunbound) || NILP (name))
6553 {
6554 fset_name (f, build_string (dpyinfo->w32_id_name));
6555 f->explicit_name = false;
6556 }
6557 else
6558 {
6559 fset_name (f, name);
6560 f->explicit_name = true;
6561 /* Use the frame's title when getting resources for this frame. */
6562 specbind (Qx_resource_name, name);
6563 }
6564
6565 if (uniscribe_available)
6566 register_font_driver (&uniscribe_font_driver, f);
6567 register_font_driver (&w32font_driver, f);
6568
6569 x_default_parameter (f, parms, Qfont_backend, Qnil,
6570 "fontBackend", "FontBackend", RES_TYPE_STRING);
6571
6572 /* Extract the window parameters from the supplied values
6573 that are needed to determine window geometry. */
6574 x_default_font_parameter (f, parms);
6575
6576 x_default_parameter (f, parms, Qborder_width, make_number (2),
6577 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6578 /* This defaults to 2 in order to match xterm. We recognize either
6579 internalBorderWidth or internalBorder (which is what xterm calls
6580 it). */
6581 if (NILP (Fassq (Qinternal_border_width, parms)))
6582 {
6583 Lisp_Object value;
6584
6585 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6586 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
6587 if (! EQ (value, Qunbound))
6588 parms = Fcons (Fcons (Qinternal_border_width, value),
6589 parms);
6590 }
6591
6592 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6593 "internalBorderWidth", "internalBorderWidth",
6594 RES_TYPE_NUMBER);
6595 /* Also do the stuff which must be set before the window exists. */
6596 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6597 "foreground", "Foreground", RES_TYPE_STRING);
6598 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6599 "background", "Background", RES_TYPE_STRING);
6600 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6601 "pointerColor", "Foreground", RES_TYPE_STRING);
6602 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6603 "cursorColor", "Foreground", RES_TYPE_STRING);
6604 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6605 "borderColor", "BorderColor", RES_TYPE_STRING);
6606
6607 /* Init faces before x_default_parameter is called for the
6608 scroll-bar-width parameter because otherwise we end up in
6609 init_iterator with a null face cache, which should not happen. */
6610 init_frame_faces (f);
6611
6612 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6613 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6614
6615 x_figure_window_size (f, parms, true, &x_width, &x_height);
6616
6617 /* No fringes on tip frame. */
6618 f->fringe_cols = 0;
6619 f->left_fringe_width = 0;
6620 f->right_fringe_width = 0;
6621 /* No dividers on tip frame. */
6622 f->right_divider_width = 0;
6623 f->bottom_divider_width = 0;
6624
6625 block_input ();
6626 my_create_tip_window (f);
6627 unblock_input ();
6628
6629 x_make_gc (f);
6630
6631 x_default_parameter (f, parms, Qauto_raise, Qnil,
6632 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6633 x_default_parameter (f, parms, Qauto_lower, Qnil,
6634 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6635 x_default_parameter (f, parms, Qcursor_type, Qbox,
6636 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6637 /* Process alpha here (Bug#17344). */
6638 x_default_parameter (f, parms, Qalpha, Qnil,
6639 "alpha", "Alpha", RES_TYPE_NUMBER);
6640
6641 /* Dimensions, especially FRAME_LINES (f), must be done via
6642 change_frame_size. Change will not be effected unless different
6643 from the current FRAME_LINES (f). */
6644 width = FRAME_COLS (f);
6645 height = FRAME_LINES (f);
6646 SET_FRAME_COLS (f, 0);
6647 SET_FRAME_LINES (f, 0);
6648 change_frame_size (f, width, height, true, false, false, false);
6649
6650 /* Set up faces after all frame parameters are known. This call
6651 also merges in face attributes specified for new frames.
6652
6653 Frame parameters may be changed if .Xdefaults contains
6654 specifications for the default font. For example, if there is an
6655 `Emacs.default.attributeBackground: pink', the `background-color'
6656 attribute of the frame get's set, which let's the internal border
6657 of the tooltip frame appear in pink. Prevent this. */
6658 {
6659 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
6660 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
6661 Lisp_Object colors = Qnil;
6662
6663 call2 (Qface_set_after_frame_default, frame, Qnil);
6664
6665 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
6666 colors = Fcons (Fcons (Qbackground_color, bg), colors);
6667 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
6668 colors = Fcons (Fcons (Qforeground_color, fg), colors);
6669
6670 if (!NILP (colors))
6671 Fmodify_frame_parameters (frame, colors);
6672 }
6673
6674 f->no_split = true;
6675
6676 /* Now this is an official tooltip frame on this display. */
6677 dpyinfo->w32_tooltip_frame = f;
6678
6679 /* Now that the frame is official, it counts as a reference to
6680 its display. */
6681 FRAME_DISPLAY_INFO (f)->reference_count++;
6682 f->terminal->reference_count++;
6683
6684 /* It is now ok to make the frame official even if we get an error
6685 below. And the frame needs to be on Vframe_list or making it
6686 visible won't work. */
6687 Vframe_list = Fcons (frame, Vframe_list);
6688 f->can_x_set_window_size = true;
6689
6690 /* Setting attributes of faces of the tooltip frame from resources
6691 and similar will set face_change, which leads to the
6692 clearing of all current matrices. Since this isn't necessary
6693 here, avoid it by resetting face_change to the value it
6694 had before we created the tip frame. */
6695 face_change = face_change_before;
6696
6697 /* Discard the unwind_protect. */
6698 return unbind_to (count, frame);
6699 }
6700
6701
6702 /* Compute where to display tip frame F. PARMS is the list of frame
6703 parameters for F. DX and DY are specified offsets from the current
6704 location of the mouse. WIDTH and HEIGHT are the width and height
6705 of the tooltip. Return coordinates relative to the root window of
6706 the display in *ROOT_X and *ROOT_Y. */
6707
6708 static void
6709 compute_tip_xy (struct frame *f,
6710 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
6711 int width, int height, int *root_x, int *root_y)
6712 {
6713 Lisp_Object left, top, right, bottom;
6714 int min_x, min_y, max_x, max_y;
6715
6716 /* User-specified position? */
6717 left = Fcdr (Fassq (Qleft, parms));
6718 top = Fcdr (Fassq (Qtop, parms));
6719 right = Fcdr (Fassq (Qright, parms));
6720 bottom = Fcdr (Fassq (Qbottom, parms));
6721
6722 /* Move the tooltip window where the mouse pointer is. Resize and
6723 show it. */
6724 if ((!INTEGERP (left) && !INTEGERP (right))
6725 || (!INTEGERP (top) && !INTEGERP (bottom)))
6726 {
6727 POINT pt;
6728
6729 /* Default min and max values. */
6730 min_x = 0;
6731 min_y = 0;
6732 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
6733 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
6734
6735 block_input ();
6736 GetCursorPos (&pt);
6737 *root_x = pt.x;
6738 *root_y = pt.y;
6739 unblock_input ();
6740
6741 /* If multiple monitor support is available, constrain the tip onto
6742 the current monitor. This improves the above by allowing negative
6743 co-ordinates if monitor positions are such that they are valid, and
6744 snaps a tooltip onto a single monitor if we are close to the edge
6745 where it would otherwise flow onto the other monitor (or into
6746 nothingness if there is a gap in the overlap). */
6747 if (monitor_from_point_fn && get_monitor_info_fn)
6748 {
6749 struct MONITOR_INFO info;
6750 HMONITOR monitor
6751 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
6752 info.cbSize = sizeof (info);
6753
6754 if (get_monitor_info_fn (monitor, &info))
6755 {
6756 min_x = info.rcWork.left;
6757 min_y = info.rcWork.top;
6758 max_x = info.rcWork.right;
6759 max_y = info.rcWork.bottom;
6760 }
6761 }
6762 }
6763
6764 if (INTEGERP (top))
6765 *root_y = XINT (top);
6766 else if (INTEGERP (bottom))
6767 *root_y = XINT (bottom) - height;
6768 else if (*root_y + XINT (dy) <= min_y)
6769 *root_y = min_y; /* Can happen for negative dy */
6770 else if (*root_y + XINT (dy) + height <= max_y)
6771 /* It fits below the pointer */
6772 *root_y += XINT (dy);
6773 else if (height + XINT (dy) + min_y <= *root_y)
6774 /* It fits above the pointer. */
6775 *root_y -= height + XINT (dy);
6776 else
6777 /* Put it on the top. */
6778 *root_y = min_y;
6779
6780 if (INTEGERP (left))
6781 *root_x = XINT (left);
6782 else if (INTEGERP (right))
6783 *root_x = XINT (right) - width;
6784 else if (*root_x + XINT (dx) <= min_x)
6785 *root_x = 0; /* Can happen for negative dx */
6786 else if (*root_x + XINT (dx) + width <= max_x)
6787 /* It fits to the right of the pointer. */
6788 *root_x += XINT (dx);
6789 else if (width + XINT (dx) + min_x <= *root_x)
6790 /* It fits to the left of the pointer. */
6791 *root_x -= width + XINT (dx);
6792 else
6793 /* Put it left justified on the screen -- it ought to fit that way. */
6794 *root_x = min_x;
6795 }
6796
6797 /* Hide tooltip frame F and delete it if DELETE is true. */
6798
6799 static Lisp_Object
6800 x_hide_tip (struct frame *f, bool delete)
6801 {
6802 if (f)
6803 {
6804 Lisp_Object frame, timer;
6805
6806 XSETFRAME (frame, f);
6807 timer = Fframe_parameter (frame, Qtooltip_timer);
6808
6809 if (!NILP (timer))
6810 call1 (Qcancel_timer, timer);
6811
6812 if (!delete && !FRAME_VISIBLE_P (f))
6813 return Qnil;
6814 else
6815 {
6816 ptrdiff_t count = SPECPDL_INDEX ();
6817
6818 specbind (Qinhibit_redisplay, Qt);
6819 specbind (Qinhibit_quit, Qt);
6820
6821 if (delete)
6822 delete_frame (frame, Qnil);
6823 else
6824 x_make_frame_invisible (f);
6825
6826 return unbind_to (count, Qt);
6827 }
6828 }
6829 return Qnil;
6830 }
6831
6832
6833 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
6834 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
6835 A tooltip window is a small window displaying a string.
6836
6837 This is an internal function; Lisp code should call `tooltip-show'.
6838
6839 FRAME nil or omitted means use the selected frame.
6840
6841 PARMS is an optional list of frame parameters which can be
6842 used to change the tooltip's appearance.
6843
6844 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6845 means use the default timeout of 5 seconds.
6846
6847 If the list of frame parameters PARMS contains a `left' parameter,
6848 display the tooltip at that x-position. If the list of frame parameters
6849 PARMS contains no `left' but a `right' parameter, display the tooltip
6850 right-adjusted at that x-position. Otherwise display it at the
6851 x-position of the mouse, with offset DX added (default is 5 if DX isn't
6852 specified).
6853
6854 Likewise for the y-position: If a `top' frame parameter is specified, it
6855 determines the position of the upper edge of the tooltip window. If a
6856 `bottom' parameter but no `top' frame parameter is specified, it
6857 determines the position of the lower edge of the tooltip window.
6858 Otherwise display the tooltip window at the y-position of the mouse,
6859 with offset DY added (default is -10).
6860
6861 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6862 Text larger than the specified size is clipped. */)
6863 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms,
6864 Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6865 {
6866 struct frame *tip_f;
6867 struct window *w;
6868 int root_x, root_y;
6869 struct buffer *old_buffer;
6870 struct text_pos pos;
6871 int width, height;
6872 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6873 ptrdiff_t count = SPECPDL_INDEX ();
6874 ptrdiff_t count_1;
6875 Lisp_Object window, size, tip_frame, parameters;
6876 AUTO_STRING (tip, " *tip*");
6877
6878 specbind (Qinhibit_redisplay, Qt);
6879
6880 CHECK_STRING (string);
6881 decode_window_system_frame (frame);
6882 if (NILP (timeout))
6883 timeout = make_number (5);
6884 else
6885 CHECK_NATNUM (timeout);
6886
6887 if (NILP (dx))
6888 dx = make_number (5);
6889 else
6890 CHECK_NUMBER (dx);
6891
6892 if (NILP (dy))
6893 dy = make_number (-10);
6894 else
6895 CHECK_NUMBER (dy);
6896
6897 parameters = Fframe_parameter (frame, Qtooltip_parameters);
6898 if (NILP (parameters))
6899 parameters = Fmake_vector (make_number (3), Qnil);
6900
6901 /* Look at current tooltip frame, if any. */
6902 tip_f = FRAME_DISPLAY_INFO (XFRAME (frame))->w32_tooltip_frame;
6903 if (tip_f)
6904 XSETFRAME (tip_frame, tip_f);
6905 else
6906 tip_frame = Qnil;
6907
6908 if (tip_f && FRAME_LIVE_P (tip_f))
6909 {
6910 Lisp_Object last_string = AREF (parameters, 0);
6911 Lisp_Object last_frame = AREF (parameters, 1);
6912 Lisp_Object last_parms = AREF (parameters, 2);
6913
6914 if (FRAME_VISIBLE_P (XFRAME (tip_frame))
6915 && EQ (frame, last_frame)
6916 && !NILP (Fequal_including_properties (last_string, string))
6917 && !NILP (Fequal (last_parms, parms)))
6918 {
6919 /* Only DX and DY have changed. */
6920 Lisp_Object timer = Fframe_parameter (tip_frame, Qtooltip_timer);
6921
6922 if (!NILP (timer))
6923 call1 (Qcancel_timer, timer);
6924
6925 block_input ();
6926 compute_tip_xy (tip_f, parms, dx, dy, FRAME_PIXEL_WIDTH (tip_f),
6927 FRAME_PIXEL_HEIGHT (tip_f), &root_x, &root_y);
6928
6929 /* Put tooltip in topmost group and in position. */
6930 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
6931 root_x, root_y, 0, 0,
6932 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6933
6934 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6935 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
6936 0, 0, 0, 0,
6937 SWP_NOMOVE | SWP_NOSIZE
6938 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6939
6940 /* Let redisplay know that we have made the frame visible already. */
6941 SET_FRAME_VISIBLE (tip_f, 1);
6942 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
6943 unblock_input ();
6944
6945 goto start_timer;
6946 }
6947 else if (tooltip_reuse_hidden_frame && EQ (frame, last_frame))
6948 {
6949 bool delete = false;
6950 Lisp_Object tail, elt, parm, last;
6951
6952 /* Check if every parameter in PARMS has the same value in
6953 last_parms. This may destruct last_parms which, however,
6954 will be recreated below. */
6955 for (tail = parms; CONSP (tail); tail = XCDR (tail))
6956 {
6957 elt = XCAR (tail);
6958 parm = Fcar (elt);
6959 /* The left, top, right and bottom parameters are handled
6960 by compute_tip_xy so they can be ignored here. */
6961 if (!EQ (parm, Qleft) && !EQ (parm, Qtop)
6962 && !EQ (parm, Qright) && !EQ (parm, Qbottom))
6963 {
6964 last = Fassq (parm, last_parms);
6965 if (NILP (Fequal (Fcdr (elt), Fcdr (last))))
6966 {
6967 /* We lost, delete the old tooltip. */
6968 delete = true;
6969 break;
6970 }
6971 else
6972 last_parms = call2 (Qassq_delete_all, parm, last_parms);
6973 }
6974 else
6975 last_parms = call2 (Qassq_delete_all, parm, last_parms);
6976 }
6977
6978 /* Now check if there's a parameter left in last_parms with a
6979 non-nil value. */
6980 for (tail = last_parms; CONSP (tail); tail = XCDR (tail))
6981 {
6982 elt = XCAR (tail);
6983 parm = Fcar (elt);
6984 if (!EQ (parm, Qleft) && !EQ (parm, Qtop) && !EQ (parm, Qright)
6985 && !EQ (parm, Qbottom) && !NILP (Fcdr (elt)))
6986 {
6987 /* We lost, delete the old tooltip. */
6988 delete = true;
6989 break;
6990 }
6991 }
6992
6993 x_hide_tip (tip_f, delete);
6994 }
6995 else
6996 x_hide_tip (tip_f, true);
6997 }
6998 else
6999 x_hide_tip (tip_f, true);
7000
7001 /* Update tooltip parameters. */
7002 {
7003 AUTO_FRAME_ARG (arg, Qtooltip_parameters, parameters);
7004 ASET (parameters, 0, string);
7005 ASET (parameters, 1, frame);
7006 ASET (parameters, 2, parms);
7007 Fmodify_frame_parameters (frame, arg);
7008 }
7009
7010 /* Block input until the tip has been fully drawn, to avoid crashes
7011 when drawing tips in menus. */
7012 block_input ();
7013
7014 if (!FRAMEP (tip_frame) || !FRAME_LIVE_P (XFRAME (tip_frame)))
7015 {
7016 /* Add default values to frame parameters. */
7017 if (NILP (Fassq (Qname, parms)))
7018 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7019 if (NILP (Fassq (Qinternal_border_width, parms)))
7020 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7021 if (NILP (Fassq (Qborder_width, parms)))
7022 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7023 if (NILP (Fassq (Qborder_color, parms)))
7024 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7025 if (NILP (Fassq (Qbackground_color, parms)))
7026 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7027 parms);
7028 if (NILP (tip_frame
7029 = x_create_tip_frame (FRAME_DISPLAY_INFO (XFRAME (frame)), parms)))
7030 {
7031 /* Creating the tip frame failed. */
7032 unblock_input ();
7033 return unbind_to (count, Qnil);
7034 }
7035 }
7036
7037 tip_f = XFRAME (tip_frame);
7038 window = FRAME_ROOT_WINDOW (tip_f);
7039 set_window_buffer (window, Fget_buffer_create (tip), false, false);
7040 w = XWINDOW (window);
7041 w->pseudo_window_p = true;
7042
7043 /* Set up the frame's root window. Note: The following code does not
7044 try to size the window or its frame correctly. Its only purpose is
7045 to make the subsequent text size calculations work. The right
7046 sizes should get installed when the toolkit gets back to us. */
7047 w->left_col = 0;
7048 w->top_line = 0;
7049 w->pixel_left = 0;
7050 w->pixel_top = 0;
7051
7052 if (CONSP (Vx_max_tooltip_size)
7053 && RANGED_INTEGERP (1, XCAR (Vx_max_tooltip_size), INT_MAX)
7054 && RANGED_INTEGERP (1, XCDR (Vx_max_tooltip_size), INT_MAX))
7055 {
7056 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
7057 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
7058 }
7059 else
7060 {
7061 w->total_cols = 80;
7062 w->total_lines = 40;
7063 }
7064
7065 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (tip_f);
7066 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (tip_f);
7067 FRAME_TOTAL_COLS (tip_f) = WINDOW_TOTAL_COLS (w);
7068 adjust_frame_glyphs (tip_f);
7069
7070 /* Insert STRING into the root window's buffer and fit the frame to
7071 the buffer. */
7072 count_1 = SPECPDL_INDEX ();
7073 old_buffer = current_buffer;
7074 set_buffer_internal_1 (XBUFFER (w->contents));
7075 bset_truncate_lines (current_buffer, Qnil);
7076 specbind (Qinhibit_read_only, Qt);
7077 specbind (Qinhibit_modification_hooks, Qt);
7078 specbind (Qinhibit_point_motion_hooks, Qt);
7079 Ferase_buffer ();
7080 Finsert (1, &string);
7081 clear_glyph_matrix (w->desired_matrix);
7082 clear_glyph_matrix (w->current_matrix);
7083 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7084 try_window (window, pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
7085 /* Calculate size of tooltip window. */
7086 size = Fwindow_text_pixel_size (window, Qnil, Qnil, Qnil,
7087 make_number (w->pixel_height), Qnil);
7088 /* Add the frame's internal border to calculated size. */
7089 width = XINT (Fcar (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7090 height = XINT (Fcdr (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7091 /* Calculate position of tooltip frame. */
7092 compute_tip_xy (tip_f, parms, dx, dy, width, height, &root_x, &root_y);
7093
7094 /* Show tooltip frame. */
7095 {
7096 RECT rect;
7097 int pad = (NUMBERP (Vw32_tooltip_extra_pixels)
7098 ? max (0, XINT (Vw32_tooltip_extra_pixels))
7099 : FRAME_COLUMN_WIDTH (tip_f));
7100
7101 rect.left = rect.top = 0;
7102 rect.right = width;
7103 rect.bottom = height;
7104 AdjustWindowRect (&rect, tip_f->output_data.w32->dwStyle,
7105 FRAME_EXTERNAL_MENU_BAR (tip_f));
7106
7107 /* Position and size tooltip and put it in the topmost group. */
7108 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7109 root_x, root_y,
7110 rect.right - rect.left + pad,
7111 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7112
7113 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7114 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7115 0, 0, 0, 0,
7116 SWP_NOMOVE | SWP_NOSIZE
7117 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7118
7119 /* Let redisplay know that we have made the frame visible already. */
7120 SET_FRAME_VISIBLE (tip_f, 1);
7121
7122 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7123 }
7124
7125 w->must_be_updated_p = true;
7126 update_single_window (w);
7127 set_buffer_internal_1 (old_buffer);
7128 unbind_to (count_1, Qnil);
7129 unblock_input ();
7130 windows_or_buffers_changed = old_windows_or_buffers_changed;
7131
7132 start_timer:
7133 {
7134 /* Let the tip disappear after timeout seconds. */
7135 AUTO_FRAME_ARG (arg, Qtooltip_timer,
7136 call3 (intern ("run-at-time"), timeout,
7137 Qnil, intern ("x-hide-tip")));
7138 Fmodify_frame_parameters (tip_frame, arg);
7139 }
7140 return unbind_to (count, Qnil);
7141 }
7142
7143
7144 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 1, 0,
7145 doc: /* Hide the current tooltip window, if there is any.
7146 Optional FRAME is the frame to hide tooltip on.
7147 Value is t if tooltip was open, nil otherwise. */)
7148 (Lisp_Object frame)
7149 {
7150 Lisp_Object obj = Qnil;
7151
7152 if (NILP (frame))
7153 {
7154 struct w32_display_info *dpyinfo;
7155
7156 for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
7157 if (dpyinfo->w32_tooltip_frame)
7158 if (!NILP (x_hide_tip (dpyinfo->w32_tooltip_frame,
7159 !tooltip_reuse_hidden_frame)))
7160 obj = Qt;
7161 }
7162 else
7163 {
7164 struct frame *f;
7165
7166 CHECK_FRAME (frame);
7167 f = XFRAME (frame);
7168 if (FRAME_DISPLAY_INFO (f)
7169 && FRAME_DISPLAY_INFO (f)->w32_tooltip_frame)
7170 obj = x_hide_tip (FRAME_DISPLAY_INFO (f)->w32_tooltip_frame,
7171 !tooltip_reuse_hidden_frame);
7172 }
7173 return obj;
7174 }
7175 \f
7176 /***********************************************************************
7177 File selection dialog
7178 ***********************************************************************/
7179
7180 #define FILE_NAME_TEXT_FIELD edt1
7181 #define FILE_NAME_COMBO_BOX cmb13
7182 #define FILE_NAME_LIST lst1
7183
7184 /* Callback for altering the behavior of the Open File dialog.
7185 Makes the Filename text field contain "Current Directory" and be
7186 read-only when "Directories" is selected in the filter. This
7187 allows us to work around the fact that the standard Open File
7188 dialog does not support directories. */
7189 static UINT_PTR CALLBACK
7190 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
7191 {
7192 if (msg == WM_NOTIFY)
7193 {
7194 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
7195 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
7196 int dropdown_changed;
7197 int dir_index;
7198 #ifdef NTGUI_UNICODE
7199 const int use_unicode = 1;
7200 #else /* !NTGUI_UNICODE */
7201 int use_unicode = w32_unicode_filenames;
7202 #endif /* NTGUI_UNICODE */
7203
7204 /* Detect when the Filter dropdown is changed. */
7205 if (use_unicode)
7206 dropdown_changed =
7207 notify_w->hdr.code == CDN_TYPECHANGE
7208 || notify_w->hdr.code == CDN_INITDONE;
7209 else
7210 dropdown_changed =
7211 notify_a->hdr.code == CDN_TYPECHANGE
7212 || notify_a->hdr.code == CDN_INITDONE;
7213 if (dropdown_changed)
7214 {
7215 HWND dialog = GetParent (hwnd);
7216 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7217 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
7218 int hdr_code;
7219
7220 /* At least on Windows 7, the above attempt to get the window handle
7221 to the File Name Text Field fails. The following code does the
7222 job though. Note that this code is based on my examination of the
7223 window hierarchy using Microsoft Spy++. bk */
7224 if (edit_control == NULL)
7225 {
7226 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
7227 if (tmp)
7228 {
7229 tmp = GetWindow (tmp, GW_CHILD);
7230 if (tmp)
7231 edit_control = GetWindow (tmp, GW_CHILD);
7232 }
7233 }
7234
7235 /* Directories is in index 2. */
7236 if (use_unicode)
7237 {
7238 dir_index = notify_w->lpOFN->nFilterIndex;
7239 hdr_code = notify_w->hdr.code;
7240 }
7241 else
7242 {
7243 dir_index = notify_a->lpOFN->nFilterIndex;
7244 hdr_code = notify_a->hdr.code;
7245 }
7246 if (dir_index == 2)
7247 {
7248 if (use_unicode)
7249 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7250 (LPARAM)L"Current Directory");
7251 else
7252 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7253 (LPARAM)"Current Directory");
7254 EnableWindow (edit_control, FALSE);
7255 /* Note that at least on Windows 7, the above call to EnableWindow
7256 disables the window that would ordinarily have focus. If we
7257 do not set focus to some other window here, focus will land in
7258 no man's land and the user will be unable to tab through the
7259 dialog box (pressing tab will only result in a beep).
7260 Avoid that problem by setting focus to the list here. */
7261 if (hdr_code == CDN_INITDONE)
7262 SetFocus (list);
7263 }
7264 else
7265 {
7266 /* Don't override default filename on init done. */
7267 if (hdr_code == CDN_TYPECHANGE)
7268 {
7269 if (use_unicode)
7270 SendMessageW (dialog, CDM_SETCONTROLTEXT,
7271 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
7272 else
7273 SendMessageA (dialog, CDM_SETCONTROLTEXT,
7274 FILE_NAME_TEXT_FIELD, (LPARAM)"");
7275 }
7276 EnableWindow (edit_control, TRUE);
7277 }
7278 }
7279 }
7280 return 0;
7281 }
7282
7283 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7284 doc: /* Read file name, prompting with PROMPT in directory DIR.
7285 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
7286 selection box, if specified. If MUSTMATCH is non-nil, the returned file
7287 or directory must exist.
7288
7289 This function is only defined on NS, MS Windows, and X Windows with the
7290 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
7291 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
7292 On Windows 7 and later, the file selection dialog "remembers" the last
7293 directory where the user selected a file, and will open that directory
7294 instead of DIR on subsequent invocations of this function with the same
7295 value of DIR as in previous invocations; this is standard Windows behavior. */)
7296 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
7297 {
7298 /* Filter index: 1: All Files, 2: Directories only */
7299 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
7300 #ifndef NTGUI_UNICODE
7301 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
7302 #endif
7303
7304 Lisp_Object filename = default_filename;
7305 struct frame *f = SELECTED_FRAME ();
7306 BOOL file_opened = FALSE;
7307 Lisp_Object orig_dir = dir;
7308 Lisp_Object orig_prompt = prompt;
7309
7310 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
7311 compatibility) we end up with the old file dialogs. Define a big
7312 enough struct for the new dialog to trick GetOpenFileName into
7313 giving us the new dialogs on newer versions of Windows. */
7314 struct {
7315 OPENFILENAMEW details;
7316 #if _WIN32_WINNT < 0x500 /* < win2k */
7317 PVOID pvReserved;
7318 DWORD dwReserved;
7319 DWORD FlagsEx;
7320 #endif /* < win2k */
7321 } new_file_details_w;
7322
7323 #ifdef NTGUI_UNICODE
7324 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
7325 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7326 const int use_unicode = 1;
7327 #else /* not NTGUI_UNICODE */
7328 struct {
7329 OPENFILENAMEA details;
7330 #if _WIN32_WINNT < 0x500 /* < win2k */
7331 PVOID pvReserved;
7332 DWORD dwReserved;
7333 DWORD FlagsEx;
7334 #endif /* < win2k */
7335 } new_file_details_a;
7336 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7337 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7338 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7339 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7340 int use_unicode = w32_unicode_filenames;
7341 wchar_t *prompt_w;
7342 char *prompt_a;
7343 int len;
7344 char fname_ret[MAX_UTF8_PATH];
7345 #endif /* NTGUI_UNICODE */
7346
7347 {
7348 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7349 system file encoding expected by the platform APIs (e.g. Cygwin's
7350 POSIX implementation) may not be the same as the encoding expected
7351 by the Windows "ANSI" APIs! */
7352
7353 CHECK_STRING (prompt);
7354 CHECK_STRING (dir);
7355
7356 dir = Fexpand_file_name (dir, Qnil);
7357
7358 if (STRINGP (filename))
7359 filename = Ffile_name_nondirectory (filename);
7360 else
7361 filename = empty_unibyte_string;
7362
7363 #ifdef CYGWIN
7364 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7365 if (SCHARS (filename) > 0)
7366 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7367 #endif
7368
7369 CHECK_STRING (dir);
7370 CHECK_STRING (filename);
7371
7372 /* The code in file_dialog_callback that attempts to set the text
7373 of the file name edit window when handling the CDN_INITDONE
7374 WM_NOTIFY message does not work. Setting filename to "Current
7375 Directory" in the only_dir_p case here does work however. */
7376 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7377 filename = build_string ("Current Directory");
7378
7379 /* Convert the values we've computed so far to system form. */
7380 #ifdef NTGUI_UNICODE
7381 to_unicode (prompt, &prompt);
7382 to_unicode (dir, &dir);
7383 to_unicode (filename, &filename);
7384 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7385 report_file_error ("filename too long", default_filename);
7386
7387 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7388 #else /* !NTGUI_UNICODE */
7389 prompt = ENCODE_FILE (prompt);
7390 dir = ENCODE_FILE (dir);
7391 filename = ENCODE_FILE (filename);
7392
7393 /* We modify these in-place, so make copies for safety. */
7394 dir = Fcopy_sequence (dir);
7395 unixtodos_filename (SSDATA (dir));
7396 filename = Fcopy_sequence (filename);
7397 unixtodos_filename (SSDATA (filename));
7398 if (SBYTES (filename) >= MAX_UTF8_PATH)
7399 report_file_error ("filename too long", default_filename);
7400 if (w32_unicode_filenames)
7401 {
7402 filename_to_utf16 (SSDATA (dir), dir_w);
7403 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7404 {
7405 /* filename_to_utf16 sets errno to ENOENT when the file
7406 name is too long or cannot be converted to UTF-16. */
7407 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7408 report_file_error ("filename too long", default_filename);
7409 }
7410 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7411 SSDATA (prompt), -1, NULL, 0);
7412 if (len > 32768)
7413 len = 32768;
7414 prompt_w = alloca (len * sizeof (wchar_t));
7415 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7416 SSDATA (prompt), -1, prompt_w, len);
7417 }
7418 else
7419 {
7420 filename_to_ansi (SSDATA (dir), dir_a);
7421 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7422 {
7423 /* filename_to_ansi sets errno to ENOENT when the file
7424 name is too long or cannot be converted to UTF-16. */
7425 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7426 report_file_error ("filename too long", default_filename);
7427 }
7428 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7429 SSDATA (prompt), -1, NULL, 0);
7430 if (len > 32768)
7431 len = 32768;
7432 prompt_w = alloca (len * sizeof (wchar_t));
7433 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7434 SSDATA (prompt), -1, prompt_w, len);
7435 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7436 if (len > 32768)
7437 len = 32768;
7438 prompt_a = alloca (len);
7439 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7440 }
7441 #endif /* NTGUI_UNICODE */
7442
7443 /* Fill in the structure for the call to GetOpenFileName below.
7444 For NTGUI_UNICODE builds (which run only on NT), we just use
7445 the actual size of the structure. For non-NTGUI_UNICODE
7446 builds, we tell the OS we're using an old version of the
7447 structure if the OS isn't new enough to support the newer
7448 version. */
7449 if (use_unicode)
7450 {
7451 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7452 if (w32_major_version > 4 && w32_major_version < 95)
7453 file_details_w->lStructSize = sizeof (new_file_details_w);
7454 else
7455 file_details_w->lStructSize = sizeof (*file_details_w);
7456 /* Set up the inout parameter for the selected file name. */
7457 file_details_w->lpstrFile = filename_buf_w;
7458 file_details_w->nMaxFile =
7459 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7460 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7461 /* Undocumented Bug in Common File Dialog:
7462 If a filter is not specified, shell links are not resolved. */
7463 file_details_w->lpstrFilter = filter_w;
7464 #ifdef NTGUI_UNICODE
7465 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7466 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7467 #else
7468 file_details_w->lpstrInitialDir = dir_w;
7469 file_details_w->lpstrTitle = prompt_w;
7470 #endif
7471 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7472 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7473 | OFN_EXPLORER | OFN_ENABLEHOOK);
7474 if (!NILP (mustmatch))
7475 {
7476 /* Require that the path to the parent directory exists. */
7477 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7478 /* If we are looking for a file, require that it exists. */
7479 if (NILP (only_dir_p))
7480 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7481 }
7482 }
7483 #ifndef NTGUI_UNICODE
7484 else
7485 {
7486 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7487 if (w32_major_version > 4 && w32_major_version < 95)
7488 file_details_a->lStructSize = sizeof (new_file_details_a);
7489 else
7490 file_details_a->lStructSize = sizeof (*file_details_a);
7491 file_details_a->lpstrFile = filename_buf_a;
7492 file_details_a->nMaxFile =
7493 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7494 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7495 file_details_a->lpstrFilter = filter_a;
7496 file_details_a->lpstrInitialDir = dir_a;
7497 file_details_a->lpstrTitle = prompt_a;
7498 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7499 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7500 | OFN_EXPLORER | OFN_ENABLEHOOK);
7501 if (!NILP (mustmatch))
7502 {
7503 /* Require that the path to the parent directory exists. */
7504 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7505 /* If we are looking for a file, require that it exists. */
7506 if (NILP (only_dir_p))
7507 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7508 }
7509 }
7510 #endif /* !NTGUI_UNICODE */
7511
7512 {
7513 int count = SPECPDL_INDEX ();
7514 /* Prevent redisplay. */
7515 specbind (Qinhibit_redisplay, Qt);
7516 block_input ();
7517 if (use_unicode)
7518 {
7519 file_details_w->lpfnHook = file_dialog_callback;
7520
7521 file_opened = GetOpenFileNameW (file_details_w);
7522 }
7523 #ifndef NTGUI_UNICODE
7524 else
7525 {
7526 file_details_a->lpfnHook = file_dialog_callback;
7527
7528 file_opened = GetOpenFileNameA (file_details_a);
7529 }
7530 #endif /* !NTGUI_UNICODE */
7531 unblock_input ();
7532 unbind_to (count, Qnil);
7533 }
7534
7535 if (file_opened)
7536 {
7537 /* Get an Emacs string from the value Windows gave us. */
7538 #ifdef NTGUI_UNICODE
7539 filename = from_unicode_buffer (filename_buf_w);
7540 #else /* !NTGUI_UNICODE */
7541 if (use_unicode)
7542 filename_from_utf16 (filename_buf_w, fname_ret);
7543 else
7544 filename_from_ansi (filename_buf_a, fname_ret);
7545 dostounix_filename (fname_ret);
7546 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7547 #endif /* NTGUI_UNICODE */
7548
7549 #ifdef CYGWIN
7550 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7551 #endif /* CYGWIN */
7552
7553 /* Strip the dummy filename off the end of the string if we
7554 added it to select a directory. */
7555 if ((use_unicode && file_details_w->nFilterIndex == 2)
7556 #ifndef NTGUI_UNICODE
7557 || (!use_unicode && file_details_a->nFilterIndex == 2)
7558 #endif
7559 )
7560 filename = Ffile_name_directory (filename);
7561 }
7562 /* User canceled the dialog without making a selection. */
7563 else if (!CommDlgExtendedError ())
7564 filename = Qnil;
7565 /* An error occurred, fallback on reading from the mini-buffer. */
7566 else
7567 filename = Fcompleting_read (
7568 orig_prompt,
7569 intern ("read-file-name-internal"),
7570 orig_dir,
7571 mustmatch,
7572 orig_dir,
7573 Qfile_name_history,
7574 default_filename,
7575 Qnil);
7576 }
7577
7578 /* Make "Cancel" equivalent to C-g. */
7579 if (NILP (filename))
7580 Fsignal (Qquit, Qnil);
7581
7582 return filename;
7583 }
7584
7585 \f
7586 #ifdef WINDOWSNT
7587 /* Moving files to the system recycle bin.
7588 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
7589 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
7590 Ssystem_move_file_to_trash, 1, 1, 0,
7591 doc: /* Move file or directory named FILENAME to the recycle bin. */)
7592 (Lisp_Object filename)
7593 {
7594 Lisp_Object handler;
7595 Lisp_Object encoded_file;
7596 Lisp_Object operation;
7597
7598 operation = Qdelete_file;
7599 if (!NILP (Ffile_directory_p (filename))
7600 && NILP (Ffile_symlink_p (filename)))
7601 {
7602 operation = intern ("delete-directory");
7603 filename = Fdirectory_file_name (filename);
7604 }
7605
7606 /* Must have fully qualified file names for moving files to Recycle
7607 Bin. */
7608 filename = Fexpand_file_name (filename, Qnil);
7609
7610 handler = Ffind_file_name_handler (filename, operation);
7611 if (!NILP (handler))
7612 return call2 (handler, operation, filename);
7613 else
7614 {
7615 const char * path;
7616 int result;
7617
7618 encoded_file = ENCODE_FILE (filename);
7619
7620 path = map_w32_filename (SSDATA (encoded_file), NULL);
7621
7622 /* The Unicode version of SHFileOperation is not supported on
7623 Windows 9X. */
7624 if (w32_unicode_filenames && os_subtype != OS_9X)
7625 {
7626 SHFILEOPSTRUCTW file_op_w;
7627 /* We need one more element beyond MAX_PATH because this is
7628 a list of file names, with the last element double-null
7629 terminated. */
7630 wchar_t tmp_path_w[MAX_PATH + 1];
7631
7632 memset (tmp_path_w, 0, sizeof (tmp_path_w));
7633 filename_to_utf16 (path, tmp_path_w);
7634
7635 /* On Windows, write permission is required to delete/move files. */
7636 _wchmod (tmp_path_w, 0666);
7637
7638 memset (&file_op_w, 0, sizeof (file_op_w));
7639 file_op_w.hwnd = HWND_DESKTOP;
7640 file_op_w.wFunc = FO_DELETE;
7641 file_op_w.pFrom = tmp_path_w;
7642 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7643 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7644 file_op_w.fAnyOperationsAborted = FALSE;
7645
7646 result = SHFileOperationW (&file_op_w);
7647 }
7648 else
7649 {
7650 SHFILEOPSTRUCTA file_op_a;
7651 char tmp_path_a[MAX_PATH + 1];
7652
7653 memset (tmp_path_a, 0, sizeof (tmp_path_a));
7654 filename_to_ansi (path, tmp_path_a);
7655
7656 /* If a file cannot be represented in ANSI codepage, don't
7657 let them inadvertently delete other files because some
7658 characters are interpreted as a wildcards. */
7659 if (_mbspbrk ((unsigned char *)tmp_path_a,
7660 (const unsigned char *)"?*"))
7661 result = ERROR_FILE_NOT_FOUND;
7662 else
7663 {
7664 _chmod (tmp_path_a, 0666);
7665
7666 memset (&file_op_a, 0, sizeof (file_op_a));
7667 file_op_a.hwnd = HWND_DESKTOP;
7668 file_op_a.wFunc = FO_DELETE;
7669 file_op_a.pFrom = tmp_path_a;
7670 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7671 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7672 file_op_a.fAnyOperationsAborted = FALSE;
7673
7674 result = SHFileOperationA (&file_op_a);
7675 }
7676 }
7677 if (result != 0)
7678 report_file_error ("Removing old name", list1 (filename));
7679 }
7680 return Qnil;
7681 }
7682
7683 #endif /* WINDOWSNT */
7684
7685 \f
7686 /***********************************************************************
7687 w32 specialized functions
7688 ***********************************************************************/
7689
7690 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
7691 Sw32_send_sys_command, 1, 2, 0,
7692 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
7693 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
7694 to minimize), #xf120 to restore frame to original size, and #xf100
7695 to activate the menubar for keyboard access. #xf140 activates the
7696 screen saver if defined.
7697
7698 If optional parameter FRAME is not specified, use selected frame. */)
7699 (Lisp_Object command, Lisp_Object frame)
7700 {
7701 struct frame *f = decode_window_system_frame (frame);
7702
7703 CHECK_NUMBER (command);
7704
7705 if (FRAME_W32_P (f))
7706 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
7707
7708 return Qnil;
7709 }
7710
7711 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
7712 doc: /* Get Windows to perform OPERATION on DOCUMENT.
7713 This is a wrapper around the ShellExecute system function, which
7714 invokes the application registered to handle OPERATION for DOCUMENT.
7715
7716 OPERATION is either nil or a string that names a supported operation.
7717 What operations can be used depends on the particular DOCUMENT and its
7718 handler application, but typically it is one of the following common
7719 operations:
7720
7721 \"open\" - open DOCUMENT, which could be a file, a directory, or an
7722 executable program (application). If it is an application,
7723 that application is launched in the current buffer's default
7724 directory. Otherwise, the application associated with
7725 DOCUMENT is launched in the buffer's default directory.
7726 \"opennew\" - like \"open\", but instruct the application to open
7727 DOCUMENT in a new window.
7728 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
7729 \"print\" - print DOCUMENT, which must be a file.
7730 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
7731 The printer should be provided in PARAMETERS, see below.
7732 \"explore\" - start the Windows Explorer on DOCUMENT.
7733 \"edit\" - launch an editor and open DOCUMENT for editing; which
7734 editor is launched depends on the association for the
7735 specified DOCUMENT.
7736 \"find\" - initiate search starting from DOCUMENT, which must specify
7737 a directory.
7738 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
7739 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
7740 the clipboard.
7741 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
7742 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
7743 which must be a directory.
7744 \"pastelink\"
7745 - create a shortcut in DOCUMENT (which must be a directory)
7746 the file or directory whose name is in the clipboard.
7747 \"runas\" - run DOCUMENT, which must be an excutable file, with
7748 elevated privileges (a.k.a. \"as Administrator\").
7749 \"properties\"
7750 - open the property sheet dialog for DOCUMENT.
7751 nil - invoke the default OPERATION, or \"open\" if default is
7752 not defined or unavailable.
7753
7754 DOCUMENT is typically the name of a document file or a URL, but can
7755 also be an executable program to run, or a directory to open in the
7756 Windows Explorer. If it is a file or a directory, it must be a local
7757 one; this function does not support remote file names.
7758
7759 If DOCUMENT is an executable program, the optional third arg PARAMETERS
7760 can be a string containing command line parameters, separated by blanks,
7761 that will be passed to the program. Some values of OPERATION also require
7762 parameters (e.g., \"printto\" requires the printer address). Otherwise,
7763 PARAMETERS should be nil or unspecified. Note that double quote characters
7764 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
7765
7766 Optional fourth argument SHOW-FLAG can be used to control how the
7767 application will be displayed when it is invoked. If SHOW-FLAG is nil
7768 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
7769 specified, otherwise it is an integer between 0 and 11 representing
7770 a ShowWindow flag:
7771
7772 0 - start hidden
7773 1 - start as normal-size window
7774 3 - start in a maximized window
7775 6 - start in a minimized window
7776 10 - start as the application itself specifies; this is the default. */)
7777 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
7778 {
7779 char *errstr;
7780 Lisp_Object current_dir = BVAR (current_buffer, directory);;
7781 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
7782 #ifdef CYGWIN
7783 intptr_t result;
7784 #else
7785 int use_unicode = w32_unicode_filenames;
7786 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
7787 Lisp_Object absdoc, handler;
7788 BOOL success;
7789 #endif
7790
7791 CHECK_STRING (document);
7792
7793 #ifdef CYGWIN
7794 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
7795 document = Fcygwin_convert_file_name_to_windows (document, Qt);
7796
7797 /* Encode filename, current directory and parameters. */
7798 current_dir = GUI_ENCODE_FILE (current_dir);
7799 document = GUI_ENCODE_FILE (document);
7800 doc_w = GUI_SDATA (document);
7801 if (STRINGP (parameters))
7802 {
7803 parameters = GUI_ENCODE_SYSTEM (parameters);
7804 params_w = GUI_SDATA (parameters);
7805 }
7806 if (STRINGP (operation))
7807 {
7808 operation = GUI_ENCODE_SYSTEM (operation);
7809 ops_w = GUI_SDATA (operation);
7810 }
7811 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7812 GUI_SDATA (current_dir),
7813 (INTEGERP (show_flag)
7814 ? XINT (show_flag) : SW_SHOWDEFAULT));
7815
7816 if (result > 32)
7817 return Qt;
7818
7819 switch (result)
7820 {
7821 case SE_ERR_ACCESSDENIED:
7822 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7823 break;
7824 case SE_ERR_ASSOCINCOMPLETE:
7825 case SE_ERR_NOASSOC:
7826 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7827 break;
7828 case SE_ERR_DDEBUSY:
7829 case SE_ERR_DDEFAIL:
7830 errstr = w32_strerror (ERROR_DDE_FAIL);
7831 break;
7832 case SE_ERR_DDETIMEOUT:
7833 errstr = w32_strerror (ERROR_TIMEOUT);
7834 break;
7835 case SE_ERR_DLLNOTFOUND:
7836 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7837 break;
7838 case SE_ERR_FNF:
7839 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7840 break;
7841 case SE_ERR_OOM:
7842 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7843 break;
7844 case SE_ERR_PNF:
7845 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7846 break;
7847 case SE_ERR_SHARE:
7848 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7849 break;
7850 default:
7851 errstr = w32_strerror (0);
7852 break;
7853 }
7854
7855 #else /* !CYGWIN */
7856
7857 const char file_url_str[] = "file:///";
7858 const int file_url_len = sizeof (file_url_str) - 1;
7859 int doclen;
7860
7861 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
7862 {
7863 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
7864 start a thread in some rare system configurations, for
7865 unknown reasons. That thread is started in the context of
7866 the Emacs process, but out of control of our code, and seems
7867 to never exit afterwards. Each such thread reserves 8MB of
7868 stack space (because that's the value recorded in the Emacs
7869 executable at link time: Emacs needs a large stack). So a
7870 large enough number of invocations of w32-shell-execute can
7871 potentially cause the Emacs process to run out of available
7872 address space, which is nasty. To work around this, we
7873 convert such URLs to local file names, which seems to prevent
7874 those threads from starting. See bug #20220. */
7875 char *p = SSDATA (document) + file_url_len;
7876
7877 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
7878 document = Fsubstring_no_properties (document,
7879 make_number (file_url_len), Qnil);
7880 }
7881 /* We have a situation here. If DOCUMENT is a relative file name,
7882 but its name includes leading directories, i.e. it lives not in
7883 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7884 will fail to find it. So we need to make the file name is
7885 absolute. But DOCUMENT does not have to be a file, it can be a
7886 URL, for example. So we make it absolute only if it is an
7887 existing file; if it is a file that does not exist, tough. */
7888 absdoc = Fexpand_file_name (document, Qnil);
7889 /* Don't call file handlers for file-exists-p, since they might
7890 attempt to access the file, which could fail or produce undesired
7891 consequences, see bug#16558 for an example. */
7892 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7893 if (NILP (handler))
7894 {
7895 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7896
7897 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7898 {
7899 /* ShellExecute fails if DOCUMENT is a UNC with forward
7900 slashes (expand-file-name above converts all backslashes
7901 to forward slashes). Now that we know DOCUMENT is a
7902 file, we can mirror all forward slashes into backslashes. */
7903 unixtodos_filename (SSDATA (absdoc_encoded));
7904 document = absdoc_encoded;
7905 }
7906 else
7907 document = ENCODE_FILE (document);
7908 }
7909 else
7910 document = ENCODE_FILE (document);
7911
7912 current_dir = ENCODE_FILE (current_dir);
7913 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
7914 be a URL that is not limited to MAX_PATH chararcters. */
7915 doclen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7916 SSDATA (document), -1, NULL, 0);
7917 doc_w = xmalloc (doclen * sizeof (wchar_t));
7918 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7919 SSDATA (document), -1, doc_w, doclen);
7920 if (use_unicode)
7921 {
7922 wchar_t current_dir_w[MAX_PATH];
7923 SHELLEXECUTEINFOW shexinfo_w;
7924
7925 /* Encode the current directory and parameters, and convert
7926 operation to UTF-16. */
7927 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7928 if (STRINGP (parameters))
7929 {
7930 int len;
7931
7932 parameters = ENCODE_SYSTEM (parameters);
7933 len = pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
7934 SSDATA (parameters), -1, NULL, 0);
7935 if (len > 32768)
7936 len = 32768;
7937 params_w = alloca (len * sizeof (wchar_t));
7938 pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
7939 SSDATA (parameters), -1, params_w, len);
7940 params_w[len - 1] = 0;
7941 }
7942 if (STRINGP (operation))
7943 {
7944 /* Assume OPERATION is pure ASCII. */
7945 const char *s = SSDATA (operation);
7946 wchar_t *d;
7947 int len = SBYTES (operation) + 1;
7948
7949 if (len > 32768)
7950 len = 32768;
7951 d = ops_w = alloca (len * sizeof (wchar_t));
7952 while (d < ops_w + len - 1)
7953 *d++ = *s++;
7954 *d = 0;
7955 }
7956
7957 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7958 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7959 able to invoke verbs from shortcut menu extensions, not just
7960 static verbs listed in the Registry. */
7961 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7962 shexinfo_w.cbSize = sizeof (shexinfo_w);
7963 shexinfo_w.fMask =
7964 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7965 shexinfo_w.hwnd = NULL;
7966 shexinfo_w.lpVerb = ops_w;
7967 shexinfo_w.lpFile = doc_w;
7968 shexinfo_w.lpParameters = params_w;
7969 shexinfo_w.lpDirectory = current_dir_w;
7970 shexinfo_w.nShow =
7971 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7972 success = ShellExecuteExW (&shexinfo_w);
7973 xfree (doc_w);
7974 }
7975 else
7976 {
7977 char current_dir_a[MAX_PATH];
7978 SHELLEXECUTEINFOA shexinfo_a;
7979 int codepage = codepage_for_filenames (NULL);
7980 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
7981 NULL, NULL);
7982
7983 doc_a = xmalloc (ldoc_a);
7984 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
7985 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7986 if (STRINGP (parameters))
7987 {
7988 parameters = ENCODE_SYSTEM (parameters);
7989 params_a = SSDATA (parameters);
7990 }
7991 if (STRINGP (operation))
7992 {
7993 /* Assume OPERATION is pure ASCII. */
7994 ops_a = SSDATA (operation);
7995 }
7996 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7997 shexinfo_a.cbSize = sizeof (shexinfo_a);
7998 shexinfo_a.fMask =
7999 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8000 shexinfo_a.hwnd = NULL;
8001 shexinfo_a.lpVerb = ops_a;
8002 shexinfo_a.lpFile = doc_a;
8003 shexinfo_a.lpParameters = params_a;
8004 shexinfo_a.lpDirectory = current_dir_a;
8005 shexinfo_a.nShow =
8006 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8007 success = ShellExecuteExA (&shexinfo_a);
8008 xfree (doc_w);
8009 xfree (doc_a);
8010 }
8011
8012 if (success)
8013 return Qt;
8014
8015 errstr = w32_strerror (0);
8016
8017 #endif /* !CYGWIN */
8018
8019 /* The error string might be encoded in the locale's encoding. */
8020 if (!NILP (Vlocale_coding_system))
8021 {
8022 Lisp_Object decoded =
8023 code_convert_string_norecord (build_unibyte_string (errstr),
8024 Vlocale_coding_system, 0);
8025 errstr = SSDATA (decoded);
8026 }
8027 error ("ShellExecute failed: %s", errstr);
8028 }
8029
8030 /* Lookup virtual keycode from string representing the name of a
8031 non-ascii keystroke into the corresponding virtual key, using
8032 lispy_function_keys. */
8033 static int
8034 lookup_vk_code (char *key)
8035 {
8036 int i;
8037
8038 for (i = 0; i < 256; i++)
8039 if (lispy_function_keys[i]
8040 && strcmp (lispy_function_keys[i], key) == 0)
8041 return i;
8042
8043 if (w32_kbdhook_active)
8044 {
8045 /* Alphanumerics map to themselves. */
8046 if (key[1] == 0)
8047 {
8048 if ((key[0] >= 'A' && key[0] <= 'Z')
8049 || (key[0] >= '0' && key[0] <= '9'))
8050 return key[0];
8051 if (key[0] >= 'a' && key[0] <= 'z')
8052 return toupper(key[0]);
8053 }
8054 }
8055
8056 return -1;
8057 }
8058
8059 /* Convert a one-element vector style key sequence to a hot key
8060 definition. */
8061 static Lisp_Object
8062 w32_parse_and_hook_hot_key (Lisp_Object key, int hook)
8063 {
8064 /* Copied from Fdefine_key and store_in_keymap. */
8065 register Lisp_Object c;
8066 int vk_code;
8067 int lisp_modifiers;
8068 int w32_modifiers;
8069 Lisp_Object res = Qnil;
8070 char* vkname;
8071
8072 CHECK_VECTOR (key);
8073
8074 if (ASIZE (key) != 1)
8075 return Qnil;
8076
8077 c = AREF (key, 0);
8078
8079 if (CONSP (c) && lucid_event_type_list_p (c))
8080 c = Fevent_convert_list (c);
8081
8082 if (! INTEGERP (c) && ! SYMBOLP (c))
8083 error ("Key definition is invalid");
8084
8085 /* Work out the base key and the modifiers. */
8086 if (SYMBOLP (c))
8087 {
8088 c = parse_modifiers (c);
8089 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8090 c = Fcar (c);
8091 if (!SYMBOLP (c))
8092 emacs_abort ();
8093 vkname = SSDATA (SYMBOL_NAME (c));
8094 /* [s-], [M-], [h-]: Register all keys for this modifier */
8095 if (w32_kbdhook_active && vkname[0] == 0)
8096 vk_code = VK_ANY;
8097 else
8098 vk_code = lookup_vk_code (vkname);
8099 }
8100 else if (INTEGERP (c))
8101 {
8102 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8103 /* Many ascii characters are their own virtual key code. */
8104 vk_code = XINT (c) & CHARACTERBITS;
8105 }
8106
8107 if (vk_code < 0 || vk_code > 255)
8108 return Qnil;
8109
8110 if ((lisp_modifiers & meta_modifier) != 0
8111 && !NILP (Vw32_alt_is_meta))
8112 lisp_modifiers |= alt_modifier;
8113
8114 /* Supply defs missing from mingw32. */
8115 #ifndef MOD_ALT
8116 #define MOD_ALT 0x0001
8117 #define MOD_CONTROL 0x0002
8118 #define MOD_SHIFT 0x0004
8119 #define MOD_WIN 0x0008
8120 #endif
8121
8122 if (w32_kbdhook_active)
8123 {
8124 /* Register Alt-x combinations. */
8125 if (lisp_modifiers & alt_modifier)
8126 {
8127 hook_w32_key (hook, VK_MENU, vk_code);
8128 res = Qt;
8129 }
8130 /* Register Win-x combinations based on modifier mappings. */
8131 if (((lisp_modifiers & hyper_modifier)
8132 && EQ (Vw32_lwindow_modifier, Qhyper))
8133 || ((lisp_modifiers & super_modifier)
8134 && EQ (Vw32_lwindow_modifier, Qsuper)))
8135 {
8136 hook_w32_key (hook, VK_LWIN, vk_code);
8137 res = Qt;
8138 }
8139 if (((lisp_modifiers & hyper_modifier)
8140 && EQ (Vw32_rwindow_modifier, Qhyper))
8141 || ((lisp_modifiers & super_modifier)
8142 && EQ (Vw32_rwindow_modifier, Qsuper)))
8143 {
8144 hook_w32_key (hook, VK_RWIN, vk_code);
8145 res = Qt;
8146 }
8147 return res;
8148 }
8149 else
8150 {
8151 /* Convert lisp modifiers to Windows hot-key form. */
8152 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8153 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8154 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8155 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8156
8157 return HOTKEY (vk_code, w32_modifiers);
8158 }
8159 }
8160
8161 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8162 Sw32_register_hot_key, 1, 1, 0,
8163 doc: /* Register KEY as a hot-key combination.
8164 Certain key combinations like Alt-Tab and Win-R are reserved for
8165 system use on Windows, and therefore are normally intercepted by the
8166 system. These key combinations can be received by registering them
8167 as hot-keys, except for Win-L which always locks the computer.
8168
8169 On Windows 98 and ME, KEY must be a one element key definition in
8170 vector form that would be acceptable to `define-key' (e.g. [A-tab] for
8171 Alt-Tab). The meta modifier is interpreted as Alt if
8172 `w32-alt-is-meta' is t, and hyper is always interpreted as the Windows
8173 modifier keys. The return value is the hotkey-id if registered, otherwise nil.
8174
8175 On Windows versions since NT, KEY can also be specified as [M-], [s-] or
8176 [h-] to indicate that all combinations of that key should be processed
8177 by Emacs instead of the operating system. The super and hyper
8178 modifiers are interpreted according to the current values of
8179 `w32-lwindow-modifier' and `w32-rwindow-modifier'. For instance,
8180 setting `w32-lwindow-modifier' to `super' and then calling
8181 `(register-hot-key [s-])' grabs all combinations of the left Windows
8182 key to Emacs, but leaves the right Windows key free for the operating
8183 system keyboard shortcuts. The return value is t if the call affected
8184 any key combinations, otherwise nil. */)
8185 (Lisp_Object key)
8186 {
8187 key = w32_parse_and_hook_hot_key (key, 1);
8188
8189 if (!w32_kbdhook_active
8190 && !NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8191 {
8192 /* Reuse an empty slot if possible. */
8193 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8194
8195 /* Safe to add new key to list, even if we have focus. */
8196 if (NILP (item))
8197 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8198 else
8199 XSETCAR (item, key);
8200
8201 /* Notify input thread about new hot-key definition, so that it
8202 takes effect without needing to switch focus. */
8203 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8204 (WPARAM) XINT (key), 0);
8205 }
8206
8207 return key;
8208 }
8209
8210 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8211 Sw32_unregister_hot_key, 1, 1, 0,
8212 doc: /* Unregister KEY as a hot-key combination. */)
8213 (Lisp_Object key)
8214 {
8215 Lisp_Object item;
8216
8217 if (!INTEGERP (key))
8218 key = w32_parse_and_hook_hot_key (key, 0);
8219
8220 if (w32_kbdhook_active)
8221 return key;
8222
8223 item = Fmemq (key, w32_grabbed_keys);
8224
8225 if (!NILP (item))
8226 {
8227 LPARAM lparam;
8228
8229 eassert (CONSP (item));
8230 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
8231 so that it works in a --with-wide-int build as well. */
8232 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
8233
8234 /* Notify input thread about hot-key definition being removed, so
8235 that it takes effect without needing focus switch. */
8236 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8237 (WPARAM) XINT (XCAR (item)), lparam))
8238 {
8239 MSG msg;
8240 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8241 }
8242 return Qt;
8243 }
8244 return Qnil;
8245 }
8246
8247 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8248 Sw32_registered_hot_keys, 0, 0, 0,
8249 doc: /* Return list of registered hot-key IDs. */)
8250 (void)
8251 {
8252 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8253 }
8254
8255 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8256 Sw32_reconstruct_hot_key, 1, 1, 0,
8257 doc: /* Convert hot-key ID to a lisp key combination.
8258 usage: (w32-reconstruct-hot-key ID) */)
8259 (Lisp_Object hotkeyid)
8260 {
8261 int vk_code, w32_modifiers;
8262 Lisp_Object key;
8263
8264 CHECK_NUMBER (hotkeyid);
8265
8266 vk_code = HOTKEY_VK_CODE (hotkeyid);
8267 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8268
8269 if (vk_code < 256 && lispy_function_keys[vk_code])
8270 key = intern (lispy_function_keys[vk_code]);
8271 else
8272 key = make_number (vk_code);
8273
8274 key = Fcons (key, Qnil);
8275 if (w32_modifiers & MOD_SHIFT)
8276 key = Fcons (Qshift, key);
8277 if (w32_modifiers & MOD_CONTROL)
8278 key = Fcons (Qctrl, key);
8279 if (w32_modifiers & MOD_ALT)
8280 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8281 if (w32_modifiers & MOD_WIN)
8282 key = Fcons (Qhyper, key);
8283
8284 return key;
8285 }
8286
8287 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8288 Sw32_toggle_lock_key, 1, 2, 0,
8289 doc: /* Toggle the state of the lock key KEY.
8290 KEY can be `capslock', `kp-numlock', or `scroll'.
8291 If the optional parameter NEW-STATE is a number, then the state of KEY
8292 is set to off if the low bit of NEW-STATE is zero, otherwise on.
8293 If NEW-STATE is omitted or nil, the function toggles the state,
8294
8295 Value is the new state of the key, or nil if the function failed
8296 to change the state. */)
8297 (Lisp_Object key, Lisp_Object new_state)
8298 {
8299 int vk_code;
8300 LPARAM lparam;
8301
8302 if (EQ (key, intern ("capslock")))
8303 vk_code = VK_CAPITAL;
8304 else if (EQ (key, intern ("kp-numlock")))
8305 vk_code = VK_NUMLOCK;
8306 else if (EQ (key, intern ("scroll")))
8307 vk_code = VK_SCROLL;
8308 else
8309 return Qnil;
8310
8311 if (!dwWindowsThreadId)
8312 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8313
8314 if (NILP (new_state))
8315 lparam = -1;
8316 else
8317 lparam = (XUINT (new_state)) & 1;
8318 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8319 (WPARAM) vk_code, lparam))
8320 {
8321 MSG msg;
8322 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8323 return make_number (msg.wParam);
8324 }
8325 return Qnil;
8326 }
8327
8328 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8329 2, 2, 0,
8330 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8331
8332 This is a direct interface to the Windows API FindWindow function. */)
8333 (Lisp_Object class, Lisp_Object name)
8334 {
8335 HWND hnd;
8336
8337 if (!NILP (class))
8338 CHECK_STRING (class);
8339 if (!NILP (name))
8340 CHECK_STRING (name);
8341
8342 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8343 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8344 if (!hnd)
8345 return Qnil;
8346 return Qt;
8347 }
8348
8349 DEFUN ("w32-frame-geometry", Fw32_frame_geometry, Sw32_frame_geometry, 0, 1, 0,
8350 doc: /* Return geometric attributes of FRAME.
8351 FRAME must be a live frame and defaults to the selected one. The return
8352 value is an association list of the attributes listed below. All height
8353 and width values are in pixels.
8354
8355 `outer-position' is a cons of the outer left and top edges of FRAME
8356 relative to the origin - the position (0, 0) - of FRAME's display.
8357
8358 `outer-size' is a cons of the outer width and height of FRAME. The
8359 outer size includes the title bar and the external borders as well as
8360 any menu and/or tool bar of frame.
8361
8362 `external-border-size' is a cons of the horizontal and vertical width of
8363 FRAME's external borders as supplied by the window manager.
8364
8365 `title-bar-size' is a cons of the width and height of the title bar of
8366 FRAME as supplied by the window manager. If both of them are zero,
8367 FRAME has no title bar. If only the width is zero, Emacs was not
8368 able to retrieve the width information.
8369
8370 `menu-bar-external', if non-nil, means the menu bar is external (never
8371 included in the inner edges of FRAME).
8372
8373 `menu-bar-size' is a cons of the width and height of the menu bar of
8374 FRAME.
8375
8376 `tool-bar-external', if non-nil, means the tool bar is external (never
8377 included in the inner edges of FRAME).
8378
8379 `tool-bar-position' tells on which side the tool bar on FRAME is and can
8380 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
8381 has no tool bar.
8382
8383 `tool-bar-size' is a cons of the width and height of the tool bar of
8384 FRAME.
8385
8386 `internal-border-width' is the width of the internal border of
8387 FRAME. */)
8388 (Lisp_Object frame)
8389 {
8390 struct frame *f = decode_live_frame (frame);
8391
8392 MENUBARINFO menu_bar;
8393 WINDOWINFO window;
8394 int left, top, right, bottom;
8395 unsigned int external_border_width, external_border_height;
8396 int title_bar_width = 0, title_bar_height = 0;
8397 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8398 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8399 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8400
8401 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8402 return Qnil;
8403
8404 block_input ();
8405 /* Outer rectangle and borders. */
8406 window.cbSize = sizeof (window);
8407 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8408 external_border_width = window.cxWindowBorders;
8409 external_border_height = window.cyWindowBorders;
8410 /* Title bar. */
8411 if (get_title_bar_info_fn)
8412 {
8413 TITLEBAR_INFO title_bar;
8414
8415 title_bar.cbSize = sizeof (title_bar);
8416 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8417 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8418 for (int i = 0; i < 6; i++)
8419 title_bar.rgstate[i] = 0;
8420 if (get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar)
8421 && !(title_bar.rgstate[0] & 0x00008001))
8422 {
8423 title_bar_width
8424 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8425 title_bar_height
8426 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8427 }
8428 }
8429 else if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8430 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8431 /* Menu bar. */
8432 menu_bar.cbSize = sizeof (menu_bar);
8433 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8434 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8435 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8436 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8437 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8438 unblock_input ();
8439
8440 left = window.rcWindow.left;
8441 top = window.rcWindow.top;
8442 right = window.rcWindow.right;
8443 bottom = window.rcWindow.bottom;
8444
8445 /* Menu bar. */
8446 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8447 /* Fix menu bar height reported by GetMenuBarInfo. */
8448 if (menu_bar_height > single_menu_bar_height)
8449 /* A wrapped menu bar. */
8450 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8451 else if (menu_bar_height > 0)
8452 /* A single line menu bar. */
8453 menu_bar_height = single_menu_bar_height;
8454
8455 return listn (CONSTYPE_HEAP, 10,
8456 Fcons (Qouter_position,
8457 Fcons (make_number (left), make_number (top))),
8458 Fcons (Qouter_size,
8459 Fcons (make_number (right - left),
8460 make_number (bottom - top))),
8461 Fcons (Qexternal_border_size,
8462 Fcons (make_number (external_border_width),
8463 make_number (external_border_height))),
8464 Fcons (Qtitle_bar_size,
8465 Fcons (make_number (title_bar_width),
8466 make_number (title_bar_height))),
8467 Fcons (Qmenu_bar_external, Qt),
8468 Fcons (Qmenu_bar_size,
8469 Fcons (make_number
8470 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8471 make_number (menu_bar_height))),
8472 Fcons (Qtool_bar_external, Qnil),
8473 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8474 Fcons (Qtool_bar_size,
8475 Fcons (make_number
8476 (tool_bar_height
8477 ? right - left - 2 * internal_border_width
8478 : 0),
8479 make_number (tool_bar_height))),
8480 Fcons (Qinternal_border_width,
8481 make_number (internal_border_width)));
8482 }
8483
8484 DEFUN ("w32-frame-edges", Fw32_frame_edges, Sw32_frame_edges, 0, 2, 0,
8485 doc: /* Return edge coordinates of FRAME.
8486 FRAME must be a live frame and defaults to the selected one. The return
8487 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8488 in pixels relative to the origin - the position (0, 0) - of FRAME's
8489 display.
8490
8491 If optional argument TYPE is the symbol `outer-edges', return the outer
8492 edges of FRAME. The outer edges comprise the decorations of the window
8493 manager (like the title bar or external borders) as well as any external
8494 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8495 `native-edges' or nil, return the native edges of FRAME. The native
8496 edges exclude the decorations of the window manager and any external
8497 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8498 the inner edges of FRAME. These edges exclude title bar, any borders,
8499 menu bar or tool bar of FRAME. */)
8500 (Lisp_Object frame, Lisp_Object type)
8501 {
8502 struct frame *f = decode_live_frame (frame);
8503
8504 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8505 return Qnil;
8506
8507 if (EQ (type, Qouter_edges))
8508 {
8509 RECT rectangle;
8510
8511 block_input ();
8512 /* Outer frame rectangle, including outer borders and title bar. */
8513 GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8514 unblock_input ();
8515
8516 return list4 (make_number (rectangle.left),
8517 make_number (rectangle.top),
8518 make_number (rectangle.right),
8519 make_number (rectangle.bottom));
8520 }
8521 else
8522 {
8523 RECT rectangle;
8524 POINT pt;
8525 int left, top, right, bottom;
8526
8527 block_input ();
8528 /* Inner frame rectangle, excluding borders and title bar. */
8529 GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
8530 /* Get top-left corner of native rectangle in screen
8531 coordinates. */
8532 pt.x = 0;
8533 pt.y = 0;
8534 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
8535 unblock_input ();
8536
8537 left = pt.x;
8538 top = pt.y;
8539 right = left + rectangle.right;
8540 bottom = top + rectangle.bottom;
8541
8542 if (EQ (type, Qinner_edges))
8543 {
8544 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8545
8546 return list4 (make_number (left + internal_border_width),
8547 make_number (top
8548 + FRAME_TOOL_BAR_HEIGHT (f)
8549 + internal_border_width),
8550 make_number (right - internal_border_width),
8551 make_number (bottom - internal_border_width));
8552 }
8553 else
8554 return list4 (make_number (left), make_number (top),
8555 make_number (right), make_number (bottom));
8556 }
8557 }
8558
8559 DEFUN ("w32-mouse-absolute-pixel-position", Fw32_mouse_absolute_pixel_position,
8560 Sw32_mouse_absolute_pixel_position, 0, 0, 0,
8561 doc: /* Return absolute position of mouse cursor in pixels.
8562 The position is returned as a cons cell (X . Y) of the coordinates of
8563 the mouse cursor position in pixels relative to a position (0, 0) of the
8564 selected frame's display. */)
8565 (void)
8566 {
8567 POINT pt;
8568
8569 block_input ();
8570 GetCursorPos (&pt);
8571 unblock_input ();
8572
8573 return Fcons (make_number (pt.x), make_number (pt.y));
8574 }
8575
8576 DEFUN ("w32-set-mouse-absolute-pixel-position", Fw32_set_mouse_absolute_pixel_position,
8577 Sw32_set_mouse_absolute_pixel_position, 2, 2, 0,
8578 doc: /* Move mouse pointer to absolute pixel position (X, Y).
8579 The coordinates X and Y are interpreted in pixels relative to a position
8580 \(0, 0) of the selected frame's display. */)
8581 (Lisp_Object x, Lisp_Object y)
8582 {
8583 UINT trail_num = 0;
8584 BOOL ret = false;
8585
8586 CHECK_TYPE_RANGED_INTEGER (int, x);
8587 CHECK_TYPE_RANGED_INTEGER (int, y);
8588
8589 block_input ();
8590 /* When "mouse trails" are in effect, moving the mouse cursor
8591 sometimes leaves behind an annoying "ghost" of the pointer.
8592 Avoid that by momentarily switching off mouse trails. */
8593 if (os_subtype == OS_NT
8594 && w32_major_version + w32_minor_version >= 6)
8595 ret = SystemParametersInfo (SPI_GETMOUSETRAILS, 0, &trail_num, 0);
8596 SetCursorPos (XINT (x), XINT (y));
8597 if (ret)
8598 SystemParametersInfo (SPI_SETMOUSETRAILS, trail_num, NULL, 0);
8599 unblock_input ();
8600
8601 return Qnil;
8602 }
8603
8604 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
8605 doc: /* Get power status information from Windows system.
8606
8607 The following %-sequences are provided:
8608 %L AC line status (verbose)
8609 %B Battery status (verbose)
8610 %b Battery status, empty means high, `-' means low,
8611 `!' means critical, and `+' means charging
8612 %p Battery load percentage
8613 %s Remaining time (to charge or discharge) in seconds
8614 %m Remaining time (to charge or discharge) in minutes
8615 %h Remaining time (to charge or discharge) in hours
8616 %t Remaining time (to charge or discharge) in the form `h:min' */)
8617 (void)
8618 {
8619 Lisp_Object status = Qnil;
8620
8621 SYSTEM_POWER_STATUS system_status;
8622 if (GetSystemPowerStatus (&system_status))
8623 {
8624 Lisp_Object line_status, battery_status, battery_status_symbol;
8625 Lisp_Object load_percentage, seconds, minutes, hours, remain;
8626
8627 long seconds_left = (long) system_status.BatteryLifeTime;
8628
8629 if (system_status.ACLineStatus == 0)
8630 line_status = build_string ("off-line");
8631 else if (system_status.ACLineStatus == 1)
8632 line_status = build_string ("on-line");
8633 else
8634 line_status = build_string ("N/A");
8635
8636 if (system_status.BatteryFlag & 128)
8637 {
8638 battery_status = build_string ("N/A");
8639 battery_status_symbol = empty_unibyte_string;
8640 }
8641 else if (system_status.BatteryFlag & 8)
8642 {
8643 battery_status = build_string ("charging");
8644 battery_status_symbol = build_string ("+");
8645 if (system_status.BatteryFullLifeTime != -1L)
8646 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
8647 }
8648 else if (system_status.BatteryFlag & 4)
8649 {
8650 battery_status = build_string ("critical");
8651 battery_status_symbol = build_string ("!");
8652 }
8653 else if (system_status.BatteryFlag & 2)
8654 {
8655 battery_status = build_string ("low");
8656 battery_status_symbol = build_string ("-");
8657 }
8658 else if (system_status.BatteryFlag & 1)
8659 {
8660 battery_status = build_string ("high");
8661 battery_status_symbol = empty_unibyte_string;
8662 }
8663 else
8664 {
8665 battery_status = build_string ("medium");
8666 battery_status_symbol = empty_unibyte_string;
8667 }
8668
8669 if (system_status.BatteryLifePercent > 100)
8670 load_percentage = build_string ("N/A");
8671 else
8672 {
8673 char buffer[16];
8674 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
8675 load_percentage = build_string (buffer);
8676 }
8677
8678 if (seconds_left < 0)
8679 seconds = minutes = hours = remain = build_string ("N/A");
8680 else
8681 {
8682 long m;
8683 double h;
8684 char buffer[16];
8685 snprintf (buffer, 16, "%ld", seconds_left);
8686 seconds = build_string (buffer);
8687
8688 m = seconds_left / 60;
8689 snprintf (buffer, 16, "%ld", m);
8690 minutes = build_string (buffer);
8691
8692 h = seconds_left / 3600.0;
8693 snprintf (buffer, 16, "%3.1f", h);
8694 hours = build_string (buffer);
8695
8696 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
8697 remain = build_string (buffer);
8698 }
8699
8700 status = listn (CONSTYPE_HEAP, 8,
8701 Fcons (make_number ('L'), line_status),
8702 Fcons (make_number ('B'), battery_status),
8703 Fcons (make_number ('b'), battery_status_symbol),
8704 Fcons (make_number ('p'), load_percentage),
8705 Fcons (make_number ('s'), seconds),
8706 Fcons (make_number ('m'), minutes),
8707 Fcons (make_number ('h'), hours),
8708 Fcons (make_number ('t'), remain));
8709 }
8710 return status;
8711 }
8712
8713 \f
8714 #ifdef WINDOWSNT
8715 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
8716 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8717 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
8718 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8719
8720 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8721 doc: /* Return storage information about the file system FILENAME is on.
8722 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8723 storage of the file system, FREE is the free storage, and AVAIL is the
8724 storage available to a non-superuser. All 3 numbers are in bytes.
8725 If the underlying system call fails, value is nil. */)
8726 (Lisp_Object filename)
8727 {
8728 Lisp_Object encoded, value;
8729
8730 CHECK_STRING (filename);
8731 filename = Fexpand_file_name (filename, Qnil);
8732 encoded = ENCODE_FILE (filename);
8733
8734 value = Qnil;
8735
8736 /* Determining the required information on Windows turns out, sadly,
8737 to be more involved than one would hope. The original Windows API
8738 call for this will return bogus information on some systems, but we
8739 must dynamically probe for the replacement api, since that was
8740 added rather late on. */
8741 {
8742 HMODULE hKernel = GetModuleHandle ("kernel32");
8743 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
8744 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
8745 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
8746 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
8747 bool have_pfn_GetDiskFreeSpaceEx =
8748 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
8749 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
8750
8751 /* On Windows, we may need to specify the root directory of the
8752 volume holding FILENAME. */
8753 char rootname[MAX_UTF8_PATH];
8754 wchar_t rootname_w[MAX_PATH];
8755 char rootname_a[MAX_PATH];
8756 char *name = SSDATA (encoded);
8757 BOOL result;
8758
8759 /* find the root name of the volume if given */
8760 if (isalpha (name[0]) && name[1] == ':')
8761 {
8762 rootname[0] = name[0];
8763 rootname[1] = name[1];
8764 rootname[2] = '\\';
8765 rootname[3] = 0;
8766 }
8767 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8768 {
8769 char *str = rootname;
8770 int slashes = 4;
8771 do
8772 {
8773 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8774 break;
8775 *str++ = *name++;
8776 }
8777 while ( *name );
8778
8779 *str++ = '\\';
8780 *str = 0;
8781 }
8782
8783 if (w32_unicode_filenames)
8784 filename_to_utf16 (rootname, rootname_w);
8785 else
8786 filename_to_ansi (rootname, rootname_a);
8787
8788 if (have_pfn_GetDiskFreeSpaceEx)
8789 {
8790 /* Unsigned large integers cannot be cast to double, so
8791 use signed ones instead. */
8792 LARGE_INTEGER availbytes;
8793 LARGE_INTEGER freebytes;
8794 LARGE_INTEGER totalbytes;
8795
8796 if (w32_unicode_filenames)
8797 result = pfn_GetDiskFreeSpaceExW (rootname_w,
8798 (ULARGE_INTEGER *)&availbytes,
8799 (ULARGE_INTEGER *)&totalbytes,
8800 (ULARGE_INTEGER *)&freebytes);
8801 else
8802 result = pfn_GetDiskFreeSpaceExA (rootname_a,
8803 (ULARGE_INTEGER *)&availbytes,
8804 (ULARGE_INTEGER *)&totalbytes,
8805 (ULARGE_INTEGER *)&freebytes);
8806 if (result)
8807 value = list3 (make_float ((double) totalbytes.QuadPart),
8808 make_float ((double) freebytes.QuadPart),
8809 make_float ((double) availbytes.QuadPart));
8810 }
8811 else
8812 {
8813 DWORD sectors_per_cluster;
8814 DWORD bytes_per_sector;
8815 DWORD free_clusters;
8816 DWORD total_clusters;
8817
8818 if (w32_unicode_filenames)
8819 result = GetDiskFreeSpaceW (rootname_w,
8820 &sectors_per_cluster,
8821 &bytes_per_sector,
8822 &free_clusters,
8823 &total_clusters);
8824 else
8825 result = GetDiskFreeSpaceA (rootname_a,
8826 &sectors_per_cluster,
8827 &bytes_per_sector,
8828 &free_clusters,
8829 &total_clusters);
8830 if (result)
8831 value = list3 (make_float ((double) total_clusters
8832 * sectors_per_cluster * bytes_per_sector),
8833 make_float ((double) free_clusters
8834 * sectors_per_cluster * bytes_per_sector),
8835 make_float ((double) free_clusters
8836 * sectors_per_cluster * bytes_per_sector));
8837 }
8838 }
8839
8840 return value;
8841 }
8842 #endif /* WINDOWSNT */
8843
8844 \f
8845 #ifdef WINDOWSNT
8846 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8847 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8848 (void)
8849 {
8850 static char pname_buf[256];
8851 int err;
8852 HANDLE hPrn;
8853 PRINTER_INFO_2W *ppi2w = NULL;
8854 PRINTER_INFO_2A *ppi2a = NULL;
8855 DWORD dwNeeded = 0, dwReturned = 0;
8856 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
8857 char port_name[MAX_UTF8_PATH];
8858
8859 /* Retrieve the default string from Win.ini (the registry).
8860 * String will be in form "printername,drivername,portname".
8861 * This is the most portable way to get the default printer. */
8862 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8863 return Qnil;
8864 /* printername precedes first "," character */
8865 strtok (pname_buf, ",");
8866 /* We want to know more than the printer name */
8867 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8868 return Qnil;
8869 /* GetPrinterW is not supported by unicows.dll. */
8870 if (w32_unicode_filenames && os_subtype != OS_9X)
8871 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
8872 else
8873 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
8874 if (dwNeeded == 0)
8875 {
8876 ClosePrinter (hPrn);
8877 return Qnil;
8878 }
8879 /* Call GetPrinter again with big enough memory block. */
8880 if (w32_unicode_filenames && os_subtype != OS_9X)
8881 {
8882 /* Allocate memory for the PRINTER_INFO_2 struct. */
8883 ppi2w = xmalloc (dwNeeded);
8884 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
8885 ClosePrinter (hPrn);
8886 if (!err)
8887 {
8888 xfree (ppi2w);
8889 return Qnil;
8890 }
8891
8892 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
8893 && ppi2w->pServerName)
8894 {
8895 filename_from_utf16 (ppi2w->pServerName, server_name);
8896 filename_from_utf16 (ppi2w->pShareName, share_name);
8897 }
8898 else
8899 {
8900 server_name[0] = '\0';
8901 filename_from_utf16 (ppi2w->pPortName, port_name);
8902 }
8903 }
8904 else
8905 {
8906 ppi2a = xmalloc (dwNeeded);
8907 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
8908 ClosePrinter (hPrn);
8909 if (!err)
8910 {
8911 xfree (ppi2a);
8912 return Qnil;
8913 }
8914
8915 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
8916 && ppi2a->pServerName)
8917 {
8918 filename_from_ansi (ppi2a->pServerName, server_name);
8919 filename_from_ansi (ppi2a->pShareName, share_name);
8920 }
8921 else
8922 {
8923 server_name[0] = '\0';
8924 filename_from_ansi (ppi2a->pPortName, port_name);
8925 }
8926 }
8927
8928 if (server_name[0])
8929 {
8930 /* a remote printer */
8931 if (server_name[0] == '\\')
8932 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
8933 share_name);
8934 else
8935 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
8936 share_name);
8937 pname_buf[sizeof (pname_buf) - 1] = '\0';
8938 }
8939 else
8940 {
8941 /* a local printer */
8942 strncpy (pname_buf, port_name, sizeof (pname_buf));
8943 pname_buf[sizeof (pname_buf) - 1] = '\0';
8944 /* `pPortName' can include several ports, delimited by ','.
8945 * we only use the first one. */
8946 strtok (pname_buf, ",");
8947 }
8948
8949 return DECODE_FILE (build_unibyte_string (pname_buf));
8950 }
8951 #endif /* WINDOWSNT */
8952 \f
8953
8954 /* Equivalent of strerror for W32 error codes. */
8955 char *
8956 w32_strerror (int error_no)
8957 {
8958 static char buf[500];
8959 DWORD ret;
8960
8961 if (error_no == 0)
8962 error_no = GetLastError ();
8963
8964 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
8965 FORMAT_MESSAGE_IGNORE_INSERTS,
8966 NULL,
8967 error_no,
8968 0, /* choose most suitable language */
8969 buf, sizeof (buf), NULL);
8970
8971 while (ret > 0 && (buf[ret - 1] == '\n' ||
8972 buf[ret - 1] == '\r' ))
8973 --ret;
8974 buf[ret] = '\0';
8975 if (!ret)
8976 sprintf (buf, "w32 error %d", error_no);
8977
8978 return buf;
8979 }
8980
8981 /* For convenience when debugging. (You cannot call GetLastError
8982 directly from GDB: it will crash, because it uses the __stdcall
8983 calling convention, not the _cdecl convention assumed by GDB.) */
8984 DWORD w32_last_error (void);
8985
8986 DWORD
8987 w32_last_error (void)
8988 {
8989 return GetLastError ();
8990 }
8991
8992 /* Cache information describing the NT system for later use. */
8993 void
8994 cache_system_info (void)
8995 {
8996 union
8997 {
8998 struct info
8999 {
9000 char major;
9001 char minor;
9002 short platform;
9003 } info;
9004 DWORD data;
9005 } version;
9006
9007 /* Cache the module handle of Emacs itself. */
9008 hinst = GetModuleHandle (NULL);
9009
9010 /* Cache the version of the operating system. */
9011 version.data = GetVersion ();
9012 w32_major_version = version.info.major;
9013 w32_minor_version = version.info.minor;
9014
9015 if (version.info.platform & 0x8000)
9016 os_subtype = OS_9X;
9017 else
9018 os_subtype = OS_NT;
9019
9020 /* Cache page size, allocation unit, processor type, etc. */
9021 GetSystemInfo (&sysinfo_cache);
9022 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
9023
9024 /* Cache os info. */
9025 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
9026 GetVersionEx (&osinfo_cache);
9027
9028 w32_build_number = osinfo_cache.dwBuildNumber;
9029 if (os_subtype == OS_9X)
9030 w32_build_number &= 0xffff;
9031
9032 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
9033 }
9034
9035 #ifdef EMACSDEBUG
9036 void
9037 _DebPrint (const char *fmt, ...)
9038 {
9039 char buf[1024];
9040 va_list args;
9041
9042 va_start (args, fmt);
9043 vsprintf (buf, fmt, args);
9044 va_end (args);
9045 #if CYGWIN
9046 fprintf (stderr, "%s", buf);
9047 #endif
9048 OutputDebugString (buf);
9049 }
9050 #endif
9051
9052 int
9053 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
9054 {
9055 int cur_state = (GetKeyState (vk_code) & 1);
9056
9057 if (NILP (new_state)
9058 || (NUMBERP (new_state)
9059 && ((XUINT (new_state)) & 1) != cur_state))
9060 {
9061 #ifdef WINDOWSNT
9062 faked_key = vk_code;
9063 #endif /* WINDOWSNT */
9064
9065 keybd_event ((BYTE) vk_code,
9066 (BYTE) MapVirtualKey (vk_code, 0),
9067 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9068 keybd_event ((BYTE) vk_code,
9069 (BYTE) MapVirtualKey (vk_code, 0),
9070 KEYEVENTF_EXTENDEDKEY | 0, 0);
9071 keybd_event ((BYTE) vk_code,
9072 (BYTE) MapVirtualKey (vk_code, 0),
9073 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9074 cur_state = !cur_state;
9075 }
9076
9077 return cur_state;
9078 }
9079
9080 /* Translate console modifiers to emacs modifiers.
9081 German keyboard support (Kai Morgan Zeise 2/18/95). */
9082 int
9083 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
9084 {
9085 int retval = 0;
9086
9087 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
9088 pressed, first remove those modifiers. */
9089 if (!NILP (Vw32_recognize_altgr)
9090 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9091 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9092 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
9093
9094 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
9095 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
9096
9097 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9098 {
9099 retval |= ctrl_modifier;
9100 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9101 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9102 retval |= meta_modifier;
9103 }
9104
9105 if (mods & LEFT_WIN_PRESSED)
9106 retval |= w32_key_to_modifier (VK_LWIN);
9107 if (mods & RIGHT_WIN_PRESSED)
9108 retval |= w32_key_to_modifier (VK_RWIN);
9109 if (mods & APPS_PRESSED)
9110 retval |= w32_key_to_modifier (VK_APPS);
9111 if (mods & SCROLLLOCK_ON)
9112 retval |= w32_key_to_modifier (VK_SCROLL);
9113
9114 /* Just in case someone wanted the original behavior, make it
9115 optional by setting w32-capslock-is-shiftlock to t. */
9116 if (NILP (Vw32_capslock_is_shiftlock)
9117 /* Keys that should _not_ be affected by CapsLock. */
9118 && ( (key == VK_BACK)
9119 || (key == VK_TAB)
9120 || (key == VK_CLEAR)
9121 || (key == VK_RETURN)
9122 || (key == VK_ESCAPE)
9123 || ((key >= VK_SPACE) && (key <= VK_HELP))
9124 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
9125 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
9126 ))
9127 {
9128 /* Only consider shift state. */
9129 if ((mods & SHIFT_PRESSED) != 0)
9130 retval |= shift_modifier;
9131 }
9132 else
9133 {
9134 /* Ignore CapsLock state if not enabled. */
9135 if (NILP (Vw32_enable_caps_lock))
9136 mods &= ~CAPSLOCK_ON;
9137 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
9138 retval |= shift_modifier;
9139 }
9140
9141 return retval;
9142 }
9143
9144 /* The return code indicates key code size. cpID is the codepage to
9145 use for translation to Unicode; -1 means use the current console
9146 input codepage. */
9147 int
9148 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
9149 {
9150 unsigned int key_code = event->wVirtualKeyCode;
9151 unsigned int mods = event->dwControlKeyState;
9152 BYTE keystate[256];
9153 static BYTE ansi_code[4];
9154 static int isdead = 0;
9155
9156 if (isdead == 2)
9157 {
9158 event->uChar.AsciiChar = ansi_code[2];
9159 isdead = 0;
9160 return 1;
9161 }
9162 if (event->uChar.AsciiChar != 0)
9163 return 1;
9164
9165 memset (keystate, 0, sizeof (keystate));
9166 keystate[key_code] = 0x80;
9167 if (mods & SHIFT_PRESSED)
9168 keystate[VK_SHIFT] = 0x80;
9169 if (mods & CAPSLOCK_ON)
9170 keystate[VK_CAPITAL] = 1;
9171 /* If we recognize right-alt and left-ctrl as AltGr, set the key
9172 states accordingly before invoking ToAscii. */
9173 if (!NILP (Vw32_recognize_altgr)
9174 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
9175 {
9176 keystate[VK_CONTROL] = 0x80;
9177 keystate[VK_LCONTROL] = 0x80;
9178 keystate[VK_MENU] = 0x80;
9179 keystate[VK_RMENU] = 0x80;
9180 }
9181
9182 #if 0
9183 /* Because of an OS bug, ToAscii corrupts the stack when called to
9184 convert a dead key in console mode on NT4. Unfortunately, trying
9185 to check for dead keys using MapVirtualKey doesn't work either -
9186 these functions apparently use internal information about keyboard
9187 layout which doesn't get properly updated in console programs when
9188 changing layout (though apparently it gets partly updated,
9189 otherwise ToAscii wouldn't crash). */
9190 if (is_dead_key (event->wVirtualKeyCode))
9191 return 0;
9192 #endif
9193
9194 /* On NT, call ToUnicode instead and then convert to the current
9195 console input codepage. */
9196 if (os_subtype == OS_NT)
9197 {
9198 WCHAR buf[128];
9199
9200 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
9201 keystate, buf, 128, 0);
9202 if (isdead > 0)
9203 {
9204 /* When we are called from the GUI message processing code,
9205 we are passed the current keyboard codepage, a positive
9206 number, to use below. */
9207 if (cpId == -1)
9208 cpId = GetConsoleCP ();
9209
9210 event->uChar.UnicodeChar = buf[isdead - 1];
9211 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
9212 (LPSTR)ansi_code, 4, NULL, NULL);
9213 }
9214 else
9215 isdead = 0;
9216 }
9217 else
9218 {
9219 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
9220 keystate, (LPWORD) ansi_code, 0);
9221 }
9222
9223 if (isdead == 0)
9224 return 0;
9225 event->uChar.AsciiChar = ansi_code[0];
9226 return isdead;
9227 }
9228
9229
9230 void
9231 w32_sys_ring_bell (struct frame *f)
9232 {
9233 if (sound_type == 0xFFFFFFFF)
9234 {
9235 Beep (666, 100);
9236 }
9237 else if (sound_type == MB_EMACS_SILENT)
9238 {
9239 /* Do nothing. */
9240 }
9241 else
9242 MessageBeep (sound_type);
9243 }
9244
9245 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
9246 0, 0, 0,
9247 doc: /* Return non-nil when a menu-bar menu is being used.
9248 Internal use only. */)
9249 (void)
9250 {
9251 return menubar_in_use ? Qt : Qnil;
9252 }
9253
9254 #if defined WINDOWSNT && !defined HAVE_DBUS
9255
9256 /***********************************************************************
9257 Tray notifications
9258 ***********************************************************************/
9259 /* A private struct declaration to avoid compile-time limits. */
9260 typedef struct MY_NOTIFYICONDATAW {
9261 DWORD cbSize;
9262 HWND hWnd;
9263 UINT uID;
9264 UINT uFlags;
9265 UINT uCallbackMessage;
9266 HICON hIcon;
9267 WCHAR szTip[128];
9268 DWORD dwState;
9269 DWORD dwStateMask;
9270 WCHAR szInfo[256];
9271 _ANONYMOUS_UNION union {
9272 UINT uTimeout;
9273 UINT uVersion;
9274 } DUMMYUNIONNAME;
9275 WCHAR szInfoTitle[64];
9276 DWORD dwInfoFlags;
9277 GUID guidItem;
9278 HICON hBalloonIcon;
9279 } MY_NOTIFYICONDATAW;
9280
9281 #define MYNOTIFYICONDATAW_V1_SIZE offsetof (MY_NOTIFYICONDATAW, szTip[64])
9282 #define MYNOTIFYICONDATAW_V2_SIZE offsetof (MY_NOTIFYICONDATAW, guidItem)
9283 #define MYNOTIFYICONDATAW_V3_SIZE offsetof (MY_NOTIFYICONDATAW, hBalloonIcon)
9284 #ifndef NIF_INFO
9285 # define NIF_INFO 0x00000010
9286 #endif
9287 #ifndef NIIF_NONE
9288 # define NIIF_NONE 0x00000000
9289 #endif
9290 #ifndef NIIF_INFO
9291 # define NIIF_INFO 0x00000001
9292 #endif
9293 #ifndef NIIF_WARNING
9294 # define NIIF_WARNING 0x00000002
9295 #endif
9296 #ifndef NIIF_ERROR
9297 # define NIIF_ERROR 0x00000003
9298 #endif
9299
9300
9301 #define EMACS_TRAY_NOTIFICATION_ID 42 /* arbitrary */
9302 #define EMACS_NOTIFICATION_MSG (WM_APP + 1)
9303
9304 enum NI_Severity {
9305 Ni_None,
9306 Ni_Info,
9307 Ni_Warn,
9308 Ni_Err
9309 };
9310
9311 /* Report the version of a DLL given by its name. The return value is
9312 constructed using MAKEDLLVERULL. */
9313 static ULONGLONG
9314 get_dll_version (const char *dll_name)
9315 {
9316 ULONGLONG version = 0;
9317 HINSTANCE hdll = LoadLibrary (dll_name);
9318
9319 if (hdll)
9320 {
9321 DLLGETVERSIONPROC pDllGetVersion
9322 = (DLLGETVERSIONPROC) GetProcAddress (hdll, "DllGetVersion");
9323
9324 if (pDllGetVersion)
9325 {
9326 DLLVERSIONINFO dvi;
9327 HRESULT result;
9328
9329 memset (&dvi, 0, sizeof(dvi));
9330 dvi.cbSize = sizeof(dvi);
9331 result = pDllGetVersion (&dvi);
9332 if (SUCCEEDED (result))
9333 version = MAKEDLLVERULL (dvi.dwMajorVersion, dvi.dwMinorVersion,
9334 0, 0);
9335 }
9336 FreeLibrary (hdll);
9337 }
9338
9339 return version;
9340 }
9341
9342 /* Return the number of bytes in UTF-8 encoded string STR that
9343 corresponds to at most LIM characters. If STR ends before LIM
9344 characters, return the number of bytes in STR including the
9345 terminating null byte. */
9346 static int
9347 utf8_mbslen_lim (const char *str, int lim)
9348 {
9349 const char *p = str;
9350 int mblen = 0, nchars = 0;
9351
9352 while (*p && nchars < lim)
9353 {
9354 int nbytes = CHAR_BYTES (*p);
9355
9356 mblen += nbytes;
9357 nchars++;
9358 p += nbytes;
9359 }
9360
9361 if (!*p && nchars < lim)
9362 mblen++;
9363
9364 return mblen;
9365 }
9366
9367 /* Low-level subroutine to show tray notifications. All strings are
9368 supposed to be unibyte UTF-8 encoded by the caller. */
9369 static EMACS_INT
9370 add_tray_notification (struct frame *f, const char *icon, const char *tip,
9371 enum NI_Severity severity, unsigned timeout,
9372 const char *title, const char *msg)
9373 {
9374 EMACS_INT retval = EMACS_TRAY_NOTIFICATION_ID;
9375
9376 if (FRAME_W32_P (f))
9377 {
9378 MY_NOTIFYICONDATAW nidw;
9379 ULONGLONG shell_dll_version = get_dll_version ("Shell32.dll");
9380 wchar_t tipw[128], msgw[256], titlew[64];
9381 int tiplen;
9382
9383 memset (&nidw, 0, sizeof(nidw));
9384
9385 /* MSDN says the full struct is supported since Vista, whose
9386 Shell32.dll version is said to be 6.0.6. But DllGetVersion
9387 cannot report the 3rd field value, it reports "build number"
9388 instead, which is something else. So we use the Windows 7's
9389 version 6.1 as cutoff, and Vista loses. (Actually, the loss
9390 is not a real one, since we don't expose the hBalloonIcon
9391 member of the struct to Lisp.) */
9392 if (shell_dll_version >= MAKEDLLVERULL (6, 1, 0, 0)) /* >= Windows 7 */
9393 nidw.cbSize = sizeof (nidw);
9394 else if (shell_dll_version >= MAKEDLLVERULL (6, 0, 0, 0)) /* XP */
9395 nidw.cbSize = MYNOTIFYICONDATAW_V3_SIZE;
9396 else if (shell_dll_version >= MAKEDLLVERULL (5, 0, 0, 0)) /* W2K */
9397 nidw.cbSize = MYNOTIFYICONDATAW_V2_SIZE;
9398 else
9399 nidw.cbSize = MYNOTIFYICONDATAW_V1_SIZE; /* < W2K */
9400 nidw.hWnd = FRAME_W32_WINDOW (f);
9401 nidw.uID = EMACS_TRAY_NOTIFICATION_ID;
9402 nidw.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO;
9403 nidw.uCallbackMessage = EMACS_NOTIFICATION_MSG;
9404 if (!*icon)
9405 nidw.hIcon = LoadIcon (hinst, EMACS_CLASS);
9406 else
9407 {
9408 if (w32_unicode_filenames)
9409 {
9410 wchar_t icon_w[MAX_PATH];
9411
9412 if (filename_to_utf16 (icon, icon_w) != 0)
9413 {
9414 errno = ENOENT;
9415 return -1;
9416 }
9417 nidw.hIcon = LoadImageW (NULL, icon_w, IMAGE_ICON, 0, 0,
9418 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9419 }
9420 else
9421 {
9422 char icon_a[MAX_PATH];
9423
9424 if (filename_to_ansi (icon, icon_a) != 0)
9425 {
9426 errno = ENOENT;
9427 return -1;
9428 }
9429 nidw.hIcon = LoadImageA (NULL, icon_a, IMAGE_ICON, 0, 0,
9430 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9431 }
9432 }
9433 if (!nidw.hIcon)
9434 {
9435 switch (GetLastError ())
9436 {
9437 case ERROR_FILE_NOT_FOUND:
9438 errno = ENOENT;
9439 break;
9440 default:
9441 errno = ENOMEM;
9442 break;
9443 }
9444 return -1;
9445 }
9446
9447 /* Windows 9X and NT4 support only 64 characters in the Tip,
9448 later versions support up to 128. */
9449 if (nidw.cbSize == MYNOTIFYICONDATAW_V1_SIZE)
9450 {
9451 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9452 tip, utf8_mbslen_lim (tip, 63),
9453 tipw, 64);
9454 if (tiplen >= 63)
9455 tipw[63] = 0;
9456 }
9457 else
9458 {
9459 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9460 tip, utf8_mbslen_lim (tip, 127),
9461 tipw, 128);
9462 if (tiplen >= 127)
9463 tipw[127] = 0;
9464 }
9465 if (tiplen == 0)
9466 {
9467 errno = EINVAL;
9468 retval = -1;
9469 goto done;
9470 }
9471 wcscpy (nidw.szTip, tipw);
9472
9473 /* The rest of the structure is only supported since Windows 2000. */
9474 if (nidw.cbSize > MYNOTIFYICONDATAW_V1_SIZE)
9475 {
9476 int slen;
9477
9478 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9479 msg, utf8_mbslen_lim (msg, 255),
9480 msgw, 256);
9481 if (slen >= 255)
9482 msgw[255] = 0;
9483 else if (slen == 0)
9484 {
9485 errno = EINVAL;
9486 retval = -1;
9487 goto done;
9488 }
9489 wcscpy (nidw.szInfo, msgw);
9490 nidw.uTimeout = timeout;
9491 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9492 title, utf8_mbslen_lim (title, 63),
9493 titlew, 64);
9494 if (slen >= 63)
9495 titlew[63] = 0;
9496 else if (slen == 0)
9497 {
9498 errno = EINVAL;
9499 retval = -1;
9500 goto done;
9501 }
9502 wcscpy (nidw.szInfoTitle, titlew);
9503
9504 switch (severity)
9505 {
9506 case Ni_None:
9507 nidw.dwInfoFlags = NIIF_NONE;
9508 break;
9509 case Ni_Info:
9510 default:
9511 nidw.dwInfoFlags = NIIF_INFO;
9512 break;
9513 case Ni_Warn:
9514 nidw.dwInfoFlags = NIIF_WARNING;
9515 break;
9516 case Ni_Err:
9517 nidw.dwInfoFlags = NIIF_ERROR;
9518 break;
9519 }
9520 }
9521
9522 if (!Shell_NotifyIconW (NIM_ADD, (PNOTIFYICONDATAW)&nidw))
9523 {
9524 /* GetLastError returns meaningless results when
9525 Shell_NotifyIcon fails. */
9526 DebPrint (("Shell_NotifyIcon ADD failed (err=%d)\n",
9527 GetLastError ()));
9528 errno = EINVAL;
9529 retval = -1;
9530 }
9531 done:
9532 if (*icon && !DestroyIcon (nidw.hIcon))
9533 DebPrint (("DestroyIcon failed (err=%d)\n", GetLastError ()));
9534 }
9535 return retval;
9536 }
9537
9538 /* Low-level subroutine to remove a tray notification. Note: we only
9539 pass the minimum data about the notification: its ID and the handle
9540 of the window to which it sends messages. MSDN doesn't say this is
9541 enough, but it works in practice. This allows us to avoid keeping
9542 the notification data around after we show the notification. */
9543 static void
9544 delete_tray_notification (struct frame *f, int id)
9545 {
9546 if (FRAME_W32_P (f))
9547 {
9548 MY_NOTIFYICONDATAW nidw;
9549
9550 memset (&nidw, 0, sizeof(nidw));
9551 nidw.hWnd = FRAME_W32_WINDOW (f);
9552 nidw.uID = id;
9553
9554 if (!Shell_NotifyIconW (NIM_DELETE, (PNOTIFYICONDATAW)&nidw))
9555 {
9556 /* GetLastError returns meaningless results when
9557 Shell_NotifyIcon fails. */
9558 DebPrint (("Shell_NotifyIcon DELETE failed\n"));
9559 errno = EINVAL;
9560 return;
9561 }
9562 }
9563 return;
9564 }
9565
9566 DEFUN ("w32-notification-notify",
9567 Fw32_notification_notify, Sw32_notification_notify,
9568 0, MANY, 0,
9569 doc: /* Display an MS-Windows tray notification as specified by PARAMS.
9570
9571 Value is the integer unique ID of the notification that can be used
9572 to remove the notification using `w32-notification-close', which see.
9573 If the function fails, the return value is nil.
9574
9575 Tray notifications, a.k.a. \"taskbar messages\", are messages that
9576 inform the user about events unrelated to the current user activity,
9577 such as a significant system event, by briefly displaying informative
9578 text in a balloon from an icon in the notification area of the taskbar.
9579
9580 Parameters in PARAMS are specified as keyword/value pairs. All the
9581 parameters are optional, but if no parameters are specified, the
9582 function will do nothing and return nil.
9583
9584 The following parameters are supported:
9585
9586 :icon ICON -- Display ICON in the system tray. If ICON is a string,
9587 it should specify a file name from which to load the
9588 icon; the specified file should be a .ico Windows icon
9589 file. If ICON is not a string, or if this parameter
9590 is not specified, the standard Emacs icon will be used.
9591
9592 :tip TIP -- Use TIP as the tooltip for the notification. If TIP
9593 is a string, this is the text of a tooltip that will
9594 be shown when the mouse pointer hovers over the tray
9595 icon added by the notification. If TIP is not a
9596 string, or if this parameter is not specified, the
9597 default tooltip text is \"Emacs notification\". The
9598 tooltip text can be up to 127 characters long (63
9599 on Windows versions before W2K). Longer strings
9600 will be truncated.
9601
9602 :level LEVEL -- Notification severity level, one of `info',
9603 `warning', or `error'. If given, the value
9604 determines the icon displayed to the left of the
9605 notification title, but only if the `:title'
9606 parameter (see below) is also specified and is a
9607 string.
9608
9609 :title TITLE -- The title of the notification. If TITLE is a string,
9610 it is displayed in a larger font immediately above
9611 the body text. The title text can be up to 63
9612 characters long; longer text will be truncated.
9613
9614 :body BODY -- The body of the notification. If BODY is a string,
9615 it specifies the text of the notification message.
9616 Use embedded newlines to control how the text is
9617 broken into lines. The body text can be up to 255
9618 characters long, and will be truncated if it's longer.
9619
9620 Note that versions of Windows before W2K support only `:icon' and `:tip'.
9621 You can pass the other parameters, but they will be ignored on those
9622 old systems.
9623
9624 There can be at most one active notification at any given time. An
9625 active notification must be removed by calling `w32-notification-close'
9626 before a new one can be shown.
9627
9628 usage: (w32-notification-notify &rest PARAMS) */)
9629 (ptrdiff_t nargs, Lisp_Object *args)
9630 {
9631 struct frame *f = SELECTED_FRAME ();
9632 Lisp_Object arg_plist, lres;
9633 EMACS_INT retval;
9634 char *icon, *tip, *title, *msg;
9635 enum NI_Severity severity;
9636 unsigned timeout = 0;
9637
9638 if (nargs == 0)
9639 return Qnil;
9640
9641 arg_plist = Flist (nargs, args);
9642
9643 /* Icon. */
9644 lres = Fplist_get (arg_plist, QCicon);
9645 if (STRINGP (lres))
9646 icon = SSDATA (ENCODE_FILE (Fexpand_file_name (lres, Qnil)));
9647 else
9648 icon = (char *)"";
9649
9650 /* Tip. */
9651 lres = Fplist_get (arg_plist, QCtip);
9652 if (STRINGP (lres))
9653 tip = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9654 else
9655 tip = (char *)"Emacs notification";
9656
9657 /* Severity. */
9658 lres = Fplist_get (arg_plist, QClevel);
9659 if (NILP (lres))
9660 severity = Ni_None;
9661 else if (EQ (lres, Qinfo))
9662 severity = Ni_Info;
9663 else if (EQ (lres, Qwarning))
9664 severity = Ni_Warn;
9665 else if (EQ (lres, Qerror))
9666 severity = Ni_Err;
9667 else
9668 severity = Ni_Info;
9669
9670 /* Title. */
9671 lres = Fplist_get (arg_plist, QCtitle);
9672 if (STRINGP (lres))
9673 title = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9674 else
9675 title = (char *)"";
9676
9677 /* Notification body text. */
9678 lres = Fplist_get (arg_plist, QCbody);
9679 if (STRINGP (lres))
9680 msg = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9681 else
9682 msg = (char *)"";
9683
9684 /* Do it! */
9685 retval = add_tray_notification (f, icon, tip, severity, timeout, title, msg);
9686 return (retval < 0 ? Qnil : make_number (retval));
9687 }
9688
9689 DEFUN ("w32-notification-close",
9690 Fw32_notification_close, Sw32_notification_close,
9691 1, 1, 0,
9692 doc: /* Remove the MS-Windows tray notification specified by its ID. */)
9693 (Lisp_Object id)
9694 {
9695 struct frame *f = SELECTED_FRAME ();
9696
9697 if (INTEGERP (id))
9698 delete_tray_notification (f, XINT (id));
9699
9700 return Qnil;
9701 }
9702
9703 #endif /* WINDOWSNT && !HAVE_DBUS */
9704
9705 \f
9706 /***********************************************************************
9707 Initialization
9708 ***********************************************************************/
9709
9710 /* Keep this list in the same order as frame_parms in frame.c.
9711 Use 0 for unsupported frame parameters. */
9712
9713 frame_parm_handler w32_frame_parm_handlers[] =
9714 {
9715 x_set_autoraise,
9716 x_set_autolower,
9717 x_set_background_color,
9718 x_set_border_color,
9719 x_set_border_width,
9720 x_set_cursor_color,
9721 x_set_cursor_type,
9722 x_set_font,
9723 x_set_foreground_color,
9724 x_set_icon_name,
9725 x_set_icon_type,
9726 x_set_internal_border_width,
9727 x_set_right_divider_width,
9728 x_set_bottom_divider_width,
9729 x_set_menu_bar_lines,
9730 x_set_mouse_color,
9731 x_explicitly_set_name,
9732 x_set_scroll_bar_width,
9733 x_set_scroll_bar_height,
9734 x_set_title,
9735 x_set_unsplittable,
9736 x_set_vertical_scroll_bars,
9737 x_set_horizontal_scroll_bars,
9738 x_set_visibility,
9739 x_set_tool_bar_lines,
9740 0, /* x_set_scroll_bar_foreground, */
9741 0, /* x_set_scroll_bar_background, */
9742 x_set_screen_gamma,
9743 x_set_line_spacing,
9744 x_set_left_fringe,
9745 x_set_right_fringe,
9746 0, /* x_set_wait_for_wm, */
9747 x_set_fullscreen,
9748 x_set_font_backend,
9749 x_set_alpha,
9750 0, /* x_set_sticky */
9751 0, /* x_set_tool_bar_position */
9752 };
9753
9754 void
9755 syms_of_w32fns (void)
9756 {
9757 globals_of_w32fns ();
9758 track_mouse_window = NULL;
9759
9760 w32_visible_system_caret_hwnd = NULL;
9761
9762 DEFSYM (Qundefined_color, "undefined-color");
9763 DEFSYM (Qcancel_timer, "cancel-timer");
9764 DEFSYM (Qhyper, "hyper");
9765 DEFSYM (Qsuper, "super");
9766 DEFSYM (Qmeta, "meta");
9767 DEFSYM (Qalt, "alt");
9768 DEFSYM (Qctrl, "ctrl");
9769 DEFSYM (Qcontrol, "control");
9770 DEFSYM (Qshift, "shift");
9771 DEFSYM (Qfont_parameter, "font-parameter");
9772 DEFSYM (Qgeometry, "geometry");
9773 DEFSYM (Qworkarea, "workarea");
9774 DEFSYM (Qmm_size, "mm-size");
9775 DEFSYM (Qframes, "frames");
9776 DEFSYM (Qassq_delete_all, "assq-delete-all");
9777 DEFSYM (Qunicode_sip, "unicode-sip");
9778 #if defined WINDOWSNT && !defined HAVE_DBUS
9779 DEFSYM (QCicon, ":icon");
9780 DEFSYM (QCtip, ":tip");
9781 DEFSYM (QClevel, ":level");
9782 DEFSYM (Qinfo, "info");
9783 DEFSYM (Qwarning, "warning");
9784 DEFSYM (QCtitle, ":title");
9785 DEFSYM (QCbody, ":body");
9786 #endif
9787
9788 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
9789 DEFSYM (Qgnutls, "gnutls");
9790 DEFSYM (Qlibxml2, "libxml2");
9791 DEFSYM (Qserif, "serif");
9792 DEFSYM (Qzlib, "zlib");
9793
9794 Fput (Qundefined_color, Qerror_conditions,
9795 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
9796 Fput (Qundefined_color, Qerror_message,
9797 build_pure_c_string ("Undefined color"));
9798
9799 staticpro (&w32_grabbed_keys);
9800 w32_grabbed_keys = Qnil;
9801
9802 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
9803 doc: /* An array of color name mappings for Windows. */);
9804 Vw32_color_map = Qnil;
9805
9806 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
9807 doc: /* Non-nil if Alt key presses are passed on to Windows.
9808 When non-nil, for example, Alt pressed and released and then space will
9809 open the System menu. When nil, Emacs processes the Alt key events, and
9810 then silently swallows them. */);
9811 Vw32_pass_alt_to_system = Qnil;
9812
9813 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
9814 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
9815 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
9816 Vw32_alt_is_meta = Qt;
9817
9818 DEFVAR_INT ("w32-quit-key", w32_quit_key,
9819 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
9820 w32_quit_key = 0;
9821
9822 DEFVAR_LISP ("w32-pass-lwindow-to-system",
9823 Vw32_pass_lwindow_to_system,
9824 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
9825
9826 When non-nil, the Start menu is opened by tapping the key.
9827 If you set this to nil, the left \"Windows\" key is processed by Emacs
9828 according to the value of `w32-lwindow-modifier', which see.
9829
9830 Note that some combinations of the left \"Windows\" key with other
9831 keys are caught by Windows at low level. For example, <lwindow>-r
9832 pops up the Windows Run dialog, <lwindow>-<Pause> pops up the "System
9833 Properties" dialog, etc. On Windows 10, no \"Windows\" key
9834 combinations are normally handed to applications. To enable Emacs to
9835 process \"Windows\" key combinations, use the function
9836 `w32-register-hot-key`.
9837
9838 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
9839 Vw32_pass_lwindow_to_system = Qt;
9840
9841 DEFVAR_LISP ("w32-pass-rwindow-to-system",
9842 Vw32_pass_rwindow_to_system,
9843 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
9844
9845 When non-nil, the Start menu is opened by tapping the key.
9846 If you set this to nil, the right \"Windows\" key is processed by Emacs
9847 according to the value of `w32-rwindow-modifier', which see.
9848
9849 Note that some combinations of the right \"Windows\" key with other
9850 keys are caught by Windows at low level. For example, <rwindow>-r
9851 pops up the Windows Run dialog, <rwindow>-<Pause> pops up the "System
9852 Properties" dialog, etc. On Windows 10, no \"Windows\" key
9853 combinations are normally handed to applications. To enable Emacs to
9854 process \"Windows\" key combinations, use the function
9855 `w32-register-hot-key`.
9856
9857 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
9858 Vw32_pass_rwindow_to_system = Qt;
9859
9860 DEFVAR_LISP ("w32-phantom-key-code",
9861 Vw32_phantom_key_code,
9862 doc: /* Virtual key code used to generate \"phantom\" key presses.
9863 Value is a number between 0 and 255.
9864
9865 Phantom key presses are generated in order to stop the system from
9866 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
9867 `w32-pass-rwindow-to-system' is nil.
9868
9869 This variable is only used on Windows 98 and ME. For other Windows
9870 versions, see the documentation of the `w32-register-hot-key`
9871 function. */);
9872 /* Although 255 is technically not a valid key code, it works and
9873 means that this hack won't interfere with any real key code. */
9874 XSETINT (Vw32_phantom_key_code, 255);
9875
9876 DEFVAR_LISP ("w32-enable-num-lock",
9877 Vw32_enable_num_lock,
9878 doc: /* If non-nil, the Num Lock key acts normally.
9879 Set to nil to handle Num Lock as the `kp-numlock' key. */);
9880 Vw32_enable_num_lock = Qt;
9881
9882 DEFVAR_LISP ("w32-enable-caps-lock",
9883 Vw32_enable_caps_lock,
9884 doc: /* If non-nil, the Caps Lock key acts normally.
9885 Set to nil to handle Caps Lock as the `capslock' key. */);
9886 Vw32_enable_caps_lock = Qt;
9887
9888 DEFVAR_LISP ("w32-scroll-lock-modifier",
9889 Vw32_scroll_lock_modifier,
9890 doc: /* Modifier to use for the Scroll Lock ON state.
9891 The value can be hyper, super, meta, alt, control or shift for the
9892 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
9893 Any other value will cause the Scroll Lock key to be ignored. */);
9894 Vw32_scroll_lock_modifier = Qnil;
9895
9896 DEFVAR_LISP ("w32-lwindow-modifier",
9897 Vw32_lwindow_modifier,
9898 doc: /* Modifier to use for the left \"Windows\" key.
9899 The value can be hyper, super, meta, alt, control or shift for the
9900 respective modifier, or nil to appear as the `lwindow' key.
9901 Any other value will cause the key to be ignored.
9902
9903 Also see the documentation of the `w32-register-hot-key` function. */);
9904 Vw32_lwindow_modifier = Qnil;
9905
9906 DEFVAR_LISP ("w32-rwindow-modifier",
9907 Vw32_rwindow_modifier,
9908 doc: /* Modifier to use for the right \"Windows\" key.
9909 The value can be hyper, super, meta, alt, control or shift for the
9910 respective modifier, or nil to appear as the `rwindow' key.
9911 Any other value will cause the key to be ignored.
9912
9913 Also see the documentation of the `w32-register-hot-key` function. */);
9914 Vw32_rwindow_modifier = Qnil;
9915
9916 DEFVAR_LISP ("w32-apps-modifier",
9917 Vw32_apps_modifier,
9918 doc: /* Modifier to use for the \"Apps\" key.
9919 The value can be hyper, super, meta, alt, control or shift for the
9920 respective modifier, or nil to appear as the `apps' key.
9921 Any other value will cause the key to be ignored. */);
9922 Vw32_apps_modifier = Qnil;
9923
9924 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
9925 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
9926 w32_enable_synthesized_fonts = 0;
9927
9928 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
9929 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
9930 Vw32_enable_palette = Qt;
9931
9932 DEFVAR_INT ("w32-mouse-button-tolerance",
9933 w32_mouse_button_tolerance,
9934 doc: /* Analogue of double click interval for faking middle mouse events.
9935 The value is the minimum time in milliseconds that must elapse between
9936 left and right button down events before they are considered distinct events.
9937 If both mouse buttons are depressed within this interval, a middle mouse
9938 button down event is generated instead. */);
9939 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
9940
9941 DEFVAR_INT ("w32-mouse-move-interval",
9942 w32_mouse_move_interval,
9943 doc: /* Minimum interval between mouse move events.
9944 The value is the minimum time in milliseconds that must elapse between
9945 successive mouse move (or scroll bar drag) events before they are
9946 reported as lisp events. */);
9947 w32_mouse_move_interval = 0;
9948
9949 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
9950 w32_pass_extra_mouse_buttons_to_system,
9951 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
9952 Recent versions of Windows support mice with up to five buttons.
9953 Since most applications don't support these extra buttons, most mouse
9954 drivers will allow you to map them to functions at the system level.
9955 If this variable is non-nil, Emacs will pass them on, allowing the
9956 system to handle them. */);
9957 w32_pass_extra_mouse_buttons_to_system = 0;
9958
9959 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
9960 w32_pass_multimedia_buttons_to_system,
9961 doc: /* If non-nil, media buttons are passed to Windows.
9962 Some modern keyboards contain buttons for controlling media players, web
9963 browsers and other applications. Generally these buttons are handled on a
9964 system wide basis, but by setting this to nil they are made available
9965 to Emacs for binding. Depending on your keyboard, additional keys that
9966 may be available are:
9967
9968 browser-back, browser-forward, browser-refresh, browser-stop,
9969 browser-search, browser-favorites, browser-home,
9970 mail, mail-reply, mail-forward, mail-send,
9971 app-1, app-2,
9972 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
9973 spell-check, correction-list, toggle-dictate-command,
9974 media-next, media-previous, media-stop, media-play-pause, media-select,
9975 media-play, media-pause, media-record, media-fast-forward, media-rewind,
9976 media-channel-up, media-channel-down,
9977 volume-mute, volume-up, volume-down,
9978 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
9979 bass-down, bass-boost, bass-up, treble-down, treble-up */);
9980 w32_pass_multimedia_buttons_to_system = 1;
9981
9982 #if 0 /* TODO: Mouse cursor customization. */
9983 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
9984 doc: /* The shape of the pointer when over text.
9985 Changing the value does not affect existing frames
9986 unless you set the mouse color. */);
9987 Vx_pointer_shape = Qnil;
9988
9989 Vx_nontext_pointer_shape = Qnil;
9990
9991 Vx_mode_pointer_shape = Qnil;
9992
9993 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
9994 doc: /* The shape of the pointer when Emacs is busy.
9995 This variable takes effect when you create a new frame
9996 or when you set the mouse color. */);
9997 Vx_hourglass_pointer_shape = Qnil;
9998
9999 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
10000 Vx_sensitive_text_pointer_shape,
10001 doc: /* The shape of the pointer when over mouse-sensitive text.
10002 This variable takes effect when you create a new frame
10003 or when you set the mouse color. */);
10004 Vx_sensitive_text_pointer_shape = Qnil;
10005
10006 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
10007 Vx_window_horizontal_drag_shape,
10008 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
10009 This variable takes effect when you create a new frame
10010 or when you set the mouse color. */);
10011 Vx_window_horizontal_drag_shape = Qnil;
10012
10013 DEFVAR_LISP ("x-window-vertical-drag-cursor",
10014 Vx_window_vertical_drag_shape,
10015 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
10016 This variable takes effect when you create a new frame
10017 or when you set the mouse color. */);
10018 Vx_window_vertical_drag_shape = Qnil;
10019 #endif
10020
10021 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
10022 doc: /* A string indicating the foreground color of the cursor box. */);
10023 Vx_cursor_fore_pixel = Qnil;
10024
10025 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
10026 doc: /* Maximum size for tooltips.
10027 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
10028 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
10029
10030 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
10031 doc: /* Non-nil if no window manager is in use.
10032 Emacs doesn't try to figure this out; this is always nil
10033 unless you set it to something else. */);
10034 /* We don't have any way to find this out, so set it to nil
10035 and maybe the user would like to set it to t. */
10036 Vx_no_window_manager = Qnil;
10037
10038 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
10039 Vx_pixel_size_width_font_regexp,
10040 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
10041
10042 Since Emacs gets width of a font matching with this regexp from
10043 PIXEL_SIZE field of the name, font finding mechanism gets faster for
10044 such a font. This is especially effective for such large fonts as
10045 Chinese, Japanese, and Korean. */);
10046 Vx_pixel_size_width_font_regexp = Qnil;
10047
10048 DEFVAR_LISP ("w32-bdf-filename-alist",
10049 Vw32_bdf_filename_alist,
10050 doc: /* List of bdf fonts and their corresponding filenames. */);
10051 Vw32_bdf_filename_alist = Qnil;
10052
10053 DEFVAR_BOOL ("w32-strict-fontnames",
10054 w32_strict_fontnames,
10055 doc: /* Non-nil means only use fonts that are exact matches for those requested.
10056 Default is nil, which allows old fontnames that are not XLFD compliant,
10057 and allows third-party CJK display to work by specifying false charset
10058 fields to trick Emacs into translating to Big5, SJIS etc.
10059 Setting this to t will prevent wrong fonts being selected when
10060 fontsets are automatically created. */);
10061 w32_strict_fontnames = 0;
10062
10063 DEFVAR_BOOL ("w32-strict-painting",
10064 w32_strict_painting,
10065 doc: /* Non-nil means use strict rules for repainting frames.
10066 Set this to nil to get the old behavior for repainting; this should
10067 only be necessary if the default setting causes problems. */);
10068 w32_strict_painting = 1;
10069
10070 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
10071 w32_use_fallback_wm_chars_method,
10072 doc: /* Non-nil means use old method of processing character keys.
10073 This is intended only for debugging of the new processing method.
10074 Default is nil.
10075
10076 This variable has effect only on NT family of systems, not on Windows 9X. */);
10077 w32_use_fallback_wm_chars_method = 0;
10078
10079 DEFVAR_BOOL ("w32-disable-new-uniscribe-apis",
10080 w32_disable_new_uniscribe_apis,
10081 doc: /* Non-nil means don't use new Uniscribe APIs.
10082 The new APIs are used to access OTF features supported by fonts.
10083 This is intended only for debugging of the new Uniscribe-related code.
10084 Default is nil.
10085
10086 This variable has effect only on Windows Vista and later. */);
10087 w32_disable_new_uniscribe_apis = 0;
10088
10089 DEFVAR_LISP ("w32-tooltip-extra-pixels",
10090 Vw32_tooltip_extra_pixels,
10091 doc: /* Number of pixels added after tooltip text.
10092 On Windows some fonts may cause the last character of a tooltip be
10093 truncated or wrapped around to the next line. Adding some extra space
10094 at the end of the toooltip works around this problem.
10095
10096 This variable specifies the number of pixels that shall be added. The
10097 default value t means to add the width of one canonical character of the
10098 tip frame. */);
10099 Vw32_tooltip_extra_pixels = Qt;
10100
10101 #if 0 /* TODO: Port to W32 */
10102 defsubr (&Sx_change_window_property);
10103 defsubr (&Sx_delete_window_property);
10104 defsubr (&Sx_window_property);
10105 #endif
10106 defsubr (&Sxw_display_color_p);
10107 defsubr (&Sx_display_grayscale_p);
10108 defsubr (&Sxw_color_defined_p);
10109 defsubr (&Sxw_color_values);
10110 defsubr (&Sx_server_max_request_size);
10111 defsubr (&Sx_server_vendor);
10112 defsubr (&Sx_server_version);
10113 defsubr (&Sx_display_pixel_width);
10114 defsubr (&Sx_display_pixel_height);
10115 defsubr (&Sx_display_mm_width);
10116 defsubr (&Sx_display_mm_height);
10117 defsubr (&Sx_display_screens);
10118 defsubr (&Sx_display_planes);
10119 defsubr (&Sx_display_color_cells);
10120 defsubr (&Sx_display_visual_class);
10121 defsubr (&Sx_display_backing_store);
10122 defsubr (&Sx_display_save_under);
10123 defsubr (&Sx_create_frame);
10124 defsubr (&Sx_open_connection);
10125 defsubr (&Sx_close_connection);
10126 defsubr (&Sx_display_list);
10127 defsubr (&Sw32_frame_geometry);
10128 defsubr (&Sw32_frame_edges);
10129 defsubr (&Sw32_mouse_absolute_pixel_position);
10130 defsubr (&Sw32_set_mouse_absolute_pixel_position);
10131 defsubr (&Sx_synchronize);
10132
10133 /* W32 specific functions */
10134
10135 defsubr (&Sw32_define_rgb_color);
10136 defsubr (&Sw32_default_color_map);
10137 defsubr (&Sw32_display_monitor_attributes_list);
10138 defsubr (&Sw32_send_sys_command);
10139 defsubr (&Sw32_shell_execute);
10140 defsubr (&Sw32_register_hot_key);
10141 defsubr (&Sw32_unregister_hot_key);
10142 defsubr (&Sw32_registered_hot_keys);
10143 defsubr (&Sw32_reconstruct_hot_key);
10144 defsubr (&Sw32_toggle_lock_key);
10145 defsubr (&Sw32_window_exists_p);
10146 defsubr (&Sw32_battery_status);
10147 defsubr (&Sw32__menu_bar_in_use);
10148 #if defined WINDOWSNT && !defined HAVE_DBUS
10149 defsubr (&Sw32_notification_notify);
10150 defsubr (&Sw32_notification_close);
10151 #endif
10152
10153 #ifdef WINDOWSNT
10154 defsubr (&Sfile_system_info);
10155 defsubr (&Sdefault_printer_name);
10156 #endif
10157
10158 defsubr (&Sset_message_beep);
10159 defsubr (&Sx_show_tip);
10160 defsubr (&Sx_hide_tip);
10161
10162 defsubr (&Sx_file_dialog);
10163 #ifdef WINDOWSNT
10164 defsubr (&Ssystem_move_file_to_trash);
10165 #endif
10166 }
10167
10168 \f
10169
10170 /* Crashing and reporting backtrace. */
10171
10172 #ifndef CYGWIN
10173 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
10174 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
10175 #endif
10176 static DWORD except_code;
10177 static PVOID except_addr;
10178
10179 #ifndef CYGWIN
10180
10181 /* Stack overflow recovery. */
10182
10183 /* MinGW headers don't declare this (should be in malloc.h). Also,
10184 the function is not present pre-W2K, so make the call through
10185 a function pointer. */
10186 typedef int (__cdecl *_resetstkoflw_proc) (void);
10187 static _resetstkoflw_proc resetstkoflw;
10188
10189 /* Re-establish the guard page at stack limit. This is needed because
10190 when a stack overflow is detected, Windows removes the guard bit
10191 from the guard page, so if we don't re-establish that protection,
10192 the next stack overflow will cause a crash. */
10193 void
10194 w32_reset_stack_overflow_guard (void)
10195 {
10196 if (resetstkoflw == NULL)
10197 resetstkoflw =
10198 (_resetstkoflw_proc)GetProcAddress (GetModuleHandle ("msvcrt.dll"),
10199 "_resetstkoflw");
10200 /* We ignore the return value. If _resetstkoflw fails, the next
10201 stack overflow will crash the program. */
10202 if (resetstkoflw != NULL)
10203 (void)resetstkoflw ();
10204 }
10205
10206 static void
10207 stack_overflow_handler (void)
10208 {
10209 /* Hard GC error may lead to stack overflow caused by
10210 too nested calls to mark_object. No way to survive. */
10211 if (gc_in_progress)
10212 terminate_due_to_signal (SIGSEGV, 40);
10213 #ifdef _WIN64
10214 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
10215 __builtin_longjmp (return_to_command_loop, 1);
10216 #else
10217 sys_longjmp (return_to_command_loop, 1);
10218 #endif
10219 }
10220
10221 /* This handler records the exception code and the address where it
10222 was triggered so that this info could be included in the backtrace.
10223 Without that, the backtrace in some cases has no information
10224 whatsoever about the offending code, and looks as if the top-level
10225 exception handler in the MinGW startup code was the one that
10226 crashed. We also recover from stack overflow, by calling our stack
10227 overflow handler that jumps back to top level. */
10228 static LONG CALLBACK
10229 my_exception_handler (EXCEPTION_POINTERS * exception_data)
10230 {
10231 except_code = exception_data->ExceptionRecord->ExceptionCode;
10232 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
10233
10234 /* If this is a stack overflow exception, attempt to recover. */
10235 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
10236 && exception_data->ExceptionRecord->NumberParameters == 2
10237 /* We can only longjmp to top level from the main thread. */
10238 && GetCurrentThreadId () == dwMainThreadId)
10239 {
10240 /* Call stack_overflow_handler (). */
10241 #ifdef _WIN64
10242 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
10243 #else
10244 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
10245 #endif
10246 /* Zero this out, so the stale address of the stack overflow
10247 exception we handled is not displayed in some future
10248 unrelated crash. */
10249 except_addr = 0;
10250 return EXCEPTION_CONTINUE_EXECUTION;
10251 }
10252
10253 if (prev_exception_handler)
10254 return prev_exception_handler (exception_data);
10255 return EXCEPTION_EXECUTE_HANDLER;
10256 }
10257 #endif
10258
10259 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
10260 PULONG);
10261
10262 #define BACKTRACE_LIMIT_MAX 62
10263
10264 static int
10265 w32_backtrace (void **buffer, int limit)
10266 {
10267 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
10268 HMODULE hm_kernel32 = NULL;
10269
10270 if (!s_pfn_CaptureStackBackTrace)
10271 {
10272 hm_kernel32 = LoadLibrary ("Kernel32.dll");
10273 s_pfn_CaptureStackBackTrace =
10274 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
10275 "RtlCaptureStackBackTrace");
10276 }
10277 if (s_pfn_CaptureStackBackTrace)
10278 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
10279 buffer, NULL);
10280 return 0;
10281 }
10282
10283 void
10284 emacs_abort (void)
10285 {
10286 int button;
10287 button = MessageBox (NULL,
10288 "A fatal error has occurred!\n\n"
10289 "Would you like to attach a debugger?\n\n"
10290 "Select:\n"
10291 "YES -- to debug Emacs, or\n"
10292 "NO -- to abort Emacs and produce a backtrace\n"
10293 " (emacs_backtrace.txt in current directory)."
10294 #if __GNUC__
10295 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
10296 "\"continue\" inside GDB before clicking YES.)"
10297 #endif
10298 , "Emacs Abort Dialog",
10299 MB_ICONEXCLAMATION | MB_TASKMODAL
10300 | MB_SETFOREGROUND | MB_YESNO);
10301 switch (button)
10302 {
10303 case IDYES:
10304 DebugBreak ();
10305 exit (2); /* tell the compiler we will never return */
10306 case IDNO:
10307 default:
10308 {
10309 void *stack[BACKTRACE_LIMIT_MAX + 1];
10310 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
10311
10312 if (i)
10313 {
10314 int errfile_fd = -1;
10315 int j;
10316 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
10317 /* The type below should really be 'void *', but
10318 INT_BUFSIZE_BOUND cannot handle that without
10319 triggering compiler warnings (under certain
10320 pedantic warning switches), it wants an
10321 integer type. */
10322 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
10323 #ifdef CYGWIN
10324 int stderr_fd = 2;
10325 #else
10326 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
10327 int stderr_fd = -1;
10328
10329 if (errout && errout != INVALID_HANDLE_VALUE)
10330 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
10331 #endif
10332
10333 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
10334 but not on Windows 7. addr2line doesn't mind a missing
10335 "0x", but will be confused by an extra one. */
10336 if (except_addr)
10337 sprintf (buf, "\r\nException 0x%x at this address:\r\n%p\r\n",
10338 (unsigned int) except_code, except_addr);
10339 if (stderr_fd >= 0)
10340 {
10341 if (except_addr)
10342 write (stderr_fd, buf, strlen (buf));
10343 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
10344 }
10345 #ifdef CYGWIN
10346 #define _open open
10347 #endif
10348 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
10349 if (errfile_fd >= 0)
10350 {
10351 lseek (errfile_fd, 0L, SEEK_END);
10352 if (except_addr)
10353 write (errfile_fd, buf, strlen (buf));
10354 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
10355 }
10356
10357 for (j = 0; j < i; j++)
10358 {
10359 /* stack[] gives the return addresses, whereas we want
10360 the address of the call, so decrease each address
10361 by approximate size of 1 CALL instruction. */
10362 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
10363 if (stderr_fd >= 0)
10364 write (stderr_fd, buf, strlen (buf));
10365 if (errfile_fd >= 0)
10366 write (errfile_fd, buf, strlen (buf));
10367 }
10368 if (i == BACKTRACE_LIMIT_MAX)
10369 {
10370 if (stderr_fd >= 0)
10371 write (stderr_fd, "...\r\n", 5);
10372 if (errfile_fd >= 0)
10373 write (errfile_fd, "...\r\n", 5);
10374 }
10375 if (errfile_fd >= 0)
10376 close (errfile_fd);
10377 }
10378 abort ();
10379 break;
10380 }
10381 }
10382 }
10383
10384 \f
10385
10386 /* Initialization. */
10387
10388 /*
10389 globals_of_w32fns is used to initialize those global variables that
10390 must always be initialized on startup even when the global variable
10391 initialized is non zero (see the function main in emacs.c).
10392 globals_of_w32fns is called from syms_of_w32fns when the global
10393 variable initialized is 0 and directly from main when initialized
10394 is non zero.
10395 */
10396 void
10397 globals_of_w32fns (void)
10398 {
10399 HMODULE user32_lib = GetModuleHandle ("user32.dll");
10400 /*
10401 TrackMouseEvent not available in all versions of Windows, so must load
10402 it dynamically. Do it once, here, instead of every time it is used.
10403 */
10404 track_mouse_event_fn = (TrackMouseEvent_Proc)
10405 GetProcAddress (user32_lib, "TrackMouseEvent");
10406
10407 monitor_from_point_fn = (MonitorFromPoint_Proc)
10408 GetProcAddress (user32_lib, "MonitorFromPoint");
10409 get_monitor_info_fn = (GetMonitorInfo_Proc)
10410 GetProcAddress (user32_lib, "GetMonitorInfoA");
10411 monitor_from_window_fn = (MonitorFromWindow_Proc)
10412 GetProcAddress (user32_lib, "MonitorFromWindow");
10413 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
10414 GetProcAddress (user32_lib, "EnumDisplayMonitors");
10415 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
10416 GetProcAddress (user32_lib, "GetTitleBarInfo");
10417
10418 {
10419 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
10420 get_composition_string_fn = (ImmGetCompositionString_Proc)
10421 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
10422 get_ime_context_fn = (ImmGetContext_Proc)
10423 GetProcAddress (imm32_lib, "ImmGetContext");
10424 release_ime_context_fn = (ImmReleaseContext_Proc)
10425 GetProcAddress (imm32_lib, "ImmReleaseContext");
10426 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
10427 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
10428 }
10429
10430 except_code = 0;
10431 except_addr = 0;
10432 #ifndef CYGWIN
10433 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
10434 resetstkoflw = NULL;
10435 #endif
10436
10437 DEFVAR_INT ("w32-ansi-code-page",
10438 w32_ansi_code_page,
10439 doc: /* The ANSI code page used by the system. */);
10440 w32_ansi_code_page = GetACP ();
10441
10442 if (os_subtype == OS_NT)
10443 w32_unicode_gui = 1;
10444 else
10445 w32_unicode_gui = 0;
10446
10447 after_deadkey = -1;
10448
10449 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
10450 InitCommonControls ();
10451
10452 syms_of_w32uniscribe ();
10453 }
10454
10455 #ifdef NTGUI_UNICODE
10456
10457 Lisp_Object
10458 ntgui_encode_system (Lisp_Object str)
10459 {
10460 Lisp_Object encoded;
10461 to_unicode (str, &encoded);
10462 return encoded;
10463 }
10464
10465 #endif /* NTGUI_UNICODE */