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