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