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