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