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