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