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