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