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