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