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