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