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