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