In w32fns.c condition TITLEBAR_INFO declaration on WINDOWS version.
[emacs.git] / src / w32fns.c
blob189a27c62f1593897b9afc406e22518fdd80a46d
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Added by Kevin Gallo */
22 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <math.h>
29 #include <fcntl.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
34 #include "lisp.h"
35 #include "w32term.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "intervals.h"
41 #include "dispextern.h"
42 #include "keyboard.h"
43 #include "blockinput.h"
44 #include "epaths.h"
45 #include "charset.h"
46 #include "coding.h"
47 #include "ccl.h"
48 #include "fontset.h"
49 #include "systime.h"
50 #include "termhooks.h"
52 #include "w32common.h"
54 #ifdef WINDOWSNT
55 #include "w32heap.h"
56 #include <mbstring.h>
57 #endif /* WINDOWSNT */
59 #if CYGWIN
60 #include "cygw32.h"
61 #else
62 #include "w32.h"
63 #endif
65 #include "bitmaps/gray.xbm"
67 #include <commctrl.h>
68 #include <commdlg.h>
69 #include <shellapi.h>
70 #include <ctype.h>
71 #include <winspool.h>
72 #include <objbase.h>
74 #include <dlgs.h>
75 #include <imm.h>
76 #include <windowsx.h>
78 #include "font.h"
79 #include "w32font.h"
81 #ifndef FOF_NO_CONNECTED_ELEMENTS
82 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
83 #endif
85 void syms_of_w32fns (void);
86 void globals_of_w32fns (void);
88 extern void free_frame_menubar (struct frame *);
89 extern int w32_console_toggle_lock_key (int, Lisp_Object);
90 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
91 extern void w32_free_menu_strings (HWND);
92 extern const char *map_w32_filename (const char *, const char **);
93 extern char * w32_strerror (int error_no);
95 #ifndef IDC_HAND
96 #define IDC_HAND MAKEINTRESOURCE(32649)
97 #endif
99 /* Prefix for system colors. */
100 #define SYSTEM_COLOR_PREFIX "System"
101 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
103 /* State variables for emulating a three button mouse. */
104 #define LMOUSE 1
105 #define MMOUSE 2
106 #define RMOUSE 4
108 static int button_state = 0;
109 static W32Msg saved_mouse_button_msg;
110 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
111 static W32Msg saved_mouse_move_msg;
112 static unsigned mouse_move_timer = 0;
114 /* Window that is tracking the mouse. */
115 static HWND track_mouse_window;
117 /* Multi-monitor API definitions that are not pulled from the headers
118 since we are compiling for NT 4. */
119 #ifndef MONITOR_DEFAULT_TO_NEAREST
120 #define MONITOR_DEFAULT_TO_NEAREST 2
121 #endif
122 #ifndef MONITORINFOF_PRIMARY
123 #define MONITORINFOF_PRIMARY 1
124 #endif
125 #ifndef SM_XVIRTUALSCREEN
126 #define SM_XVIRTUALSCREEN 76
127 #endif
128 #ifndef SM_YVIRTUALSCREEN
129 #define SM_YVIRTUALSCREEN 77
130 #endif
131 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
132 To avoid a compile error on one or the other, redefine with a new name. */
133 struct MONITOR_INFO
135 DWORD cbSize;
136 RECT rcMonitor;
137 RECT rcWork;
138 DWORD dwFlags;
141 #if _WIN32_WINDOWS >= 0x0410
142 #define C_CHILDREN_TITLEBAR CCHILDREN_TITLEBAR
143 typedef TITLEBARINFO TITLEBAR_INFO;
144 #else
145 #define C_CHILDREN_TITLEBAR 5
146 typedef struct
148 DWORD cbSize;
149 RECT rcTitleBar;
150 DWORD rgstate[C_CHILDREN_TITLEBAR+1];
151 } TITLEBAR_INFO, *PTITLEBAR_INFO;
152 #endif
154 #ifndef CCHDEVICENAME
155 #define CCHDEVICENAME 32
156 #endif
157 struct MONITOR_INFO_EX
159 DWORD cbSize;
160 RECT rcMonitor;
161 RECT rcWork;
162 DWORD dwFlags;
163 char szDevice[CCHDEVICENAME];
166 /* Reportedly, MSVC does not have this in its headers. */
167 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
168 DECLARE_HANDLE(HMONITOR);
169 #endif
171 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
172 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
173 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
174 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
175 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
176 typedef BOOL (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
177 typedef BOOL (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
178 IN COMPOSITIONFORM *form);
179 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
180 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
181 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
182 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
183 (IN HWND hwnd, IN DWORD dwFlags);
184 typedef BOOL CALLBACK (* MonitorEnum_Proc)
185 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
186 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
187 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
188 typedef BOOL (WINAPI * GetTitleBarInfo_Proc)
189 (IN HWND hwnd, OUT TITLEBAR_INFO* info);
191 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
192 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
193 ImmGetContext_Proc get_ime_context_fn = NULL;
194 ImmReleaseContext_Proc release_ime_context_fn = NULL;
195 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
196 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
197 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
198 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
199 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
200 GetTitleBarInfo_Proc get_title_bar_info_fn = NULL;
202 #ifdef NTGUI_UNICODE
203 #define unicode_append_menu AppendMenuW
204 #else /* !NTGUI_UNICODE */
205 extern AppendMenuW_Proc unicode_append_menu;
206 #endif /* NTGUI_UNICODE */
208 /* Flag to selectively ignore WM_IME_CHAR messages. */
209 static int ignore_ime_char = 0;
211 /* W95 mousewheel handler */
212 unsigned int msh_mousewheel = 0;
214 /* Timers */
215 #define MOUSE_BUTTON_ID 1
216 #define MOUSE_MOVE_ID 2
217 #define MENU_FREE_ID 3
218 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
219 is received. */
220 #define MENU_FREE_DELAY 1000
221 static unsigned menu_free_timer = 0;
223 #ifdef GLYPH_DEBUG
224 static ptrdiff_t image_cache_refcount;
225 static int dpyinfo_refcount;
226 #endif
228 static HWND w32_visible_system_caret_hwnd;
230 static int w32_unicode_gui;
232 /* From w32menu.c */
233 extern HMENU current_popup_menu;
234 int menubar_in_use = 0;
236 /* From w32uniscribe.c */
237 extern void syms_of_w32uniscribe (void);
238 extern int uniscribe_available;
240 #ifdef WINDOWSNT
241 /* From w32inevt.c */
242 extern int faked_key;
243 #endif /* WINDOWSNT */
245 /* This gives us the page size and the size of the allocation unit on NT. */
246 SYSTEM_INFO sysinfo_cache;
248 /* This gives us version, build, and platform identification. */
249 OSVERSIONINFO osinfo_cache;
251 DWORD_PTR syspage_mask = 0;
253 /* The major and minor versions of NT. */
254 int w32_major_version;
255 int w32_minor_version;
256 int w32_build_number;
258 /* Distinguish between Windows NT and Windows 95. */
259 int os_subtype;
261 #ifdef HAVE_NTGUI
262 HINSTANCE hinst = NULL;
263 #endif
265 static unsigned int sound_type = 0xFFFFFFFF;
266 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
268 /* Let the user specify a display with a frame.
269 nil stands for the selected frame--or, if that is not a w32 frame,
270 the first display on the list. */
272 struct w32_display_info *
273 check_x_display_info (Lisp_Object object)
275 if (NILP (object))
277 struct frame *sf = XFRAME (selected_frame);
279 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
280 return FRAME_DISPLAY_INFO (sf);
281 else
282 return &one_w32_display_info;
284 else if (TERMINALP (object))
286 struct terminal *t = decode_live_terminal (object);
288 if (t->type != output_w32)
289 error ("Terminal %d is not a W32 display", t->id);
291 return t->display_info.w32;
293 else if (STRINGP (object))
294 return x_display_info_for_name (object);
295 else
297 struct frame *f;
299 CHECK_LIVE_FRAME (object);
300 f = XFRAME (object);
301 if (! FRAME_W32_P (f))
302 error ("Non-W32 frame used");
303 return FRAME_DISPLAY_INFO (f);
307 /* Return the Emacs frame-object corresponding to an w32 window.
308 It could be the frame's main window or an icon window. */
310 struct frame *
311 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
313 Lisp_Object tail, frame;
314 struct frame *f;
316 FOR_EACH_FRAME (tail, frame)
318 f = XFRAME (frame);
319 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
320 continue;
322 if (FRAME_W32_WINDOW (f) == wdesc)
323 return f;
325 return 0;
329 static Lisp_Object unwind_create_frame (Lisp_Object);
330 static void unwind_create_tip_frame (Lisp_Object);
331 static void my_create_window (struct frame *);
332 static void my_create_tip_window (struct frame *);
334 /* TODO: Native Input Method support; see x_create_im. */
335 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
336 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
337 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
338 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
339 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
340 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
341 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
342 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
343 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
344 void x_set_menu_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
345 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
346 void x_set_tool_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
347 void x_set_internal_border_width (struct frame *f, Lisp_Object, Lisp_Object);
350 /* Store the screen positions of frame F into XPTR and YPTR.
351 These are the positions of the containing window manager window,
352 not Emacs's own window. */
354 void
355 x_real_positions (struct frame *f, int *xptr, int *yptr)
357 POINT pt;
358 RECT rect;
360 /* Get the bounds of the WM window. */
361 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
363 pt.x = 0;
364 pt.y = 0;
366 /* Convert (0, 0) in the client area to screen co-ordinates. */
367 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
369 *xptr = rect.left;
370 *yptr = rect.top;
373 /* Returns the window rectangle appropriate for the given fullscreen mode.
374 The normal rect parameter was the window's rectangle prior to entering
375 fullscreen mode. If multiple monitor support is available, the nearest
376 monitor to the window is chosen. */
378 void
379 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
381 struct MONITOR_INFO mi = { sizeof(mi) };
382 if (monitor_from_window_fn && get_monitor_info_fn)
384 HMONITOR monitor =
385 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
386 get_monitor_info_fn (monitor, &mi);
388 else
390 mi.rcMonitor.left = 0;
391 mi.rcMonitor.top = 0;
392 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
393 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
394 mi.rcWork.left = 0;
395 mi.rcWork.top = 0;
396 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
397 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
400 switch (fsmode)
402 case FULLSCREEN_BOTH:
403 rect->left = mi.rcMonitor.left;
404 rect->top = mi.rcMonitor.top;
405 rect->right = mi.rcMonitor.right;
406 rect->bottom = mi.rcMonitor.bottom;
407 break;
408 case FULLSCREEN_WIDTH:
409 rect->left = mi.rcWork.left;
410 rect->top = normal.top;
411 rect->right = mi.rcWork.right;
412 rect->bottom = normal.bottom;
413 break;
414 case FULLSCREEN_HEIGHT:
415 rect->left = normal.left;
416 rect->top = mi.rcWork.top;
417 rect->right = normal.right;
418 rect->bottom = mi.rcWork.bottom;
419 break;
420 default:
421 *rect = normal;
422 break;
428 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
429 Sw32_define_rgb_color, 4, 4, 0,
430 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
431 This adds or updates a named color to `w32-color-map', making it
432 available for use. The original entry's RGB ref is returned, or nil
433 if the entry is new. */)
434 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
436 Lisp_Object rgb;
437 Lisp_Object oldrgb = Qnil;
438 Lisp_Object entry;
440 CHECK_NUMBER (red);
441 CHECK_NUMBER (green);
442 CHECK_NUMBER (blue);
443 CHECK_STRING (name);
445 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
447 block_input ();
449 /* replace existing entry in w32-color-map or add new entry. */
450 entry = Fassoc (name, Vw32_color_map);
451 if (NILP (entry))
453 entry = Fcons (name, rgb);
454 Vw32_color_map = Fcons (entry, Vw32_color_map);
456 else
458 oldrgb = Fcdr (entry);
459 Fsetcdr (entry, rgb);
462 unblock_input ();
464 return (oldrgb);
467 /* The default colors for the w32 color map */
468 typedef struct colormap_t
470 char *name;
471 COLORREF colorref;
472 } colormap_t;
474 colormap_t w32_color_map[] =
476 {"snow" , PALETTERGB (255,250,250)},
477 {"ghost white" , PALETTERGB (248,248,255)},
478 {"GhostWhite" , PALETTERGB (248,248,255)},
479 {"white smoke" , PALETTERGB (245,245,245)},
480 {"WhiteSmoke" , PALETTERGB (245,245,245)},
481 {"gainsboro" , PALETTERGB (220,220,220)},
482 {"floral white" , PALETTERGB (255,250,240)},
483 {"FloralWhite" , PALETTERGB (255,250,240)},
484 {"old lace" , PALETTERGB (253,245,230)},
485 {"OldLace" , PALETTERGB (253,245,230)},
486 {"linen" , PALETTERGB (250,240,230)},
487 {"antique white" , PALETTERGB (250,235,215)},
488 {"AntiqueWhite" , PALETTERGB (250,235,215)},
489 {"papaya whip" , PALETTERGB (255,239,213)},
490 {"PapayaWhip" , PALETTERGB (255,239,213)},
491 {"blanched almond" , PALETTERGB (255,235,205)},
492 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
493 {"bisque" , PALETTERGB (255,228,196)},
494 {"peach puff" , PALETTERGB (255,218,185)},
495 {"PeachPuff" , PALETTERGB (255,218,185)},
496 {"navajo white" , PALETTERGB (255,222,173)},
497 {"NavajoWhite" , PALETTERGB (255,222,173)},
498 {"moccasin" , PALETTERGB (255,228,181)},
499 {"cornsilk" , PALETTERGB (255,248,220)},
500 {"ivory" , PALETTERGB (255,255,240)},
501 {"lemon chiffon" , PALETTERGB (255,250,205)},
502 {"LemonChiffon" , PALETTERGB (255,250,205)},
503 {"seashell" , PALETTERGB (255,245,238)},
504 {"honeydew" , PALETTERGB (240,255,240)},
505 {"mint cream" , PALETTERGB (245,255,250)},
506 {"MintCream" , PALETTERGB (245,255,250)},
507 {"azure" , PALETTERGB (240,255,255)},
508 {"alice blue" , PALETTERGB (240,248,255)},
509 {"AliceBlue" , PALETTERGB (240,248,255)},
510 {"lavender" , PALETTERGB (230,230,250)},
511 {"lavender blush" , PALETTERGB (255,240,245)},
512 {"LavenderBlush" , PALETTERGB (255,240,245)},
513 {"misty rose" , PALETTERGB (255,228,225)},
514 {"MistyRose" , PALETTERGB (255,228,225)},
515 {"white" , PALETTERGB (255,255,255)},
516 {"black" , PALETTERGB ( 0, 0, 0)},
517 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
518 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
519 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
520 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
521 {"dim gray" , PALETTERGB (105,105,105)},
522 {"DimGray" , PALETTERGB (105,105,105)},
523 {"dim grey" , PALETTERGB (105,105,105)},
524 {"DimGrey" , PALETTERGB (105,105,105)},
525 {"slate gray" , PALETTERGB (112,128,144)},
526 {"SlateGray" , PALETTERGB (112,128,144)},
527 {"slate grey" , PALETTERGB (112,128,144)},
528 {"SlateGrey" , PALETTERGB (112,128,144)},
529 {"light slate gray" , PALETTERGB (119,136,153)},
530 {"LightSlateGray" , PALETTERGB (119,136,153)},
531 {"light slate grey" , PALETTERGB (119,136,153)},
532 {"LightSlateGrey" , PALETTERGB (119,136,153)},
533 {"gray" , PALETTERGB (190,190,190)},
534 {"grey" , PALETTERGB (190,190,190)},
535 {"light grey" , PALETTERGB (211,211,211)},
536 {"LightGrey" , PALETTERGB (211,211,211)},
537 {"light gray" , PALETTERGB (211,211,211)},
538 {"LightGray" , PALETTERGB (211,211,211)},
539 {"midnight blue" , PALETTERGB ( 25, 25,112)},
540 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
541 {"navy" , PALETTERGB ( 0, 0,128)},
542 {"navy blue" , PALETTERGB ( 0, 0,128)},
543 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
544 {"cornflower blue" , PALETTERGB (100,149,237)},
545 {"CornflowerBlue" , PALETTERGB (100,149,237)},
546 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
547 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
548 {"slate blue" , PALETTERGB (106, 90,205)},
549 {"SlateBlue" , PALETTERGB (106, 90,205)},
550 {"medium slate blue" , PALETTERGB (123,104,238)},
551 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
552 {"light slate blue" , PALETTERGB (132,112,255)},
553 {"LightSlateBlue" , PALETTERGB (132,112,255)},
554 {"medium blue" , PALETTERGB ( 0, 0,205)},
555 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
556 {"royal blue" , PALETTERGB ( 65,105,225)},
557 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
558 {"blue" , PALETTERGB ( 0, 0,255)},
559 {"dodger blue" , PALETTERGB ( 30,144,255)},
560 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
561 {"deep sky blue" , PALETTERGB ( 0,191,255)},
562 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
563 {"sky blue" , PALETTERGB (135,206,235)},
564 {"SkyBlue" , PALETTERGB (135,206,235)},
565 {"light sky blue" , PALETTERGB (135,206,250)},
566 {"LightSkyBlue" , PALETTERGB (135,206,250)},
567 {"steel blue" , PALETTERGB ( 70,130,180)},
568 {"SteelBlue" , PALETTERGB ( 70,130,180)},
569 {"light steel blue" , PALETTERGB (176,196,222)},
570 {"LightSteelBlue" , PALETTERGB (176,196,222)},
571 {"light blue" , PALETTERGB (173,216,230)},
572 {"LightBlue" , PALETTERGB (173,216,230)},
573 {"powder blue" , PALETTERGB (176,224,230)},
574 {"PowderBlue" , PALETTERGB (176,224,230)},
575 {"pale turquoise" , PALETTERGB (175,238,238)},
576 {"PaleTurquoise" , PALETTERGB (175,238,238)},
577 {"dark turquoise" , PALETTERGB ( 0,206,209)},
578 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
579 {"medium turquoise" , PALETTERGB ( 72,209,204)},
580 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
581 {"turquoise" , PALETTERGB ( 64,224,208)},
582 {"cyan" , PALETTERGB ( 0,255,255)},
583 {"light cyan" , PALETTERGB (224,255,255)},
584 {"LightCyan" , PALETTERGB (224,255,255)},
585 {"cadet blue" , PALETTERGB ( 95,158,160)},
586 {"CadetBlue" , PALETTERGB ( 95,158,160)},
587 {"medium aquamarine" , PALETTERGB (102,205,170)},
588 {"MediumAquamarine" , PALETTERGB (102,205,170)},
589 {"aquamarine" , PALETTERGB (127,255,212)},
590 {"dark green" , PALETTERGB ( 0,100, 0)},
591 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
592 {"dark olive green" , PALETTERGB ( 85,107, 47)},
593 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
594 {"dark sea green" , PALETTERGB (143,188,143)},
595 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
596 {"sea green" , PALETTERGB ( 46,139, 87)},
597 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
598 {"medium sea green" , PALETTERGB ( 60,179,113)},
599 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
600 {"light sea green" , PALETTERGB ( 32,178,170)},
601 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
602 {"pale green" , PALETTERGB (152,251,152)},
603 {"PaleGreen" , PALETTERGB (152,251,152)},
604 {"spring green" , PALETTERGB ( 0,255,127)},
605 {"SpringGreen" , PALETTERGB ( 0,255,127)},
606 {"lawn green" , PALETTERGB (124,252, 0)},
607 {"LawnGreen" , PALETTERGB (124,252, 0)},
608 {"green" , PALETTERGB ( 0,255, 0)},
609 {"chartreuse" , PALETTERGB (127,255, 0)},
610 {"medium spring green" , PALETTERGB ( 0,250,154)},
611 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
612 {"green yellow" , PALETTERGB (173,255, 47)},
613 {"GreenYellow" , PALETTERGB (173,255, 47)},
614 {"lime green" , PALETTERGB ( 50,205, 50)},
615 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
616 {"yellow green" , PALETTERGB (154,205, 50)},
617 {"YellowGreen" , PALETTERGB (154,205, 50)},
618 {"forest green" , PALETTERGB ( 34,139, 34)},
619 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
620 {"olive drab" , PALETTERGB (107,142, 35)},
621 {"OliveDrab" , PALETTERGB (107,142, 35)},
622 {"dark khaki" , PALETTERGB (189,183,107)},
623 {"DarkKhaki" , PALETTERGB (189,183,107)},
624 {"khaki" , PALETTERGB (240,230,140)},
625 {"pale goldenrod" , PALETTERGB (238,232,170)},
626 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
627 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
628 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
629 {"light yellow" , PALETTERGB (255,255,224)},
630 {"LightYellow" , PALETTERGB (255,255,224)},
631 {"yellow" , PALETTERGB (255,255, 0)},
632 {"gold" , PALETTERGB (255,215, 0)},
633 {"light goldenrod" , PALETTERGB (238,221,130)},
634 {"LightGoldenrod" , PALETTERGB (238,221,130)},
635 {"goldenrod" , PALETTERGB (218,165, 32)},
636 {"dark goldenrod" , PALETTERGB (184,134, 11)},
637 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
638 {"rosy brown" , PALETTERGB (188,143,143)},
639 {"RosyBrown" , PALETTERGB (188,143,143)},
640 {"indian red" , PALETTERGB (205, 92, 92)},
641 {"IndianRed" , PALETTERGB (205, 92, 92)},
642 {"saddle brown" , PALETTERGB (139, 69, 19)},
643 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
644 {"sienna" , PALETTERGB (160, 82, 45)},
645 {"peru" , PALETTERGB (205,133, 63)},
646 {"burlywood" , PALETTERGB (222,184,135)},
647 {"beige" , PALETTERGB (245,245,220)},
648 {"wheat" , PALETTERGB (245,222,179)},
649 {"sandy brown" , PALETTERGB (244,164, 96)},
650 {"SandyBrown" , PALETTERGB (244,164, 96)},
651 {"tan" , PALETTERGB (210,180,140)},
652 {"chocolate" , PALETTERGB (210,105, 30)},
653 {"firebrick" , PALETTERGB (178,34, 34)},
654 {"brown" , PALETTERGB (165,42, 42)},
655 {"dark salmon" , PALETTERGB (233,150,122)},
656 {"DarkSalmon" , PALETTERGB (233,150,122)},
657 {"salmon" , PALETTERGB (250,128,114)},
658 {"light salmon" , PALETTERGB (255,160,122)},
659 {"LightSalmon" , PALETTERGB (255,160,122)},
660 {"orange" , PALETTERGB (255,165, 0)},
661 {"dark orange" , PALETTERGB (255,140, 0)},
662 {"DarkOrange" , PALETTERGB (255,140, 0)},
663 {"coral" , PALETTERGB (255,127, 80)},
664 {"light coral" , PALETTERGB (240,128,128)},
665 {"LightCoral" , PALETTERGB (240,128,128)},
666 {"tomato" , PALETTERGB (255, 99, 71)},
667 {"orange red" , PALETTERGB (255, 69, 0)},
668 {"OrangeRed" , PALETTERGB (255, 69, 0)},
669 {"red" , PALETTERGB (255, 0, 0)},
670 {"hot pink" , PALETTERGB (255,105,180)},
671 {"HotPink" , PALETTERGB (255,105,180)},
672 {"deep pink" , PALETTERGB (255, 20,147)},
673 {"DeepPink" , PALETTERGB (255, 20,147)},
674 {"pink" , PALETTERGB (255,192,203)},
675 {"light pink" , PALETTERGB (255,182,193)},
676 {"LightPink" , PALETTERGB (255,182,193)},
677 {"pale violet red" , PALETTERGB (219,112,147)},
678 {"PaleVioletRed" , PALETTERGB (219,112,147)},
679 {"maroon" , PALETTERGB (176, 48, 96)},
680 {"medium violet red" , PALETTERGB (199, 21,133)},
681 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
682 {"violet red" , PALETTERGB (208, 32,144)},
683 {"VioletRed" , PALETTERGB (208, 32,144)},
684 {"magenta" , PALETTERGB (255, 0,255)},
685 {"violet" , PALETTERGB (238,130,238)},
686 {"plum" , PALETTERGB (221,160,221)},
687 {"orchid" , PALETTERGB (218,112,214)},
688 {"medium orchid" , PALETTERGB (186, 85,211)},
689 {"MediumOrchid" , PALETTERGB (186, 85,211)},
690 {"dark orchid" , PALETTERGB (153, 50,204)},
691 {"DarkOrchid" , PALETTERGB (153, 50,204)},
692 {"dark violet" , PALETTERGB (148, 0,211)},
693 {"DarkViolet" , PALETTERGB (148, 0,211)},
694 {"blue violet" , PALETTERGB (138, 43,226)},
695 {"BlueViolet" , PALETTERGB (138, 43,226)},
696 {"purple" , PALETTERGB (160, 32,240)},
697 {"medium purple" , PALETTERGB (147,112,219)},
698 {"MediumPurple" , PALETTERGB (147,112,219)},
699 {"thistle" , PALETTERGB (216,191,216)},
700 {"gray0" , PALETTERGB ( 0, 0, 0)},
701 {"grey0" , PALETTERGB ( 0, 0, 0)},
702 {"dark grey" , PALETTERGB (169,169,169)},
703 {"DarkGrey" , PALETTERGB (169,169,169)},
704 {"dark gray" , PALETTERGB (169,169,169)},
705 {"DarkGray" , PALETTERGB (169,169,169)},
706 {"dark blue" , PALETTERGB ( 0, 0,139)},
707 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
708 {"dark cyan" , PALETTERGB ( 0,139,139)},
709 {"DarkCyan" , PALETTERGB ( 0,139,139)},
710 {"dark magenta" , PALETTERGB (139, 0,139)},
711 {"DarkMagenta" , PALETTERGB (139, 0,139)},
712 {"dark red" , PALETTERGB (139, 0, 0)},
713 {"DarkRed" , PALETTERGB (139, 0, 0)},
714 {"light green" , PALETTERGB (144,238,144)},
715 {"LightGreen" , PALETTERGB (144,238,144)},
718 static Lisp_Object
719 w32_default_color_map (void)
721 int i;
722 colormap_t *pc = w32_color_map;
723 Lisp_Object cmap;
725 block_input ();
727 cmap = Qnil;
729 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
730 cmap = Fcons (Fcons (build_string (pc->name),
731 make_number (pc->colorref)),
732 cmap);
734 unblock_input ();
736 return (cmap);
739 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
740 0, 0, 0, doc: /* Return the default color map. */)
741 (void)
743 return w32_default_color_map ();
746 static Lisp_Object
747 w32_color_map_lookup (const char *colorname)
749 Lisp_Object tail, ret = Qnil;
751 block_input ();
753 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
755 register Lisp_Object elt, tem;
757 elt = XCAR (tail);
758 if (!CONSP (elt)) continue;
760 tem = XCAR (elt);
762 if (lstrcmpi (SDATA (tem), colorname) == 0)
764 ret = Fcdr (elt);
765 break;
768 QUIT;
771 unblock_input ();
773 return ret;
777 static void
778 add_system_logical_colors_to_map (Lisp_Object *system_colors)
780 HKEY colors_key;
782 /* Other registry operations are done with input blocked. */
783 block_input ();
785 /* Look for "Control Panel/Colors" under User and Machine registry
786 settings. */
787 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
788 KEY_READ, &colors_key) == ERROR_SUCCESS
789 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
790 KEY_READ, &colors_key) == ERROR_SUCCESS)
792 /* List all keys. */
793 char color_buffer[64];
794 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
795 int index = 0;
796 DWORD name_size, color_size;
797 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
799 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
800 color_size = sizeof (color_buffer);
802 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
804 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
805 NULL, NULL, color_buffer, &color_size)
806 == ERROR_SUCCESS)
808 int r, g, b;
809 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
810 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
811 make_number (RGB (r, g, b))),
812 *system_colors);
814 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
815 color_size = sizeof (color_buffer);
816 index++;
818 RegCloseKey (colors_key);
821 unblock_input ();
825 static Lisp_Object
826 x_to_w32_color (const char * colorname)
828 register Lisp_Object ret = Qnil;
830 block_input ();
832 if (colorname[0] == '#')
834 /* Could be an old-style RGB Device specification. */
835 int size = strlen (colorname + 1);
836 char *color = alloca (size + 1);
838 strcpy (color, colorname + 1);
839 if (size == 3 || size == 6 || size == 9 || size == 12)
841 UINT colorval;
842 int i, pos;
843 pos = 0;
844 size /= 3;
845 colorval = 0;
847 for (i = 0; i < 3; i++)
849 char *end;
850 char t;
851 unsigned long value;
853 /* The check for 'x' in the following conditional takes into
854 account the fact that strtol allows a "0x" in front of
855 our numbers, and we don't. */
856 if (!isxdigit (color[0]) || color[1] == 'x')
857 break;
858 t = color[size];
859 color[size] = '\0';
860 value = strtoul (color, &end, 16);
861 color[size] = t;
862 if (errno == ERANGE || end - color != size)
863 break;
864 switch (size)
866 case 1:
867 value = value * 0x10;
868 break;
869 case 2:
870 break;
871 case 3:
872 value /= 0x10;
873 break;
874 case 4:
875 value /= 0x100;
876 break;
878 colorval |= (value << pos);
879 pos += 0x8;
880 if (i == 2)
882 unblock_input ();
883 XSETINT (ret, colorval);
884 return ret;
886 color = end;
890 else if (strnicmp (colorname, "rgb:", 4) == 0)
892 const char *color;
893 UINT colorval;
894 int i, pos;
895 pos = 0;
897 colorval = 0;
898 color = colorname + 4;
899 for (i = 0; i < 3; i++)
901 char *end;
902 unsigned long value;
904 /* The check for 'x' in the following conditional takes into
905 account the fact that strtol allows a "0x" in front of
906 our numbers, and we don't. */
907 if (!isxdigit (color[0]) || color[1] == 'x')
908 break;
909 value = strtoul (color, &end, 16);
910 if (errno == ERANGE)
911 break;
912 switch (end - color)
914 case 1:
915 value = value * 0x10 + value;
916 break;
917 case 2:
918 break;
919 case 3:
920 value /= 0x10;
921 break;
922 case 4:
923 value /= 0x100;
924 break;
925 default:
926 value = ULONG_MAX;
928 if (value == ULONG_MAX)
929 break;
930 colorval |= (value << pos);
931 pos += 0x8;
932 if (i == 2)
934 if (*end != '\0')
935 break;
936 unblock_input ();
937 XSETINT (ret, colorval);
938 return ret;
940 if (*end != '/')
941 break;
942 color = end + 1;
945 else if (strnicmp (colorname, "rgbi:", 5) == 0)
947 /* This is an RGB Intensity specification. */
948 const char *color;
949 UINT colorval;
950 int i, pos;
951 pos = 0;
953 colorval = 0;
954 color = colorname + 5;
955 for (i = 0; i < 3; i++)
957 char *end;
958 double value;
959 UINT val;
961 value = strtod (color, &end);
962 if (errno == ERANGE)
963 break;
964 if (value < 0.0 || value > 1.0)
965 break;
966 val = (UINT)(0x100 * value);
967 /* We used 0x100 instead of 0xFF to give a continuous
968 range between 0.0 and 1.0 inclusive. The next statement
969 fixes the 1.0 case. */
970 if (val == 0x100)
971 val = 0xFF;
972 colorval |= (val << pos);
973 pos += 0x8;
974 if (i == 2)
976 if (*end != '\0')
977 break;
978 unblock_input ();
979 XSETINT (ret, colorval);
980 return ret;
982 if (*end != '/')
983 break;
984 color = end + 1;
987 /* I am not going to attempt to handle any of the CIE color schemes
988 or TekHVC, since I don't know the algorithms for conversion to
989 RGB. */
991 /* If we fail to lookup the color name in w32_color_map, then check the
992 colorname to see if it can be crudely approximated: If the X color
993 ends in a number (e.g., "darkseagreen2"), strip the number and
994 return the result of looking up the base color name. */
995 ret = w32_color_map_lookup (colorname);
996 if (NILP (ret))
998 int len = strlen (colorname);
1000 if (isdigit (colorname[len - 1]))
1002 char *ptr, *approx = alloca (len + 1);
1004 strcpy (approx, colorname);
1005 ptr = &approx[len - 1];
1006 while (ptr > approx && isdigit (*ptr))
1007 *ptr-- = '\0';
1009 ret = w32_color_map_lookup (approx);
1013 unblock_input ();
1014 return ret;
1017 void
1018 w32_regenerate_palette (struct frame *f)
1020 struct w32_palette_entry * list;
1021 LOGPALETTE * log_palette;
1022 HPALETTE new_palette;
1023 int i;
1025 /* don't bother trying to create palette if not supported */
1026 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1027 return;
1029 log_palette = (LOGPALETTE *)
1030 alloca (sizeof (LOGPALETTE) +
1031 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1032 log_palette->palVersion = 0x300;
1033 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1035 list = FRAME_DISPLAY_INFO (f)->color_list;
1036 for (i = 0;
1037 i < FRAME_DISPLAY_INFO (f)->num_colors;
1038 i++, list = list->next)
1039 log_palette->palPalEntry[i] = list->entry;
1041 new_palette = CreatePalette (log_palette);
1043 enter_crit ();
1045 if (FRAME_DISPLAY_INFO (f)->palette)
1046 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1047 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1049 /* Realize display palette and garbage all frames. */
1050 release_frame_dc (f, get_frame_dc (f));
1052 leave_crit ();
1055 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1056 #define SET_W32_COLOR(pe, color) \
1057 do \
1059 pe.peRed = GetRValue (color); \
1060 pe.peGreen = GetGValue (color); \
1061 pe.peBlue = GetBValue (color); \
1062 pe.peFlags = 0; \
1063 } while (0)
1065 #if 0
1066 /* Keep these around in case we ever want to track color usage. */
1067 void
1068 w32_map_color (struct frame *f, COLORREF color)
1070 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1072 if (NILP (Vw32_enable_palette))
1073 return;
1075 /* check if color is already mapped */
1076 while (list)
1078 if (W32_COLOR (list->entry) == color)
1080 ++list->refcount;
1081 return;
1083 list = list->next;
1086 /* not already mapped, so add to list and recreate Windows palette */
1087 list = xmalloc (sizeof (struct w32_palette_entry));
1088 SET_W32_COLOR (list->entry, color);
1089 list->refcount = 1;
1090 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1091 FRAME_DISPLAY_INFO (f)->color_list = list;
1092 FRAME_DISPLAY_INFO (f)->num_colors++;
1094 /* set flag that palette must be regenerated */
1095 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1098 void
1099 w32_unmap_color (struct frame *f, COLORREF color)
1101 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1102 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1104 if (NILP (Vw32_enable_palette))
1105 return;
1107 /* check if color is already mapped */
1108 while (list)
1110 if (W32_COLOR (list->entry) == color)
1112 if (--list->refcount == 0)
1114 *prev = list->next;
1115 xfree (list);
1116 FRAME_DISPLAY_INFO (f)->num_colors--;
1117 break;
1119 else
1120 return;
1122 prev = &list->next;
1123 list = list->next;
1126 /* set flag that palette must be regenerated */
1127 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1129 #endif
1132 /* Gamma-correct COLOR on frame F. */
1134 void
1135 gamma_correct (struct frame *f, COLORREF *color)
1137 if (f->gamma)
1139 *color = PALETTERGB (
1140 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1141 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1142 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1147 /* Decide if color named COLOR is valid for the display associated with
1148 the selected frame; if so, return the rgb values in COLOR_DEF.
1149 If ALLOC is nonzero, allocate a new colormap cell. */
1152 w32_defined_color (struct frame *f, const char *color, XColor *color_def,
1153 bool alloc_p)
1155 register Lisp_Object tem;
1156 COLORREF w32_color_ref;
1158 tem = x_to_w32_color (color);
1160 if (!NILP (tem))
1162 if (f)
1164 /* Apply gamma correction. */
1165 w32_color_ref = XUINT (tem);
1166 gamma_correct (f, &w32_color_ref);
1167 XSETINT (tem, w32_color_ref);
1170 /* Map this color to the palette if it is enabled. */
1171 if (!NILP (Vw32_enable_palette))
1173 struct w32_palette_entry * entry =
1174 one_w32_display_info.color_list;
1175 struct w32_palette_entry ** prev =
1176 &one_w32_display_info.color_list;
1178 /* check if color is already mapped */
1179 while (entry)
1181 if (W32_COLOR (entry->entry) == XUINT (tem))
1182 break;
1183 prev = &entry->next;
1184 entry = entry->next;
1187 if (entry == NULL && alloc_p)
1189 /* not already mapped, so add to list */
1190 entry = xmalloc (sizeof (struct w32_palette_entry));
1191 SET_W32_COLOR (entry->entry, XUINT (tem));
1192 entry->next = NULL;
1193 *prev = entry;
1194 one_w32_display_info.num_colors++;
1196 /* set flag that palette must be regenerated */
1197 one_w32_display_info.regen_palette = TRUE;
1200 /* Ensure COLORREF value is snapped to nearest color in (default)
1201 palette by simulating the PALETTERGB macro. This works whether
1202 or not the display device has a palette. */
1203 w32_color_ref = XUINT (tem) | 0x2000000;
1205 color_def->pixel = w32_color_ref;
1206 color_def->red = GetRValue (w32_color_ref) * 256;
1207 color_def->green = GetGValue (w32_color_ref) * 256;
1208 color_def->blue = GetBValue (w32_color_ref) * 256;
1210 return 1;
1212 else
1214 return 0;
1218 /* Given a string ARG naming a color, compute a pixel value from it
1219 suitable for screen F.
1220 If F is not a color screen, return DEF (default) regardless of what
1221 ARG says. */
1224 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1226 XColor cdef;
1228 CHECK_STRING (arg);
1230 if (strcmp (SDATA (arg), "black") == 0)
1231 return BLACK_PIX_DEFAULT (f);
1232 else if (strcmp (SDATA (arg), "white") == 0)
1233 return WHITE_PIX_DEFAULT (f);
1235 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1236 return def;
1238 /* w32_defined_color is responsible for coping with failures
1239 by looking for a near-miss. */
1240 if (w32_defined_color (f, SDATA (arg), &cdef, true))
1241 return cdef.pixel;
1243 /* defined_color failed; return an ultimate default. */
1244 return def;
1249 /* Functions called only from `x_set_frame_param'
1250 to set individual parameters.
1252 If FRAME_W32_WINDOW (f) is 0,
1253 the frame is being created and its window does not exist yet.
1254 In that case, just record the parameter's new value
1255 in the standard place; do not attempt to change the window. */
1257 void
1258 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1260 struct w32_output *x = f->output_data.w32;
1261 PIX_TYPE fg, old_fg;
1263 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1264 old_fg = FRAME_FOREGROUND_PIXEL (f);
1265 FRAME_FOREGROUND_PIXEL (f) = fg;
1267 if (FRAME_W32_WINDOW (f) != 0)
1269 if (x->cursor_pixel == old_fg)
1271 x->cursor_pixel = fg;
1272 x->cursor_gc->background = fg;
1275 update_face_from_frame_parameter (f, Qforeground_color, arg);
1276 if (FRAME_VISIBLE_P (f))
1277 redraw_frame (f);
1281 void
1282 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1284 FRAME_BACKGROUND_PIXEL (f)
1285 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1287 if (FRAME_W32_WINDOW (f) != 0)
1289 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1290 FRAME_BACKGROUND_PIXEL (f));
1292 update_face_from_frame_parameter (f, Qbackground_color, arg);
1294 if (FRAME_VISIBLE_P (f))
1295 redraw_frame (f);
1299 void
1300 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1302 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1303 int count;
1304 int mask_color;
1306 if (!EQ (Qnil, arg))
1307 f->output_data.w32->mouse_pixel
1308 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1309 mask_color = FRAME_BACKGROUND_PIXEL (f);
1311 /* Don't let pointers be invisible. */
1312 if (mask_color == f->output_data.w32->mouse_pixel
1313 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1314 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1316 #if 0 /* TODO : Mouse cursor customization. */
1317 block_input ();
1319 /* It's not okay to crash if the user selects a screwy cursor. */
1320 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1322 if (!EQ (Qnil, Vx_pointer_shape))
1324 CHECK_NUMBER (Vx_pointer_shape);
1325 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1327 else
1328 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1329 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1331 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1333 CHECK_NUMBER (Vx_nontext_pointer_shape);
1334 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1335 XINT (Vx_nontext_pointer_shape));
1337 else
1338 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1339 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1341 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1343 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1344 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1345 XINT (Vx_hourglass_pointer_shape));
1347 else
1348 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1349 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1351 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1352 if (!EQ (Qnil, Vx_mode_pointer_shape))
1354 CHECK_NUMBER (Vx_mode_pointer_shape);
1355 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1356 XINT (Vx_mode_pointer_shape));
1358 else
1359 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1360 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1362 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1364 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1365 hand_cursor
1366 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1367 XINT (Vx_sensitive_text_pointer_shape));
1369 else
1370 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1372 if (!NILP (Vx_window_horizontal_drag_shape))
1374 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1375 horizontal_drag_cursor
1376 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1377 XINT (Vx_window_horizontal_drag_shape));
1379 else
1380 horizontal_drag_cursor
1381 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1383 if (!NILP (Vx_window_vertical_drag_shape))
1385 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1386 vertical_drag_cursor
1387 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1388 XINT (Vx_window_vertical_drag_shape));
1390 else
1391 vertical_drag_cursor
1392 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1394 /* Check and report errors with the above calls. */
1395 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1396 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1399 XColor fore_color, back_color;
1401 fore_color.pixel = f->output_data.w32->mouse_pixel;
1402 back_color.pixel = mask_color;
1403 XQueryColor (FRAME_W32_DISPLAY (f),
1404 DefaultColormap (FRAME_W32_DISPLAY (f),
1405 DefaultScreen (FRAME_W32_DISPLAY (f))),
1406 &fore_color);
1407 XQueryColor (FRAME_W32_DISPLAY (f),
1408 DefaultColormap (FRAME_W32_DISPLAY (f),
1409 DefaultScreen (FRAME_W32_DISPLAY (f))),
1410 &back_color);
1411 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1412 &fore_color, &back_color);
1413 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1414 &fore_color, &back_color);
1415 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1416 &fore_color, &back_color);
1417 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1418 &fore_color, &back_color);
1419 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1420 &fore_color, &back_color);
1423 if (FRAME_W32_WINDOW (f) != 0)
1424 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1426 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1427 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1428 f->output_data.w32->text_cursor = cursor;
1430 if (nontext_cursor != f->output_data.w32->nontext_cursor
1431 && f->output_data.w32->nontext_cursor != 0)
1432 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1433 f->output_data.w32->nontext_cursor = nontext_cursor;
1435 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1436 && f->output_data.w32->hourglass_cursor != 0)
1437 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1438 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1440 if (mode_cursor != f->output_data.w32->modeline_cursor
1441 && f->output_data.w32->modeline_cursor != 0)
1442 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1443 f->output_data.w32->modeline_cursor = mode_cursor;
1445 if (hand_cursor != f->output_data.w32->hand_cursor
1446 && f->output_data.w32->hand_cursor != 0)
1447 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1448 f->output_data.w32->hand_cursor = hand_cursor;
1450 XFlush (FRAME_W32_DISPLAY (f));
1451 unblock_input ();
1453 update_face_from_frame_parameter (f, Qmouse_color, arg);
1454 #endif /* TODO */
1457 void
1458 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1460 unsigned long fore_pixel, pixel;
1462 if (!NILP (Vx_cursor_fore_pixel))
1463 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1464 WHITE_PIX_DEFAULT (f));
1465 else
1466 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1468 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1470 /* Make sure that the cursor color differs from the background color. */
1471 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1473 pixel = f->output_data.w32->mouse_pixel;
1474 if (pixel == fore_pixel)
1475 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1478 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1479 f->output_data.w32->cursor_pixel = pixel;
1481 if (FRAME_W32_WINDOW (f) != 0)
1483 block_input ();
1484 /* Update frame's cursor_gc. */
1485 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1486 f->output_data.w32->cursor_gc->background = pixel;
1488 unblock_input ();
1490 if (FRAME_VISIBLE_P (f))
1492 x_update_cursor (f, 0);
1493 x_update_cursor (f, 1);
1497 update_face_from_frame_parameter (f, Qcursor_color, arg);
1500 /* Set the border-color of frame F to pixel value PIX.
1501 Note that this does not fully take effect if done before
1502 F has a window. */
1504 void
1505 x_set_border_pixel (struct frame *f, int pix)
1508 f->output_data.w32->border_pixel = pix;
1510 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1512 if (FRAME_VISIBLE_P (f))
1513 redraw_frame (f);
1517 /* Set the border-color of frame F to value described by ARG.
1518 ARG can be a string naming a color.
1519 The border-color is used for the border that is drawn by the server.
1520 Note that this does not fully take effect if done before
1521 F has a window; it must be redone when the window is created. */
1523 void
1524 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1526 int pix;
1528 CHECK_STRING (arg);
1529 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1530 x_set_border_pixel (f, pix);
1531 update_face_from_frame_parameter (f, Qborder_color, arg);
1535 void
1536 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1538 set_frame_cursor_types (f, arg);
1541 void
1542 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1544 bool result;
1546 if (NILP (arg) && NILP (oldval))
1547 return;
1549 if (STRINGP (arg) && STRINGP (oldval)
1550 && EQ (Fstring_equal (oldval, arg), Qt))
1551 return;
1553 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1554 return;
1556 block_input ();
1558 result = x_bitmap_icon (f, arg);
1559 if (result)
1561 unblock_input ();
1562 error ("No icon window available");
1565 unblock_input ();
1568 void
1569 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1571 if (STRINGP (arg))
1573 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1574 return;
1576 else if (!NILP (arg) || NILP (oldval))
1577 return;
1579 fset_icon_name (f, arg);
1581 #if 0
1582 if (f->output_data.w32->icon_bitmap != 0)
1583 return;
1585 block_input ();
1587 result = x_text_icon (f,
1588 SSDATA ((!NILP (f->icon_name)
1589 ? f->icon_name
1590 : !NILP (f->title)
1591 ? f->title
1592 : f->name)));
1594 if (result)
1596 unblock_input ();
1597 error ("No icon window available");
1600 /* If the window was unmapped (and its icon was mapped),
1601 the new icon is not mapped, so map the window in its stead. */
1602 if (FRAME_VISIBLE_P (f))
1604 #ifdef USE_X_TOOLKIT
1605 XtPopup (f->output_data.w32->widget, XtGrabNone);
1606 #endif
1607 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1610 XFlush (FRAME_W32_DISPLAY (f));
1611 unblock_input ();
1612 #endif
1615 void
1616 x_clear_under_internal_border (struct frame *f)
1618 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1620 /* Clear border if it's larger than before. */
1621 if (border != 0)
1623 HDC hdc = get_frame_dc (f);
1624 int width = FRAME_PIXEL_WIDTH (f);
1625 int height = FRAME_PIXEL_HEIGHT (f);
1627 block_input ();
1628 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1629 w32_clear_area (f, hdc, 0, 0, border, height);
1630 w32_clear_area (f, hdc, width - border, 0, border, height);
1631 w32_clear_area (f, hdc, 0, height - border, width, border);
1632 release_frame_dc (f, hdc);
1633 unblock_input ();
1638 void
1639 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1641 int border;
1643 CHECK_TYPE_RANGED_INTEGER (int, arg);
1644 border = max (XINT (arg), 0);
1646 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1648 FRAME_INTERNAL_BORDER_WIDTH (f) = border;
1650 if (FRAME_X_WINDOW (f) != 0)
1652 adjust_frame_size (f, -1, -1, 3, false, Qinternal_border_width);
1654 if (FRAME_VISIBLE_P (f))
1655 x_clear_under_internal_border (f);
1661 void
1662 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1664 int nlines;
1666 /* Right now, menu bars don't work properly in minibuf-only frames;
1667 most of the commands try to apply themselves to the minibuffer
1668 frame itself, and get an error because you can't switch buffers
1669 in or split the minibuffer window. */
1670 if (FRAME_MINIBUF_ONLY_P (f))
1671 return;
1673 if (INTEGERP (value))
1674 nlines = XINT (value);
1675 else
1676 nlines = 0;
1678 FRAME_MENU_BAR_LINES (f) = 0;
1679 FRAME_MENU_BAR_HEIGHT (f) = 0;
1680 if (nlines)
1682 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1683 windows_or_buffers_changed = 23;
1685 else
1687 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1688 free_frame_menubar (f);
1689 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1691 /* Adjust the frame size so that the client (text) dimensions
1692 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1693 set correctly. Note that we resize twice: The first time upon
1694 a request from the window manager who wants to keep the height
1695 of the outer rectangle (including decorations) unchanged, and a
1696 second time because we want to keep the height of the inner
1697 rectangle (without the decorations unchanged). */
1698 adjust_frame_size (f, -1, -1, 2, true, Qmenu_bar_lines);
1700 /* Not sure whether this is needed. */
1701 x_clear_under_internal_border (f);
1706 /* Set the number of lines used for the tool bar of frame F to VALUE.
1707 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1708 the old number of tool bar lines (and is unused). This function may
1709 change the height of all windows on frame F to match the new tool bar
1710 height. By design, the frame's height doesn't change (but maybe it
1711 should if we don't get enough space otherwise). */
1713 void
1714 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1716 int nlines;
1718 /* Treat tool bars like menu bars. */
1719 if (FRAME_MINIBUF_ONLY_P (f))
1720 return;
1722 /* Use VALUE only if an integer >= 0. */
1723 if (INTEGERP (value) && XINT (value) >= 0)
1724 nlines = XFASTINT (value);
1725 else
1726 nlines = 0;
1728 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1732 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1733 void
1734 x_change_tool_bar_height (struct frame *f, int height)
1736 Lisp_Object frame;
1737 int unit = FRAME_LINE_HEIGHT (f);
1738 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1739 int lines = (height + unit - 1) / unit;
1740 int old_text_height = FRAME_TEXT_HEIGHT (f);
1741 Lisp_Object fullscreen;
1743 /* Make sure we redisplay all windows in this frame. */
1744 windows_or_buffers_changed = 23;
1746 /* Recalculate tool bar and frame text sizes. */
1747 FRAME_TOOL_BAR_HEIGHT (f) = height;
1748 FRAME_TOOL_BAR_LINES (f) = lines;
1749 /* Store `tool-bar-lines' and `height' frame parameters. */
1750 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1751 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1753 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1755 clear_frame (f);
1756 clear_current_matrices (f);
1759 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1760 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1762 /* Recalculate toolbar height. */
1763 f->n_tool_bar_rows = 0;
1765 adjust_frame_size (f, -1, -1,
1766 ((!f->tool_bar_redisplayed_once
1767 && (NILP (fullscreen =
1768 get_frame_param (f, Qfullscreen))
1769 || EQ (fullscreen, Qfullwidth))) ? 1
1770 : (old_height == 0 || height == 0) ? 2
1771 : 4),
1772 false, Qtool_bar_lines);
1774 /* adjust_frame_size might not have done anything, garbage frame
1775 here. */
1776 adjust_frame_glyphs (f);
1777 SET_FRAME_GARBAGED (f);
1778 if (FRAME_X_WINDOW (f))
1779 x_clear_under_internal_border (f);
1782 static void
1783 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1785 if (FRAME_W32_WINDOW (f))
1787 block_input ();
1788 #ifdef __CYGWIN__
1789 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1790 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1791 #else
1792 /* The frame's title many times shows the name of the file
1793 visited in the selected window's buffer, so it makes sense to
1794 support non-ASCII characters outside of the current system
1795 codepage in the title. */
1796 if (w32_unicode_filenames)
1798 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1799 wchar_t *title_w;
1800 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1801 -1, NULL, 0);
1803 if (tlen > 0)
1805 /* Windows truncates the title text beyond what fits on
1806 a single line, so we can limit the length to some
1807 reasonably large value, and use alloca. */
1808 if (tlen > 10000)
1809 tlen = 10000;
1810 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1811 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1812 title_w, tlen);
1813 title_w[tlen] = L'\0';
1814 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1816 else /* Conversion to UTF-16 failed, so we punt. */
1817 SetWindowTextA (FRAME_W32_WINDOW (f),
1818 SSDATA (ENCODE_SYSTEM (name)));
1820 else
1821 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1822 #endif
1823 unblock_input ();
1827 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1828 w32_id_name.
1830 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1831 name; if NAME is a string, set F's name to NAME and set
1832 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1834 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1835 suggesting a new name, which lisp code should override; if
1836 F->explicit_name is set, ignore the new name; otherwise, set it. */
1838 void
1839 x_set_name (struct frame *f, Lisp_Object name, bool explicit)
1841 /* Make sure that requests from lisp code override requests from
1842 Emacs redisplay code. */
1843 if (explicit)
1845 /* If we're switching from explicit to implicit, we had better
1846 update the mode lines and thereby update the title. */
1847 if (f->explicit_name && NILP (name))
1848 update_mode_lines = 25;
1850 f->explicit_name = ! NILP (name);
1852 else if (f->explicit_name)
1853 return;
1855 /* If NAME is nil, set the name to the w32_id_name. */
1856 if (NILP (name))
1858 /* Check for no change needed in this very common case
1859 before we do any consing. */
1860 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1861 SDATA (f->name)))
1862 return;
1863 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1865 else
1866 CHECK_STRING (name);
1868 /* Don't change the name if it's already NAME. */
1869 if (! NILP (Fstring_equal (name, f->name)))
1870 return;
1872 fset_name (f, name);
1874 /* For setting the frame title, the title parameter should override
1875 the name parameter. */
1876 if (! NILP (f->title))
1877 name = f->title;
1879 w32_set_title_bar_text (f, name);
1882 /* This function should be called when the user's lisp code has
1883 specified a name for the frame; the name will override any set by the
1884 redisplay code. */
1885 void
1886 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1888 x_set_name (f, arg, true);
1891 /* This function should be called by Emacs redisplay code to set the
1892 name; names set this way will never override names set by the user's
1893 lisp code. */
1894 void
1895 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1897 x_set_name (f, arg, false);
1900 /* Change the title of frame F to NAME.
1901 If NAME is nil, use the frame name as the title. */
1903 void
1904 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1906 /* Don't change the title if it's already NAME. */
1907 if (EQ (name, f->title))
1908 return;
1910 update_mode_lines = 26;
1912 fset_title (f, name);
1914 if (NILP (name))
1915 name = f->name;
1917 w32_set_title_bar_text (f, name);
1920 void
1921 x_set_scroll_bar_default_width (struct frame *f)
1923 int unit = FRAME_COLUMN_WIDTH (f);
1925 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1926 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1927 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1931 void
1932 x_set_scroll_bar_default_height (struct frame *f)
1934 int unit = FRAME_LINE_HEIGHT (f);
1936 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
1937 FRAME_CONFIG_SCROLL_BAR_LINES (f)
1938 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
1941 /* Subroutines for creating a frame. */
1943 Cursor
1944 w32_load_cursor (LPCTSTR name)
1946 /* Try first to load cursor from application resource. */
1947 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1948 name, IMAGE_CURSOR, 0, 0,
1949 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1950 if (!cursor)
1952 /* Then try to load a shared predefined cursor. */
1953 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1954 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1956 return cursor;
1959 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1961 #define INIT_WINDOW_CLASS(WC) \
1962 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1963 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1964 (WC).cbClsExtra = 0; \
1965 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1966 (WC).hInstance = hinst; \
1967 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1968 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1969 (WC).hbrBackground = NULL; \
1970 (WC).lpszMenuName = NULL; \
1972 static BOOL
1973 w32_init_class (HINSTANCE hinst)
1975 if (w32_unicode_gui)
1977 WNDCLASSW uwc;
1978 INIT_WINDOW_CLASS(uwc);
1979 uwc.lpszClassName = L"Emacs";
1981 return RegisterClassW (&uwc);
1983 else
1985 WNDCLASS wc;
1986 INIT_WINDOW_CLASS(wc);
1987 wc.lpszClassName = EMACS_CLASS;
1989 return RegisterClassA (&wc);
1993 static HWND
1994 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
1996 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1997 /* Position and size of scroll bar. */
1998 bar->left, bar->top, bar->width, bar->height,
1999 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2002 static HWND
2003 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
2005 return CreateWindow ("SCROLLBAR", "", SBS_HORZ | WS_CHILD | WS_VISIBLE,
2006 /* Position and size of scroll bar. */
2007 bar->left, bar->top, bar->width, bar->height,
2008 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2011 static void
2012 w32_createwindow (struct frame *f, int *coords)
2014 HWND hwnd;
2015 RECT rect;
2016 int top;
2017 int left;
2019 rect.left = rect.top = 0;
2020 rect.right = FRAME_PIXEL_WIDTH (f);
2021 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2023 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2024 FRAME_EXTERNAL_MENU_BAR (f));
2026 /* Do first time app init */
2028 w32_init_class (hinst);
2030 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2032 left = f->left_pos;
2033 top = f->top_pos;
2035 else
2037 left = coords[0];
2038 top = coords[1];
2041 FRAME_W32_WINDOW (f) = hwnd
2042 = CreateWindow (EMACS_CLASS,
2043 f->namebuf,
2044 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2045 left, top,
2046 rect.right - rect.left, rect.bottom - rect.top,
2047 NULL,
2048 NULL,
2049 hinst,
2050 NULL);
2052 if (hwnd)
2054 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2055 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2056 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2057 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2058 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2059 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2061 /* Enable drag-n-drop. */
2062 DragAcceptFiles (hwnd, TRUE);
2064 /* Do this to discard the default setting specified by our parent. */
2065 ShowWindow (hwnd, SW_HIDE);
2067 /* Update frame positions. */
2068 GetWindowRect (hwnd, &rect);
2069 f->left_pos = rect.left;
2070 f->top_pos = rect.top;
2074 static void
2075 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2077 wmsg->msg.hwnd = hwnd;
2078 wmsg->msg.message = msg;
2079 wmsg->msg.wParam = wParam;
2080 wmsg->msg.lParam = lParam;
2081 wmsg->msg.time = GetMessageTime ();
2083 post_msg (wmsg);
2086 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2087 between left and right keys as advertised. We test for this
2088 support dynamically, and set a flag when the support is absent. If
2089 absent, we keep track of the left and right control and alt keys
2090 ourselves. This is particularly necessary on keyboards that rely
2091 upon the AltGr key, which is represented as having the left control
2092 and right alt keys pressed. For these keyboards, we need to know
2093 when the left alt key has been pressed in addition to the AltGr key
2094 so that we can properly support M-AltGr-key sequences (such as M-@
2095 on Swedish keyboards). */
2097 #define EMACS_LCONTROL 0
2098 #define EMACS_RCONTROL 1
2099 #define EMACS_LMENU 2
2100 #define EMACS_RMENU 3
2102 static int modifiers[4];
2103 static int modifiers_recorded;
2104 static int modifier_key_support_tested;
2106 static void
2107 test_modifier_support (unsigned int wparam)
2109 unsigned int l, r;
2111 if (wparam != VK_CONTROL && wparam != VK_MENU)
2112 return;
2113 if (wparam == VK_CONTROL)
2115 l = VK_LCONTROL;
2116 r = VK_RCONTROL;
2118 else
2120 l = VK_LMENU;
2121 r = VK_RMENU;
2123 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2124 modifiers_recorded = 1;
2125 else
2126 modifiers_recorded = 0;
2127 modifier_key_support_tested = 1;
2130 static void
2131 record_keydown (unsigned int wparam, unsigned int lparam)
2133 int i;
2135 if (!modifier_key_support_tested)
2136 test_modifier_support (wparam);
2138 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2139 return;
2141 if (wparam == VK_CONTROL)
2142 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2143 else
2144 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2146 modifiers[i] = 1;
2149 static void
2150 record_keyup (unsigned int wparam, unsigned int lparam)
2152 int i;
2154 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2155 return;
2157 if (wparam == VK_CONTROL)
2158 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2159 else
2160 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2162 modifiers[i] = 0;
2165 /* Emacs can lose focus while a modifier key has been pressed. When
2166 it regains focus, be conservative and clear all modifiers since
2167 we cannot reconstruct the left and right modifier state. */
2168 static void
2169 reset_modifiers (void)
2171 SHORT ctrl, alt;
2173 if (GetFocus () == NULL)
2174 /* Emacs doesn't have keyboard focus. Do nothing. */
2175 return;
2177 ctrl = GetAsyncKeyState (VK_CONTROL);
2178 alt = GetAsyncKeyState (VK_MENU);
2180 if (!(ctrl & 0x08000))
2181 /* Clear any recorded control modifier state. */
2182 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2184 if (!(alt & 0x08000))
2185 /* Clear any recorded alt modifier state. */
2186 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2188 /* Update the state of all modifier keys, because modifiers used in
2189 hot-key combinations can get stuck on if Emacs loses focus as a
2190 result of a hot-key being pressed. */
2192 BYTE keystate[256];
2194 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2196 memset (keystate, 0, sizeof (keystate));
2197 GetKeyboardState (keystate);
2198 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2199 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2200 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2201 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2202 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2203 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2204 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2205 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2206 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2207 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2208 SetKeyboardState (keystate);
2212 /* Synchronize modifier state with what is reported with the current
2213 keystroke. Even if we cannot distinguish between left and right
2214 modifier keys, we know that, if no modifiers are set, then neither
2215 the left or right modifier should be set. */
2216 static void
2217 sync_modifiers (void)
2219 if (!modifiers_recorded)
2220 return;
2222 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2223 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2225 if (!(GetKeyState (VK_MENU) & 0x8000))
2226 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2229 static int
2230 modifier_set (int vkey)
2232 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2233 toggle keys is not an omission! If you want to add it, you will
2234 have to make changes in the default sub-case of the WM_KEYDOWN
2235 switch, because if the NUMLOCK modifier is set, the code there
2236 will directly convert any key that looks like an ASCII letter,
2237 and also downcase those that look like upper-case ASCII. */
2238 if (vkey == VK_CAPITAL)
2240 if (NILP (Vw32_enable_caps_lock))
2241 return 0;
2242 else
2243 return (GetKeyState (vkey) & 0x1);
2245 if (vkey == VK_SCROLL)
2247 if (NILP (Vw32_scroll_lock_modifier)
2248 /* w32-scroll-lock-modifier can be any non-nil value that is
2249 not one of the modifiers, in which case it shall be ignored. */
2250 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2251 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2252 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2253 || EQ (Vw32_scroll_lock_modifier, Qalt)
2254 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2255 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2256 return 0;
2257 else
2258 return (GetKeyState (vkey) & 0x1);
2261 if (!modifiers_recorded)
2262 return (GetKeyState (vkey) & 0x8000);
2264 switch (vkey)
2266 case VK_LCONTROL:
2267 return modifiers[EMACS_LCONTROL];
2268 case VK_RCONTROL:
2269 return modifiers[EMACS_RCONTROL];
2270 case VK_LMENU:
2271 return modifiers[EMACS_LMENU];
2272 case VK_RMENU:
2273 return modifiers[EMACS_RMENU];
2275 return (GetKeyState (vkey) & 0x8000);
2278 /* Convert between the modifier bits W32 uses and the modifier bits
2279 Emacs uses. */
2281 unsigned int
2282 w32_key_to_modifier (int key)
2284 Lisp_Object key_mapping;
2286 switch (key)
2288 case VK_LWIN:
2289 key_mapping = Vw32_lwindow_modifier;
2290 break;
2291 case VK_RWIN:
2292 key_mapping = Vw32_rwindow_modifier;
2293 break;
2294 case VK_APPS:
2295 key_mapping = Vw32_apps_modifier;
2296 break;
2297 case VK_SCROLL:
2298 key_mapping = Vw32_scroll_lock_modifier;
2299 break;
2300 default:
2301 key_mapping = Qnil;
2304 /* NB. This code runs in the input thread, asynchronously to the lisp
2305 thread, so we must be careful to ensure access to lisp data is
2306 thread-safe. The following code is safe because the modifier
2307 variable values are updated atomically from lisp and symbols are
2308 not relocated by GC. Also, we don't have to worry about seeing GC
2309 markbits here. */
2310 if (EQ (key_mapping, Qhyper))
2311 return hyper_modifier;
2312 if (EQ (key_mapping, Qsuper))
2313 return super_modifier;
2314 if (EQ (key_mapping, Qmeta))
2315 return meta_modifier;
2316 if (EQ (key_mapping, Qalt))
2317 return alt_modifier;
2318 if (EQ (key_mapping, Qctrl))
2319 return ctrl_modifier;
2320 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2321 return ctrl_modifier;
2322 if (EQ (key_mapping, Qshift))
2323 return shift_modifier;
2325 /* Don't generate any modifier if not explicitly requested. */
2326 return 0;
2329 static unsigned int
2330 w32_get_modifiers (void)
2332 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2333 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2334 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2335 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2336 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2337 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2338 (modifier_set (VK_MENU) ?
2339 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2342 /* We map the VK_* modifiers into console modifier constants
2343 so that we can use the same routines to handle both console
2344 and window input. */
2346 static int
2347 construct_console_modifiers (void)
2349 int mods;
2351 mods = 0;
2352 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2353 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2354 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2355 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2356 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2357 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2358 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2359 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2360 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2361 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2362 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2364 return mods;
2367 static int
2368 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2370 int mods;
2372 /* Convert to emacs modifiers. */
2373 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2375 return mods;
2378 unsigned int
2379 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2381 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2382 return virt_key;
2384 if (virt_key == VK_RETURN)
2385 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2387 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2388 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2390 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2391 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2393 if (virt_key == VK_CLEAR)
2394 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2396 return virt_key;
2399 /* List of special key combinations which w32 would normally capture,
2400 but Emacs should grab instead. Not directly visible to lisp, to
2401 simplify synchronization. Each item is an integer encoding a virtual
2402 key code and modifier combination to capture. */
2403 static Lisp_Object w32_grabbed_keys;
2405 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2406 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2407 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2408 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2410 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2411 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2412 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2414 /* Register hot-keys for reserved key combinations when Emacs has
2415 keyboard focus, since this is the only way Emacs can receive key
2416 combinations like Alt-Tab which are used by the system. */
2418 static void
2419 register_hot_keys (HWND hwnd)
2421 Lisp_Object keylist;
2423 /* Use CONSP, since we are called asynchronously. */
2424 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2426 Lisp_Object key = XCAR (keylist);
2428 /* Deleted entries get set to nil. */
2429 if (!INTEGERP (key))
2430 continue;
2432 RegisterHotKey (hwnd, HOTKEY_ID (key),
2433 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2437 static void
2438 unregister_hot_keys (HWND hwnd)
2440 Lisp_Object keylist;
2442 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2444 Lisp_Object key = XCAR (keylist);
2446 if (!INTEGERP (key))
2447 continue;
2449 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2453 #if EMACSDEBUG
2454 const char*
2455 w32_name_of_message (UINT msg)
2457 unsigned i;
2458 static char buf[64];
2459 static const struct {
2460 UINT msg;
2461 const char* name;
2462 } msgnames[] = {
2463 #define M(msg) { msg, # msg }
2464 M (WM_PAINT),
2465 M (WM_TIMER),
2466 M (WM_USER),
2467 M (WM_MOUSEMOVE),
2468 M (WM_LBUTTONUP),
2469 M (WM_KEYDOWN),
2470 M (WM_EMACS_KILL),
2471 M (WM_EMACS_CREATEWINDOW),
2472 M (WM_EMACS_DONE),
2473 M (WM_EMACS_CREATEVSCROLLBAR),
2474 M (WM_EMACS_CREATEHSCROLLBAR),
2475 M (WM_EMACS_SHOWWINDOW),
2476 M (WM_EMACS_SETWINDOWPOS),
2477 M (WM_EMACS_DESTROYWINDOW),
2478 M (WM_EMACS_TRACKPOPUPMENU),
2479 M (WM_EMACS_SETFOCUS),
2480 M (WM_EMACS_SETFOREGROUND),
2481 M (WM_EMACS_SETLOCALE),
2482 M (WM_EMACS_SETKEYBOARDLAYOUT),
2483 M (WM_EMACS_REGISTER_HOT_KEY),
2484 M (WM_EMACS_UNREGISTER_HOT_KEY),
2485 M (WM_EMACS_TOGGLE_LOCK_KEY),
2486 M (WM_EMACS_TRACK_CARET),
2487 M (WM_EMACS_DESTROY_CARET),
2488 M (WM_EMACS_SHOW_CARET),
2489 M (WM_EMACS_HIDE_CARET),
2490 M (WM_EMACS_SETCURSOR),
2491 M (WM_EMACS_SHOWCURSOR),
2492 M (WM_EMACS_PAINT),
2493 M (WM_CHAR),
2494 #undef M
2495 { 0, 0 }
2498 for (i = 0; msgnames[i].name; ++i)
2499 if (msgnames[i].msg == msg)
2500 return msgnames[i].name;
2502 sprintf (buf, "message 0x%04x", (unsigned)msg);
2503 return buf;
2505 #endif /* EMACSDEBUG */
2507 /* Here's an overview of how Emacs input works in GUI sessions on
2508 MS-Windows. (For description of non-GUI input, see the commentary
2509 before w32_console_read_socket in w32inevt.c.)
2511 System messages are read and processed by w32_msg_pump below. This
2512 function runs in a separate thread. It handles a small number of
2513 custom WM_EMACS_* messages (posted by the main thread, look for
2514 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2515 is the main window procedure for the entire Emacs application.
2517 w32_wnd_proc also runs in the same separate input thread. It
2518 handles some messages, mostly those that need GDI calls, by itself.
2519 For the others, it calls my_post_msg, which inserts the messages
2520 into the input queue serviced by w32_read_socket.
2522 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2523 called synchronously from keyboard.c when it is known or suspected
2524 that some input is available. w32_read_socket either handles
2525 messages immediately, or converts them into Emacs input events and
2526 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2527 them and process them when read_char and its callers require
2528 input.
2530 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2531 select(2) takes the place of w32_read_socket.
2535 /* Main message dispatch loop. */
2537 static void
2538 w32_msg_pump (deferred_msg * msg_buf)
2540 MSG msg;
2541 WPARAM result;
2542 HWND focus_window;
2544 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2546 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2549 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2550 /* w32_name_of_message (msg.message), msg.time)); */
2552 if (msg.hwnd == NULL)
2554 switch (msg.message)
2556 case WM_NULL:
2557 /* Produced by complete_deferred_msg; just ignore. */
2558 break;
2559 case WM_EMACS_CREATEWINDOW:
2560 /* Initialize COM for this window. Even though we don't use it,
2561 some third party shell extensions can cause it to be used in
2562 system dialogs, which causes a crash if it is not initialized.
2563 This is a known bug in Windows, which was fixed long ago, but
2564 the patch for XP is not publicly available until XP SP3,
2565 and older versions will never be patched. */
2566 CoInitialize (NULL);
2567 w32_createwindow ((struct frame *) msg.wParam,
2568 (int *) msg.lParam);
2569 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2570 emacs_abort ();
2571 break;
2572 case WM_EMACS_SETLOCALE:
2573 SetThreadLocale (msg.wParam);
2574 /* Reply is not expected. */
2575 break;
2576 case WM_EMACS_SETKEYBOARDLAYOUT:
2577 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2578 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2579 result, 0))
2580 emacs_abort ();
2581 break;
2582 case WM_EMACS_REGISTER_HOT_KEY:
2583 focus_window = GetFocus ();
2584 if (focus_window != NULL)
2585 RegisterHotKey (focus_window,
2586 RAW_HOTKEY_ID (msg.wParam),
2587 RAW_HOTKEY_MODIFIERS (msg.wParam),
2588 RAW_HOTKEY_VK_CODE (msg.wParam));
2589 /* Reply is not expected. */
2590 break;
2591 case WM_EMACS_UNREGISTER_HOT_KEY:
2592 focus_window = GetFocus ();
2593 if (focus_window != NULL)
2594 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2595 /* Mark item as erased. NB: this code must be
2596 thread-safe. The next line is okay because the cons
2597 cell is never made into garbage and is not relocated by
2598 GC. */
2599 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
2600 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2601 emacs_abort ();
2602 break;
2603 case WM_EMACS_TOGGLE_LOCK_KEY:
2605 int vk_code = (int) msg.wParam;
2606 int cur_state = (GetKeyState (vk_code) & 1);
2607 int new_state = msg.lParam;
2609 if (new_state == -1
2610 || ((new_state & 1) != cur_state))
2612 one_w32_display_info.faked_key = vk_code;
2614 keybd_event ((BYTE) vk_code,
2615 (BYTE) MapVirtualKey (vk_code, 0),
2616 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2617 keybd_event ((BYTE) vk_code,
2618 (BYTE) MapVirtualKey (vk_code, 0),
2619 KEYEVENTF_EXTENDEDKEY | 0, 0);
2620 keybd_event ((BYTE) vk_code,
2621 (BYTE) MapVirtualKey (vk_code, 0),
2622 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2623 cur_state = !cur_state;
2625 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2626 cur_state, 0))
2627 emacs_abort ();
2629 break;
2630 #ifdef MSG_DEBUG
2631 /* Broadcast messages make it here, so you need to be looking
2632 for something in particular for this to be useful. */
2633 default:
2634 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2635 #endif
2638 else
2640 if (w32_unicode_gui)
2641 DispatchMessageW (&msg);
2642 else
2643 DispatchMessageA (&msg);
2646 /* Exit nested loop when our deferred message has completed. */
2647 if (msg_buf->completed)
2648 break;
2652 deferred_msg * deferred_msg_head;
2654 static deferred_msg *
2655 find_deferred_msg (HWND hwnd, UINT msg)
2657 deferred_msg * item;
2659 /* Don't actually need synchronization for read access, since
2660 modification of single pointer is always atomic. */
2661 /* enter_crit (); */
2663 for (item = deferred_msg_head; item != NULL; item = item->next)
2664 if (item->w32msg.msg.hwnd == hwnd
2665 && item->w32msg.msg.message == msg)
2666 break;
2668 /* leave_crit (); */
2670 return item;
2673 static LRESULT
2674 send_deferred_msg (deferred_msg * msg_buf,
2675 HWND hwnd,
2676 UINT msg,
2677 WPARAM wParam,
2678 LPARAM lParam)
2680 /* Only input thread can send deferred messages. */
2681 if (GetCurrentThreadId () != dwWindowsThreadId)
2682 emacs_abort ();
2684 /* It is an error to send a message that is already deferred. */
2685 if (find_deferred_msg (hwnd, msg) != NULL)
2686 emacs_abort ();
2688 /* Enforced synchronization is not needed because this is the only
2689 function that alters deferred_msg_head, and the following critical
2690 section is guaranteed to only be serially reentered (since only the
2691 input thread can call us). */
2693 /* enter_crit (); */
2695 msg_buf->completed = 0;
2696 msg_buf->next = deferred_msg_head;
2697 deferred_msg_head = msg_buf;
2698 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2700 /* leave_crit (); */
2702 /* Start a new nested message loop to process other messages until
2703 this one is completed. */
2704 w32_msg_pump (msg_buf);
2706 deferred_msg_head = msg_buf->next;
2708 return msg_buf->result;
2711 void
2712 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2714 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2716 if (msg_buf == NULL)
2717 /* Message may have been canceled, so don't abort. */
2718 return;
2720 msg_buf->result = result;
2721 msg_buf->completed = 1;
2723 /* Ensure input thread is woken so it notices the completion. */
2724 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2727 static void
2728 cancel_all_deferred_msgs (void)
2730 deferred_msg * item;
2732 /* Don't actually need synchronization for read access, since
2733 modification of single pointer is always atomic. */
2734 /* enter_crit (); */
2736 for (item = deferred_msg_head; item != NULL; item = item->next)
2738 item->result = 0;
2739 item->completed = 1;
2742 /* leave_crit (); */
2744 /* Ensure input thread is woken so it notices the completion. */
2745 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2748 DWORD WINAPI
2749 w32_msg_worker (void *arg)
2751 MSG msg;
2752 deferred_msg dummy_buf;
2754 /* Ensure our message queue is created */
2756 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2758 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2759 emacs_abort ();
2761 memset (&dummy_buf, 0, sizeof (dummy_buf));
2762 dummy_buf.w32msg.msg.hwnd = NULL;
2763 dummy_buf.w32msg.msg.message = WM_NULL;
2765 /* This is the initial message loop which should only exit when the
2766 application quits. */
2767 w32_msg_pump (&dummy_buf);
2769 return 0;
2772 static void
2773 signal_user_input (void)
2775 /* Interrupt any lisp that wants to be interrupted by input. */
2776 if (!NILP (Vthrow_on_input))
2778 Vquit_flag = Vthrow_on_input;
2779 /* Doing a QUIT from this thread is a bad idea, since this
2780 unwinds the stack of the Lisp thread, and the Windows runtime
2781 rightfully barfs. Disabled. */
2782 #if 0
2783 /* If we're inside a function that wants immediate quits,
2784 do it now. */
2785 if (immediate_quit && NILP (Vinhibit_quit))
2787 immediate_quit = 0;
2788 QUIT;
2790 #endif
2795 static void
2796 post_character_message (HWND hwnd, UINT msg,
2797 WPARAM wParam, LPARAM lParam,
2798 DWORD modifiers)
2800 W32Msg wmsg;
2802 wmsg.dwModifiers = modifiers;
2804 /* Detect quit_char and set quit-flag directly. Note that we
2805 still need to post a message to ensure the main thread will be
2806 woken up if blocked in sys_select, but we do NOT want to post
2807 the quit_char message itself (because it will usually be as if
2808 the user had typed quit_char twice). Instead, we post a dummy
2809 message that has no particular effect. */
2811 int c = wParam;
2812 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2813 c = make_ctrl_char (c) & 0377;
2814 if (c == quit_char
2815 || (wmsg.dwModifiers == 0
2816 && w32_quit_key && wParam == w32_quit_key))
2818 Vquit_flag = Qt;
2820 /* The choice of message is somewhat arbitrary, as long as
2821 the main thread handler just ignores it. */
2822 msg = WM_NULL;
2824 /* Interrupt any blocking system calls. */
2825 signal_quit ();
2827 /* As a safety precaution, forcibly complete any deferred
2828 messages. This is a kludge, but I don't see any particularly
2829 clean way to handle the situation where a deferred message is
2830 "dropped" in the lisp thread, and will thus never be
2831 completed, eg. by the user trying to activate the menubar
2832 when the lisp thread is busy, and then typing C-g when the
2833 menubar doesn't open promptly (with the result that the
2834 menubar never responds at all because the deferred
2835 WM_INITMENU message is never completed). Another problem
2836 situation is when the lisp thread calls SendMessage (to send
2837 a window manager command) when a message has been deferred;
2838 the lisp thread gets blocked indefinitely waiting for the
2839 deferred message to be completed, which itself is waiting for
2840 the lisp thread to respond.
2842 Note that we don't want to block the input thread waiting for
2843 a response from the lisp thread (although that would at least
2844 solve the deadlock problem above), because we want to be able
2845 to receive C-g to interrupt the lisp thread. */
2846 cancel_all_deferred_msgs ();
2848 else
2849 signal_user_input ();
2852 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2855 static int
2856 get_wm_chars (HWND aWnd, int *buf, int buflen, int ignore_ctrl, int ctrl,
2857 int *ctrl_cnt, int *is_dead, int vk, int exp)
2859 MSG msg;
2860 /* If doubled is at the end, ignore it. */
2861 int i = buflen, doubled = 0, code_unit;
2863 if (ctrl_cnt)
2864 *ctrl_cnt = 0;
2865 if (is_dead)
2866 *is_dead = -1;
2867 eassert (w32_unicode_gui);
2868 while (buflen
2869 /* Should be called only when w32_unicode_gui: */
2870 && PeekMessageW (&msg, aWnd, WM_KEYFIRST, WM_KEYLAST,
2871 PM_NOREMOVE | PM_NOYIELD)
2872 && (msg.message == WM_CHAR || msg.message == WM_SYSCHAR
2873 || msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR
2874 || msg.message == WM_UNICHAR))
2876 /* We extract character payload, but in this call we handle only the
2877 characters which come BEFORE the next keyup/keydown message. */
2878 int dead;
2880 GetMessageW (&msg, aWnd, msg.message, msg.message);
2881 dead = (msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR);
2882 if (is_dead)
2883 *is_dead = (dead ? msg.wParam : -1);
2884 if (dead)
2885 continue;
2886 code_unit = msg.wParam;
2887 if (doubled)
2889 /* Had surrogate. */
2890 if (msg.message == WM_UNICHAR
2891 || code_unit < 0xDC00 || code_unit > 0xDFFF)
2892 { /* Mismatched first surrogate.
2893 Pass both code units as if they were two characters. */
2894 *buf++ = doubled;
2895 if (!--buflen)
2896 return i; /* Drop the 2nd char if at the end of the buffer. */
2898 else /* see https://en.wikipedia.org/wiki/UTF-16 */
2899 code_unit = (doubled << 10) + code_unit - 0x35FDC00;
2900 doubled = 0;
2902 else if (code_unit >= 0xD800 && code_unit <= 0xDBFF)
2904 /* Handle mismatched 2nd surrogate the same as a normal character. */
2905 doubled = code_unit;
2906 continue;
2909 /* The only "fake" characters delivered by ToUnicode() or
2910 TranslateMessage() are:
2911 0x01 .. 0x1a for Ctrl-letter, Enter, Tab, Ctrl-Break, Esc, Backspace
2912 0x00 and 0x1b .. 0x1f for Control- []\@^_
2913 0x7f for Control-BackSpace
2914 0x20 for Control-Space */
2915 if (ignore_ctrl
2916 && (code_unit < 0x20 || code_unit == 0x7f
2917 || (code_unit == 0x20 && ctrl)))
2919 /* Non-character payload in a WM_CHAR
2920 (Ctrl-something pressed, see above). Ignore, and report. */
2921 if (ctrl_cnt)
2922 *ctrl_cnt++;
2923 continue;
2925 /* Traditionally, Emacs would ignore the character payload of VK_NUMPAD*
2926 keys, and would treat them later via `function-key-map'. In addition
2927 to usual 102-key NUMPAD keys, this map also treats `kp-'-variants of
2928 space, tab, enter, separator, equal. TAB and EQUAL, apparently,
2929 cannot be generated on Win-GUI branch. ENTER is already handled
2930 by the code above. According to `lispy_function_keys', kp_space is
2931 generated by not-extended VK_CLEAR. (kp-tab != VK_OEM_NEC_EQUAL!).
2933 We do similarly for backward-compatibility, but ignore only the
2934 characters restorable later by `function-key-map'. */
2935 if (code_unit < 0x7f
2936 && ((vk >= VK_NUMPAD0 && vk <= VK_DIVIDE)
2937 || (exp && ((vk >= VK_PRIOR && vk <= VK_DOWN) ||
2938 vk == VK_INSERT || vk == VK_DELETE || vk == VK_CLEAR)))
2939 && strchr ("0123456789/*-+.,", code_unit))
2940 continue;
2941 *buf++ = code_unit;
2942 buflen--;
2944 return i - buflen;
2947 #ifdef DBG_WM_CHARS
2948 # define FPRINTF_WM_CHARS(ARG) fprintf ARG
2949 #else
2950 # define FPRINTF_WM_CHARS(ARG) 0
2951 #endif
2953 /* This is a heuristic only. This is supposed to track the state of the
2954 finite automaton in the language environment of Windows.
2956 However, separate windows (if with the same different language
2957 environments!) should have different values. Moreover, switching to a
2958 non-Emacs window with the same language environment, and using (dead)keys
2959 there would change the value stored in the kernel, but not this value. */
2960 /* A layout may emit deadkey=0. It looks like this would reset the state
2961 of the kernel's finite automaton (equivalent to emiting 0-length string,
2962 which is otherwise impossible in the dead-key map of a layout).
2963 Be ready to treat the case when this delivers WM_(SYS)DEADCHAR. */
2964 static int after_deadkey = -1;
2967 deliver_wm_chars (int do_translate, HWND hwnd, UINT msg, UINT wParam,
2968 UINT lParam, int legacy_alt_meta)
2970 /* An "old style" keyboard description may assign up to 125 UTF-16 code
2971 points to a keypress.
2972 (However, the "old style" TranslateMessage() would deliver at most 16 of
2973 them.) Be on a safe side, and prepare to treat many more. */
2974 int ctrl_cnt, buf[1024], count, is_dead, after_dead = (after_deadkey > 0);
2976 /* Since the keypress processing logic of Windows has a lot of state, it
2977 is important to call TranslateMessage() for every keyup/keydown, AND
2978 do it exactly once. (The actual change of state is done by
2979 ToUnicode[Ex](), which is called by TranslateMessage(). So one can
2980 call ToUnicode[Ex]() instead.)
2982 The "usual" message pump calls TranslateMessage() for EVERY event.
2983 Emacs calls TranslateMessage() very selectively (is it needed for doing
2984 some tricky stuff with Win95??? With newer Windows, selectiveness is,
2985 most probably, not needed -- and harms a lot).
2987 So, with the usual message pump, the following call to TranslateMessage()
2988 is not needed (and is going to be VERY harmful). With Emacs' message
2989 pump, the call is needed. */
2990 if (do_translate)
2992 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
2994 windows_msg.time = GetMessageTime ();
2995 TranslateMessage (&windows_msg);
2997 count = get_wm_chars (hwnd, buf, sizeof (buf)/sizeof (*buf), 1,
2998 /* The message may have been synthesized by
2999 who knows what; be conservative. */
3000 modifier_set (VK_LCONTROL)
3001 || modifier_set (VK_RCONTROL)
3002 || modifier_set (VK_CONTROL),
3003 &ctrl_cnt, &is_dead, wParam,
3004 (lParam & 0x1000000L) != 0);
3005 if (count)
3007 W32Msg wmsg;
3008 DWORD console_modifiers = construct_console_modifiers ();
3009 int *b = buf, strip_Alt = 1, strip_ExtraMods = 1, hairy = 0;
3010 char *type_CtrlAlt = NULL;
3012 /* XXXX In fact, there may be another case when we need to do the same:
3013 What happens if the string defined in the LIGATURES has length
3014 0? Probably, we will get count==0, but the state of the finite
3015 automaton would reset to 0??? */
3016 after_deadkey = -1;
3018 /* wParam is checked when converting CapsLock to Shift; this is a clone
3019 of w32_get_key_modifiers (). */
3020 wmsg.dwModifiers = w32_kbd_mods_to_emacs (console_modifiers, wParam);
3022 /* What follows is just heuristics; the correct treatement requires
3023 non-destructive ToUnicode():
3024 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Can_an_application_on_Windows_accept_keyboard_events?_Part_IV:_application-specific_modifiers
3026 What one needs to find is:
3027 * which of the present modifiers AFFECT the resulting char(s)
3028 (so should be stripped, since their EFFECT is "already
3029 taken into account" in the string in buf), and
3030 * which modifiers are not affecting buf, so should be reported to
3031 the application for further treatment.
3033 Example: assume that we know:
3034 (A) lCtrl+rCtrl+rAlt modifiers with VK_A key produce a Latin "f"
3035 ("may be logical" in JCUKEN-flavored Russian keyboard flavors);
3036 (B) removing any of lCtrl, rCtrl, rAlt changes the produced char;
3037 (C) Win-modifier is not affecting the produced character
3038 (this is the common case: happens with all "standard" layouts).
3040 Suppose the user presses Win+lCtrl+rCtrl+rAlt modifiers with VK_A.
3041 What is the intent of the user? We need to guess the intent to decide
3042 which event to deliver to the application.
3044 This looks like a reasonable logic: since Win- modifier doesn't affect
3045 the output string, the user was pressing Win for SOME OTHER purpose.
3046 So the user wanted to generate Win-SOMETHING event. Now, what is
3047 something? If one takes the mantra that "character payload is more
3048 important than the combination of keypresses which resulted in this
3049 payload", then one should ignore lCtrl+rCtrl+rAlt, ignore VK_A, and
3050 assume that the user wanted to generate Win-f.
3052 Unfortunately, without non-destructive ToUnicode(), checking (B),(C)
3053 is out of question. So we use heuristics (hopefully, covering
3054 99.9999% of cases). */
3056 /* Another thing to watch for is a possibility to use AltGr-* and
3057 Ctrl-Alt-* with different semantic.
3059 Background: the layout defining the KLLF_ALTGR bit are treated
3060 specially by the kernel: when VK_RMENU (=rightAlt, =AltGr) is pressed
3061 (released), a press (release) of VK_LCONTROL is emulated (unless Ctrl
3062 is already down). As a result, any press/release of AltGr is seen
3063 by applications as a press/release of lCtrl AND rAlt. This is
3064 applicable, in particular, to ToUnicode[Ex](). (Keyrepeat is covered
3065 the same way!)
3067 NOTE: it IS possible to see bare rAlt even with KLLF_ALTGR; but this
3068 requires a good finger coordination: doing (physically)
3069 Down-lCtrl Down-rAlt Up-lCtrl Down-a
3070 (doing quick enough, so that key repeat of rAlt [which would
3071 generate new "fake" Down-lCtrl events] does not happens before 'a'
3072 is down) results in no "fake" events, so the application will see
3073 only rAlt down when 'a' is pressed. (However, fake Up-lCtrl WILL
3074 be generated when rAlt goes UP.)
3076 In fact, note also that KLLF_ALTGR does not prohibit construction of
3077 rCtrl-rAlt (just press them in this order!).
3079 Moreover: "traditional" layouts do not define distinct modifier-masks
3080 for VK_LMENU and VK_RMENU (same for VK_L/RCONTROL). Instead, they
3081 rely on the KLLF_ALTGR bit to make the behavior of VK_LMENU and
3082 VK_RMENU distinct. As a corollary, for such layouts, the produced
3083 character is the same for AltGr-* (=rAlt-*) and Ctrl-Alt-* (in any
3084 combination of handedness). For description of masks, see
3086 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Keyboard_input_on_Windows,_Part_I:_what_is_the_kernel_doing?
3088 By default, Emacs was using these coincidences via the following
3089 heuristics: it was treating:
3090 (*) keypresses with lCtrl-rAlt modifiers as if they are carrying
3091 ONLY the character payload (no matter what the actual keyboard
3092 was defining: if lCtrl-lAlt-b was delivering U+05df=beta, then
3093 Emacs saw [beta]; if lCtrl-lAlt-b was undefined in the layout,
3094 the keypress was completely ignored), and
3095 (*) keypresses with the other combinations of handedness of Ctrl-Alt
3096 modifiers (e.g., lCtrl-lAlt) as if they NEVER carry a character
3097 payload (so they were reported "raw": if lCtrl-lAlt-b was
3098 delivering beta, then Emacs saw event [C-A-b], and not [beta]).
3099 This worked good for "traditional" layouts: users could type both
3100 AltGr-x and Ctrl-Alt-x, and one was a character, another a bindable
3101 event.
3103 However, for layouts which deliver different characters for AltGr-x
3104 and lCtrl-lAlt-x, this scheme makes the latter character unaccessible
3105 in Emacs. While it is easy to access functionality of [C-M-x] in
3106 Emacs by other means (for example, by the `controlify' prefix, or
3107 using lCtrl-rCtrl-x, or rCtrl-rAlt-x [in this order]), missing
3108 characters cannot be reconstructed without a tedious manual work. */
3110 /* These two cases are often going to be distinguishable, since at most
3111 one of these character is defined with KBDCTRL | KBDMENU modifier
3112 bitmap. (This heuristic breaks if both lCtrl-lAlt- AND lCtrl-rAlt-
3113 are translated to modifier bitmaps distinct from KBDCTRL | KBDMENU,
3114 or in the cases when lCtrl-lAlt-* and lCtrl-rAlt-* are generally
3115 different, but lCtrl-lAlt-x and lCtrl-rAlt-x happen to deliver the
3116 same character.)
3118 So we have 2 chunks of info:
3119 (A) is it lCtrl-rAlt-, or lCtrl-lAlt, or some other combination?
3120 (B) is the delivered character defined with KBDCTRL | KBDMENU bits?
3121 Basing on (A) and (B), we should decide whether to ignore the
3122 delivered character. (Before, Emacs was completely ignoring (B), and
3123 was treating the 3-state of (A) as a bit.) This means that we have 6
3124 bits of customization.
3126 Additionally, a presence of two Ctrl down may be AltGr-rCtrl-. */
3128 /* Strip all non-Shift modifiers if:
3129 - more than one UTF-16 code point delivered (can't call VkKeyScanW ())
3130 - or the character is a result of combining with a prefix key. */
3131 if (!after_dead && count == 1 && *b < 0x10000)
3133 if (console_modifiers & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
3134 && console_modifiers & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
3136 type_CtrlAlt = "bB"; /* generic bindable Ctrl-Alt- modifiers */
3137 if (console_modifiers & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)
3138 == (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3139 /* double-Ctrl:
3140 e.g. AltGr-rCtrl on some layouts (in this order!) */
3141 type_CtrlAlt = "dD";
3142 else if (console_modifiers
3143 & (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED)
3144 == (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3145 type_CtrlAlt = "lL"; /* Ctrl-Alt- modifiers on the left */
3146 else if (!NILP (Vw32_recognize_altgr)
3147 && (console_modifiers
3148 & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
3149 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
3150 type_CtrlAlt = "gG"; /* modifiers as in AltGr */
3152 else if (wmsg.dwModifiers & (alt_modifier | meta_modifier)
3153 || (console_modifiers
3154 & (LEFT_WIN_PRESSED | RIGHT_WIN_PRESSED
3155 | APPS_PRESSED | SCROLLLOCK_ON)))
3157 /* Pure Alt (or combination of Alt, Win, APPS, scrolllock. */
3158 type_CtrlAlt = "aA";
3160 if (type_CtrlAlt)
3162 /* Out of bound bitmap: */
3163 SHORT r = VkKeyScanW (*b), bitmap = 0x1FF;
3165 FPRINTF_WM_CHARS((stderr, "VkKeyScanW %#06x %#04x\n", (int)r,
3166 wParam));
3167 if ((r & 0xFF) == wParam)
3168 bitmap = r>>8; /* *b is reachable via simple interface */
3169 if (*type_CtrlAlt == 'a') /* Simple Alt seen */
3171 if ((bitmap & ~1) == 0) /* 1: KBDSHIFT */
3173 /* In "traditional" layouts, Alt without Ctrl does not
3174 change the delivered character. This detects this
3175 situation; it is safe to report this as Alt-something
3176 -- as opposed to delivering the reported character
3177 without modifiers. */
3178 if (legacy_alt_meta
3179 && *b > 0x7f && ('A' <= wParam && wParam <= 'Z'))
3180 /* For backward-compatibility with older Emacsen, let
3181 this be processed by another branch below (which
3182 would convert it to Alt-Latin char via wParam). */
3183 return 0;
3185 else
3186 hairy = 1;
3188 /* Check whether the delivered character(s) is accessible via
3189 KBDCTRL | KBDALT ( | KBDSHIFT ) modifier mask (which is 7). */
3190 else if ((bitmap & ~1) != 6)
3192 /* The character is not accessible via plain Ctrl-Alt(-Shift)
3193 (which is, probably, same as AltGr) modifiers.
3194 Either it was after a prefix key, or is combined with
3195 modifier keys which we don't see, or there is an asymmetry
3196 between left-hand and right-hand modifiers, or other hairy
3197 stuff. */
3198 hairy = 1;
3200 /* The best solution is to delegate these tough (but rarely
3201 needed) choices to the user. Temporarily (???), it is
3202 implemented as C macros.
3204 Essentially, there are 3 things to do: return 0 (handle to the
3205 legacy processing code [ignoring the character payload]; keep
3206 some modifiers (so that they will be processed by the binding
3207 system [on top of the character payload]; strip modifiers [so
3208 that `self-insert' is going to be triggered with the character
3209 payload]).
3211 The default below should cover 99.9999% of cases:
3212 (a) strip Alt- in the hairy case only;
3213 (stripping = not ignoring)
3214 (l) for lAlt-lCtrl, ignore the char in simple cases only;
3215 (g) for what looks like AltGr, ignore the modifiers;
3216 (d) for what looks like lCtrl-rCtrl-Alt (probably
3217 AltGr-rCtrl), ignore the character in simple cases only;
3218 (b) for other cases of Ctrl-Alt, ignore the character in
3219 simple cases only.
3221 Essentially, in all hairy cases, and in looks-like-AltGr case,
3222 we keep the character, ignoring the modifiers. In all the
3223 other cases, we ignore the delivered character. */
3224 #define S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD "aldb"
3225 #define S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS ""
3226 if (strchr (S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD,
3227 type_CtrlAlt[hairy]))
3228 return 0;
3229 /* If in neither list, report all the modifiers we see COMBINED
3230 WITH the reported character. */
3231 if (strchr (S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS,
3232 type_CtrlAlt[hairy]))
3233 strip_ExtraMods = 0;
3236 if (strip_ExtraMods)
3237 wmsg.dwModifiers = wmsg.dwModifiers & shift_modifier;
3239 signal_user_input ();
3240 while (count--)
3242 FPRINTF_WM_CHARS((stderr, "unichar %#06x\n", *b));
3243 my_post_msg (&wmsg, hwnd, WM_UNICHAR, *b++, lParam);
3245 if (!ctrl_cnt) /* Process ALSO as ctrl */
3246 return 1;
3247 else
3248 FPRINTF_WM_CHARS((stderr, "extra ctrl char\n"));
3249 return -1;
3251 else if (is_dead >= 0)
3253 FPRINTF_WM_CHARS((stderr, "dead %#06x\n", is_dead));
3254 after_deadkey = is_dead;
3255 return 1;
3257 return 0;
3260 /* Main window procedure */
3262 static LRESULT CALLBACK
3263 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
3265 struct frame *f;
3266 struct w32_display_info *dpyinfo = &one_w32_display_info;
3267 W32Msg wmsg;
3268 int windows_translate;
3269 int key;
3271 /* Note that it is okay to call x_window_to_frame, even though we are
3272 not running in the main lisp thread, because frame deletion
3273 requires the lisp thread to synchronize with this thread. Thus, if
3274 a frame struct is returned, it can be used without concern that the
3275 lisp thread might make it disappear while we are using it.
3277 NB. Walking the frame list in this thread is safe (as long as
3278 writes of Lisp_Object slots are atomic, which they are on Windows).
3279 Although delete-frame can destructively modify the frame list while
3280 we are walking it, a garbage collection cannot occur until after
3281 delete-frame has synchronized with this thread.
3283 It is also safe to use functions that make GDI calls, such as
3284 w32_clear_rect, because these functions must obtain a DC handle
3285 from the frame struct using get_frame_dc which is thread-aware. */
3287 switch (msg)
3289 case WM_ERASEBKGND:
3290 f = x_window_to_frame (dpyinfo, hwnd);
3291 if (f)
3293 HDC hdc = get_frame_dc (f);
3294 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
3295 w32_clear_rect (f, hdc, &wmsg.rect);
3296 release_frame_dc (f, hdc);
3298 #if defined (W32_DEBUG_DISPLAY)
3299 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
3301 wmsg.rect.left, wmsg.rect.top,
3302 wmsg.rect.right, wmsg.rect.bottom));
3303 #endif /* W32_DEBUG_DISPLAY */
3305 return 1;
3306 case WM_PALETTECHANGED:
3307 /* ignore our own changes */
3308 if ((HWND)wParam != hwnd)
3310 f = x_window_to_frame (dpyinfo, hwnd);
3311 if (f)
3312 /* get_frame_dc will realize our palette and force all
3313 frames to be redrawn if needed. */
3314 release_frame_dc (f, get_frame_dc (f));
3316 return 0;
3317 case WM_PAINT:
3319 PAINTSTRUCT paintStruct;
3320 RECT update_rect;
3321 memset (&update_rect, 0, sizeof (update_rect));
3323 f = x_window_to_frame (dpyinfo, hwnd);
3324 if (f == 0)
3326 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
3327 return 0;
3330 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
3331 fails. Apparently this can happen under some
3332 circumstances. */
3333 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
3335 enter_crit ();
3336 BeginPaint (hwnd, &paintStruct);
3338 /* The rectangles returned by GetUpdateRect and BeginPaint
3339 do not always match. Play it safe by assuming both areas
3340 are invalid. */
3341 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
3343 #if defined (W32_DEBUG_DISPLAY)
3344 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
3346 wmsg.rect.left, wmsg.rect.top,
3347 wmsg.rect.right, wmsg.rect.bottom));
3348 DebPrint ((" [update region is %d,%d-%d,%d]\n",
3349 update_rect.left, update_rect.top,
3350 update_rect.right, update_rect.bottom));
3351 #endif
3352 EndPaint (hwnd, &paintStruct);
3353 leave_crit ();
3355 /* Change the message type to prevent Windows from
3356 combining WM_PAINT messages in the Lisp thread's queue,
3357 since Windows assumes that each message queue is
3358 dedicated to one frame and does not bother checking
3359 that hwnd matches before combining them. */
3360 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
3362 return 0;
3365 /* If GetUpdateRect returns 0 (meaning there is no update
3366 region), assume the whole window needs to be repainted. */
3367 GetClientRect (hwnd, &wmsg.rect);
3368 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3369 return 0;
3372 case WM_INPUTLANGCHANGE:
3373 /* Inform lisp thread of keyboard layout changes. */
3374 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3376 /* The state of the finite automaton is separate per every input
3377 language environment (so it does not change when one switches
3378 to a different window with the same environment). Moreover,
3379 the experiments show that the state is not remembered when
3380 one switches back to the pre-previous environment. */
3381 after_deadkey = -1;
3383 /* XXXX??? What follows is a COMPLETE misunderstanding of Windows! */
3385 /* Clear dead keys in the keyboard state; for simplicity only
3386 preserve modifier key states. */
3388 int i;
3389 BYTE keystate[256];
3391 GetKeyboardState (keystate);
3392 for (i = 0; i < 256; i++)
3393 if (1
3394 && i != VK_SHIFT
3395 && i != VK_LSHIFT
3396 && i != VK_RSHIFT
3397 && i != VK_CAPITAL
3398 && i != VK_NUMLOCK
3399 && i != VK_SCROLL
3400 && i != VK_CONTROL
3401 && i != VK_LCONTROL
3402 && i != VK_RCONTROL
3403 && i != VK_MENU
3404 && i != VK_LMENU
3405 && i != VK_RMENU
3406 && i != VK_LWIN
3407 && i != VK_RWIN)
3408 keystate[i] = 0;
3409 SetKeyboardState (keystate);
3411 goto dflt;
3413 case WM_HOTKEY:
3414 /* Synchronize hot keys with normal input. */
3415 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3416 return (0);
3418 case WM_KEYUP:
3419 case WM_SYSKEYUP:
3420 record_keyup (wParam, lParam);
3421 goto dflt;
3423 case WM_KEYDOWN:
3424 case WM_SYSKEYDOWN:
3425 /* Ignore keystrokes we fake ourself; see below. */
3426 if (dpyinfo->faked_key == wParam)
3428 dpyinfo->faked_key = 0;
3429 /* Make sure TranslateMessage sees them though (as long as
3430 they don't produce WM_CHAR messages). This ensures that
3431 indicator lights are toggled promptly on Windows 9x, for
3432 example. */
3433 if (wParam < 256 && lispy_function_keys[wParam])
3435 windows_translate = 1;
3436 goto translate;
3438 return 0;
3441 /* Synchronize modifiers with current keystroke. */
3442 sync_modifiers ();
3443 record_keydown (wParam, lParam);
3444 if (w32_use_fallback_wm_chars_method)
3445 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3447 windows_translate = 0;
3449 switch (wParam)
3451 case VK_LWIN:
3452 if (NILP (Vw32_pass_lwindow_to_system))
3454 /* Prevent system from acting on keyup (which opens the
3455 Start menu if no other key was pressed) by simulating a
3456 press of Space which we will ignore. */
3457 if (GetAsyncKeyState (wParam) & 1)
3459 if (NUMBERP (Vw32_phantom_key_code))
3460 key = XUINT (Vw32_phantom_key_code) & 255;
3461 else
3462 key = VK_SPACE;
3463 dpyinfo->faked_key = key;
3464 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3467 if (!NILP (Vw32_lwindow_modifier))
3468 return 0;
3469 break;
3470 case VK_RWIN:
3471 if (NILP (Vw32_pass_rwindow_to_system))
3473 if (GetAsyncKeyState (wParam) & 1)
3475 if (NUMBERP (Vw32_phantom_key_code))
3476 key = XUINT (Vw32_phantom_key_code) & 255;
3477 else
3478 key = VK_SPACE;
3479 dpyinfo->faked_key = key;
3480 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3483 if (!NILP (Vw32_rwindow_modifier))
3484 return 0;
3485 break;
3486 case VK_APPS:
3487 if (!NILP (Vw32_apps_modifier))
3488 return 0;
3489 break;
3490 case VK_MENU:
3491 if (NILP (Vw32_pass_alt_to_system))
3492 /* Prevent DefWindowProc from activating the menu bar if an
3493 Alt key is pressed and released by itself. */
3494 return 0;
3495 windows_translate = 1;
3496 break;
3497 case VK_CAPITAL:
3498 /* Decide whether to treat as modifier or function key. */
3499 if (NILP (Vw32_enable_caps_lock))
3500 goto disable_lock_key;
3501 windows_translate = 1;
3502 break;
3503 case VK_NUMLOCK:
3504 /* Decide whether to treat as modifier or function key. */
3505 if (NILP (Vw32_enable_num_lock))
3506 goto disable_lock_key;
3507 windows_translate = 1;
3508 break;
3509 case VK_SCROLL:
3510 /* Decide whether to treat as modifier or function key. */
3511 if (NILP (Vw32_scroll_lock_modifier))
3512 goto disable_lock_key;
3513 windows_translate = 1;
3514 break;
3515 disable_lock_key:
3516 /* Ensure the appropriate lock key state (and indicator light)
3517 remains in the same state. We do this by faking another
3518 press of the relevant key. Apparently, this really is the
3519 only way to toggle the state of the indicator lights. */
3520 dpyinfo->faked_key = wParam;
3521 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3522 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3523 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3524 KEYEVENTF_EXTENDEDKEY | 0, 0);
3525 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3526 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3527 /* Ensure indicator lights are updated promptly on Windows 9x
3528 (TranslateMessage apparently does this), after forwarding
3529 input event. */
3530 post_character_message (hwnd, msg, wParam, lParam,
3531 w32_get_key_modifiers (wParam, lParam));
3532 windows_translate = 1;
3533 break;
3534 case VK_CONTROL:
3535 case VK_SHIFT:
3536 case VK_PROCESSKEY: /* Generated by IME. */
3537 windows_translate = 1;
3538 break;
3539 case VK_CANCEL:
3540 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3541 which is confusing for purposes of key binding; convert
3542 VK_CANCEL events into VK_PAUSE events. */
3543 wParam = VK_PAUSE;
3544 break;
3545 case VK_PAUSE:
3546 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3547 for purposes of key binding; convert these back into
3548 VK_NUMLOCK events, at least when we want to see NumLock key
3549 presses. (Note that there is never any possibility that
3550 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3551 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3552 wParam = VK_NUMLOCK;
3553 break;
3554 default:
3555 if (w32_unicode_gui && !w32_use_fallback_wm_chars_method)
3557 /* If this event generates characters or deadkeys, do
3558 not interpret it as a "raw combination of modifiers
3559 and keysym". Hide deadkeys, and use the generated
3560 character(s) instead of the keysym. (Backward
3561 compatibility: exceptions for numpad keys generating
3562 0-9 . , / * - +, and for extra-Alt combined with a
3563 non-Latin char.)
3565 Try to not report modifiers which have effect on
3566 which character or deadkey is generated.
3568 Example (contrived): if rightAlt-? generates f (on a
3569 Cyrillic keyboard layout), and Ctrl, leftAlt do not
3570 affect the generated character, one wants to report
3571 Ctrl-leftAlt-f if the user presses
3572 Ctrl-leftAlt-rightAlt-?. */
3573 int res;
3574 #if 0
3575 /* Some of WM_CHAR may be fed to us directly, some are
3576 results of TranslateMessage(). Using 0 as the first
3577 argument (in a separate call) might help us
3578 distinguish these two cases.
3580 However, the keypress feeders would most probably
3581 expect the "standard" message pump, when
3582 TranslateMessage() is called on EVERY KeyDown/KeyUp
3583 event. So they may feed us Down-Ctrl Down-FAKE
3584 Char-o and expect us to recognize it as Ctrl-o.
3585 Using 0 as the first argument would interfere with
3586 this. */
3587 deliver_wm_chars (0, hwnd, msg, wParam, lParam, 1);
3588 #endif
3589 /* Processing the generated WM_CHAR messages *WHILE* we
3590 handle KEYDOWN/UP event is the best choice, since
3591 without any fuss, we know all 3 of: scancode, virtual
3592 keycode, and expansion. (Additionally, one knows
3593 boundaries of expansion of different keypresses.) */
3594 res = deliver_wm_chars (1, hwnd, msg, wParam, lParam, 1);
3595 windows_translate = -(res != 0);
3596 if (res > 0) /* Bound to character(s) or a deadkey */
3597 break;
3598 /* deliver_wm_chars may make some branches after this vestigal. */
3600 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3601 /* If not defined as a function key, change it to a WM_CHAR message. */
3602 if (wParam > 255 || !lispy_function_keys[wParam])
3604 DWORD modifiers = construct_console_modifiers ();
3606 if (!NILP (Vw32_recognize_altgr)
3607 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3609 /* Always let TranslateMessage handle AltGr key chords;
3610 for some reason, ToAscii doesn't always process AltGr
3611 chords correctly. */
3612 windows_translate = 1;
3614 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3616 /* Handle key chords including any modifiers other
3617 than shift directly, in order to preserve as much
3618 modifier information as possible. */
3619 if ('A' <= wParam && wParam <= 'Z')
3621 /* Don't translate modified alphabetic keystrokes,
3622 so the user doesn't need to constantly switch
3623 layout to type control or meta keystrokes when
3624 the normal layout translates alphabetic
3625 characters to non-ascii characters. */
3626 if (!modifier_set (VK_SHIFT))
3627 wParam += ('a' - 'A');
3628 msg = WM_CHAR;
3630 else
3632 /* Try to handle other keystrokes by determining the
3633 base character (ie. translating the base key plus
3634 shift modifier). */
3635 int add;
3636 KEY_EVENT_RECORD key;
3638 key.bKeyDown = TRUE;
3639 key.wRepeatCount = 1;
3640 key.wVirtualKeyCode = wParam;
3641 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3642 key.uChar.AsciiChar = 0;
3643 key.dwControlKeyState = modifiers;
3645 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3646 /* 0 means an unrecognized keycode, negative means
3647 dead key. Ignore both. */
3648 while (--add >= 0)
3650 /* Forward asciified character sequence. */
3651 post_character_message
3652 (hwnd, WM_CHAR,
3653 (unsigned char) key.uChar.AsciiChar, lParam,
3654 w32_get_key_modifiers (wParam, lParam));
3655 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3657 return 0;
3660 else
3662 /* Let TranslateMessage handle everything else. */
3663 windows_translate = 1;
3668 if (windows_translate == -1)
3669 break;
3670 translate:
3671 if (windows_translate)
3673 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3674 windows_msg.time = GetMessageTime ();
3675 TranslateMessage (&windows_msg);
3676 goto dflt;
3679 /* Fall through */
3681 case WM_SYSCHAR:
3682 case WM_CHAR:
3683 if (wParam > 255 )
3685 W32Msg wmsg;
3687 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3688 signal_user_input ();
3689 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3692 else
3693 post_character_message (hwnd, msg, wParam, lParam,
3694 w32_get_key_modifiers (wParam, lParam));
3695 break;
3697 case WM_UNICHAR:
3698 /* WM_UNICHAR looks promising from the docs, but the exact
3699 circumstances in which TranslateMessage sends it is one of those
3700 Microsoft secret API things that EU and US courts are supposed
3701 to have put a stop to already. Spy++ shows it being sent to Notepad
3702 and other MS apps, but never to Emacs.
3704 Some third party IMEs send it in accordance with the official
3705 documentation though, so handle it here.
3707 UNICODE_NOCHAR is used to test for support for this message.
3708 TRUE indicates that the message is supported. */
3709 if (wParam == UNICODE_NOCHAR)
3710 return TRUE;
3713 W32Msg wmsg;
3714 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3715 signal_user_input ();
3716 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3718 break;
3720 case WM_IME_CHAR:
3721 /* If we can't get the IME result as Unicode, use default processing,
3722 which will at least allow characters decodable in the system locale
3723 get through. */
3724 if (!get_composition_string_fn)
3725 goto dflt;
3727 else if (!ignore_ime_char)
3729 wchar_t * buffer;
3730 int size, i;
3731 W32Msg wmsg;
3732 HIMC context = get_ime_context_fn (hwnd);
3733 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3734 /* Get buffer size. */
3735 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3736 buffer = alloca (size);
3737 size = get_composition_string_fn (context, GCS_RESULTSTR,
3738 buffer, size);
3739 release_ime_context_fn (hwnd, context);
3741 signal_user_input ();
3742 for (i = 0; i < size / sizeof (wchar_t); i++)
3744 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3745 lParam);
3747 /* Ignore the messages for the rest of the
3748 characters in the string that was output above. */
3749 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3751 else
3752 ignore_ime_char--;
3754 break;
3756 case WM_IME_STARTCOMPOSITION:
3757 if (!set_ime_composition_window_fn)
3758 goto dflt;
3759 else
3761 COMPOSITIONFORM form;
3762 HIMC context;
3763 struct window *w;
3765 /* Implementation note: The code below does something that
3766 one shouldn't do: it accesses the window object from a
3767 separate thread, while the main (a.k.a. "Lisp") thread
3768 runs and can legitimately delete and even GC it. That is
3769 why we are extra careful not to futz with a window that
3770 is different from the one recorded when the system caret
3771 coordinates were last modified. That is also why we are
3772 careful not to move the IME window if the window
3773 described by W was deleted, as indicated by its buffer
3774 field being reset to nil. */
3775 f = x_window_to_frame (dpyinfo, hwnd);
3776 if (!(f && FRAME_LIVE_P (f)))
3777 goto dflt;
3778 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3779 /* Punt if someone changed the frame's selected window
3780 behind our back. */
3781 if (w != w32_system_caret_window)
3782 goto dflt;
3784 form.dwStyle = CFS_RECT;
3785 form.ptCurrentPos.x = w32_system_caret_x;
3786 form.ptCurrentPos.y = w32_system_caret_y;
3788 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3789 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3790 + w32_system_caret_hdr_height);
3791 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3792 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3793 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3794 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3795 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3796 - w32_system_caret_mode_height);
3798 /* Punt if the window was deleted behind our back. */
3799 if (!BUFFERP (w->contents))
3800 goto dflt;
3802 context = get_ime_context_fn (hwnd);
3804 if (!context)
3805 goto dflt;
3807 set_ime_composition_window_fn (context, &form);
3808 release_ime_context_fn (hwnd, context);
3810 /* We should "goto dflt" here to pass WM_IME_STARTCOMPOSITION to
3811 DefWindowProc, so that the composition window will actually
3812 be displayed. But doing so causes trouble with displaying
3813 dialog boxes, such as the file selection dialog or font
3814 selection dialog. So something else is needed to fix the
3815 former without breaking the latter. See bug#11732. */
3816 break;
3818 case WM_IME_ENDCOMPOSITION:
3819 ignore_ime_char = 0;
3820 goto dflt;
3822 /* Simulate middle mouse button events when left and right buttons
3823 are used together, but only if user has two button mouse. */
3824 case WM_LBUTTONDOWN:
3825 case WM_RBUTTONDOWN:
3826 if (w32_num_mouse_buttons > 2)
3827 goto handle_plain_button;
3830 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3831 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3833 if (button_state & this)
3834 return 0;
3836 if (button_state == 0)
3837 SetCapture (hwnd);
3839 button_state |= this;
3841 if (button_state & other)
3843 if (mouse_button_timer)
3845 KillTimer (hwnd, mouse_button_timer);
3846 mouse_button_timer = 0;
3848 /* Generate middle mouse event instead. */
3849 msg = WM_MBUTTONDOWN;
3850 button_state |= MMOUSE;
3852 else if (button_state & MMOUSE)
3854 /* Ignore button event if we've already generated a
3855 middle mouse down event. This happens if the
3856 user releases and press one of the two buttons
3857 after we've faked a middle mouse event. */
3858 return 0;
3860 else
3862 /* Flush out saved message. */
3863 post_msg (&saved_mouse_button_msg);
3865 wmsg.dwModifiers = w32_get_modifiers ();
3866 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3867 signal_user_input ();
3869 /* Clear message buffer. */
3870 saved_mouse_button_msg.msg.hwnd = 0;
3872 else
3874 /* Hold onto message for now. */
3875 mouse_button_timer =
3876 SetTimer (hwnd, MOUSE_BUTTON_ID,
3877 w32_mouse_button_tolerance, NULL);
3878 saved_mouse_button_msg.msg.hwnd = hwnd;
3879 saved_mouse_button_msg.msg.message = msg;
3880 saved_mouse_button_msg.msg.wParam = wParam;
3881 saved_mouse_button_msg.msg.lParam = lParam;
3882 saved_mouse_button_msg.msg.time = GetMessageTime ();
3883 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3886 return 0;
3888 case WM_LBUTTONUP:
3889 case WM_RBUTTONUP:
3890 if (w32_num_mouse_buttons > 2)
3891 goto handle_plain_button;
3894 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3895 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3897 if ((button_state & this) == 0)
3898 return 0;
3900 button_state &= ~this;
3902 if (button_state & MMOUSE)
3904 /* Only generate event when second button is released. */
3905 if ((button_state & other) == 0)
3907 msg = WM_MBUTTONUP;
3908 button_state &= ~MMOUSE;
3910 if (button_state) emacs_abort ();
3912 else
3913 return 0;
3915 else
3917 /* Flush out saved message if necessary. */
3918 if (saved_mouse_button_msg.msg.hwnd)
3920 post_msg (&saved_mouse_button_msg);
3923 wmsg.dwModifiers = w32_get_modifiers ();
3924 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3925 signal_user_input ();
3927 /* Always clear message buffer and cancel timer. */
3928 saved_mouse_button_msg.msg.hwnd = 0;
3929 KillTimer (hwnd, mouse_button_timer);
3930 mouse_button_timer = 0;
3932 if (button_state == 0)
3933 ReleaseCapture ();
3935 return 0;
3937 case WM_XBUTTONDOWN:
3938 case WM_XBUTTONUP:
3939 if (w32_pass_extra_mouse_buttons_to_system)
3940 goto dflt;
3941 /* else fall through and process them. */
3942 case WM_MBUTTONDOWN:
3943 case WM_MBUTTONUP:
3944 handle_plain_button:
3946 BOOL up;
3947 int button;
3949 /* Ignore middle and extra buttons as long as the menu is active. */
3950 f = x_window_to_frame (dpyinfo, hwnd);
3951 if (f && f->output_data.w32->menubar_active)
3952 return 0;
3954 if (parse_button (msg, HIWORD (wParam), &button, &up))
3956 if (up) ReleaseCapture ();
3957 else SetCapture (hwnd);
3958 button = (button == 0) ? LMOUSE :
3959 ((button == 1) ? MMOUSE : RMOUSE);
3960 if (up)
3961 button_state &= ~button;
3962 else
3963 button_state |= button;
3967 wmsg.dwModifiers = w32_get_modifiers ();
3968 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3969 signal_user_input ();
3971 /* Need to return true for XBUTTON messages, false for others,
3972 to indicate that we processed the message. */
3973 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3975 case WM_MOUSEMOVE:
3976 f = x_window_to_frame (dpyinfo, hwnd);
3977 if (f)
3979 /* Ignore mouse movements as long as the menu is active.
3980 These movements are processed by the window manager
3981 anyway, and it's wrong to handle them as if they happened
3982 on the underlying frame. */
3983 if (f->output_data.w32->menubar_active)
3984 return 0;
3986 /* If the mouse moved, and the mouse pointer is invisible,
3987 make it visible again. We do this here so as to be able
3988 to show the mouse pointer even when the main
3989 (a.k.a. "Lisp") thread is busy doing something. */
3990 static int last_x, last_y;
3991 int x = GET_X_LPARAM (lParam);
3992 int y = GET_Y_LPARAM (lParam);
3994 if (f->pointer_invisible
3995 && (x != last_x || y != last_y))
3996 f->pointer_invisible = false;
3998 last_x = x;
3999 last_y = y;
4002 /* If the mouse has just moved into the frame, start tracking
4003 it, so we will be notified when it leaves the frame. Mouse
4004 tracking only works under W98 and NT4 and later. On earlier
4005 versions, there is no way of telling when the mouse leaves the
4006 frame, so we just have to put up with help-echo and mouse
4007 highlighting remaining while the frame is not active. */
4008 if (track_mouse_event_fn && !track_mouse_window
4009 /* If the menu bar is active, turning on tracking of mouse
4010 movement events might send these events to the tooltip
4011 frame, if the user happens to move the mouse pointer over
4012 the tooltip. But since we don't process events for
4013 tooltip frames, this causes Windows to present a
4014 hourglass cursor, which is ugly and unexpected. So don't
4015 enable tracking mouse events in this case; they will be
4016 restarted when the menu pops down. (Confusingly, the
4017 menubar_active member of f->output_data.w32, tested
4018 above, is only set when a menu was popped up _not_ from
4019 the frame's menu bar, but via x-popup-menu.) */
4020 && !menubar_in_use)
4022 TRACKMOUSEEVENT tme;
4023 tme.cbSize = sizeof (tme);
4024 tme.dwFlags = TME_LEAVE;
4025 tme.hwndTrack = hwnd;
4026 tme.dwHoverTime = HOVER_DEFAULT;
4028 track_mouse_event_fn (&tme);
4029 track_mouse_window = hwnd;
4031 case WM_HSCROLL:
4032 case WM_VSCROLL:
4033 if (w32_mouse_move_interval <= 0
4034 || (msg == WM_MOUSEMOVE && button_state == 0))
4036 wmsg.dwModifiers = w32_get_modifiers ();
4037 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4038 return 0;
4041 /* Hang onto mouse move and scroll messages for a bit, to avoid
4042 sending such events to Emacs faster than it can process them.
4043 If we get more events before the timer from the first message
4044 expires, we just replace the first message. */
4046 if (saved_mouse_move_msg.msg.hwnd == 0)
4047 mouse_move_timer =
4048 SetTimer (hwnd, MOUSE_MOVE_ID,
4049 w32_mouse_move_interval, NULL);
4051 /* Hold onto message for now. */
4052 saved_mouse_move_msg.msg.hwnd = hwnd;
4053 saved_mouse_move_msg.msg.message = msg;
4054 saved_mouse_move_msg.msg.wParam = wParam;
4055 saved_mouse_move_msg.msg.lParam = lParam;
4056 saved_mouse_move_msg.msg.time = GetMessageTime ();
4057 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4059 return 0;
4061 case WM_MOUSEWHEEL:
4062 case WM_DROPFILES:
4063 wmsg.dwModifiers = w32_get_modifiers ();
4064 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4065 signal_user_input ();
4066 return 0;
4068 case WM_APPCOMMAND:
4069 if (w32_pass_multimedia_buttons_to_system)
4070 goto dflt;
4071 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
4072 case WM_MOUSEHWHEEL:
4073 wmsg.dwModifiers = w32_get_modifiers ();
4074 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4075 signal_user_input ();
4076 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
4077 handled, to prevent the system trying to handle it by faking
4078 scroll bar events. */
4079 return 1;
4081 case WM_TIMER:
4082 /* Flush out saved messages if necessary. */
4083 if (wParam == mouse_button_timer)
4085 if (saved_mouse_button_msg.msg.hwnd)
4087 post_msg (&saved_mouse_button_msg);
4088 signal_user_input ();
4089 saved_mouse_button_msg.msg.hwnd = 0;
4091 KillTimer (hwnd, mouse_button_timer);
4092 mouse_button_timer = 0;
4094 else if (wParam == mouse_move_timer)
4096 if (saved_mouse_move_msg.msg.hwnd)
4098 post_msg (&saved_mouse_move_msg);
4099 saved_mouse_move_msg.msg.hwnd = 0;
4101 KillTimer (hwnd, mouse_move_timer);
4102 mouse_move_timer = 0;
4104 else if (wParam == menu_free_timer)
4106 KillTimer (hwnd, menu_free_timer);
4107 menu_free_timer = 0;
4108 f = x_window_to_frame (dpyinfo, hwnd);
4109 /* If a popup menu is active, don't wipe its strings. */
4110 if (menubar_in_use
4111 && current_popup_menu == NULL)
4113 /* Free memory used by owner-drawn and help-echo strings. */
4114 w32_free_menu_strings (hwnd);
4115 if (f)
4116 f->output_data.w32->menubar_active = 0;
4117 menubar_in_use = 0;
4120 return 0;
4122 case WM_NCACTIVATE:
4123 /* Windows doesn't send us focus messages when putting up and
4124 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4125 The only indication we get that something happened is receiving
4126 this message afterwards. So this is a good time to reset our
4127 keyboard modifiers' state. */
4128 reset_modifiers ();
4129 goto dflt;
4131 case WM_INITMENU:
4132 button_state = 0;
4133 ReleaseCapture ();
4134 /* We must ensure menu bar is fully constructed and up to date
4135 before allowing user interaction with it. To achieve this
4136 we send this message to the lisp thread and wait for a
4137 reply (whose value is not actually needed) to indicate that
4138 the menu bar is now ready for use, so we can now return.
4140 To remain responsive in the meantime, we enter a nested message
4141 loop that can process all other messages.
4143 However, we skip all this if the message results from calling
4144 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4145 thread a message because it is blocked on us at this point. We
4146 set menubar_active before calling TrackPopupMenu to indicate
4147 this (there is no possibility of confusion with real menubar
4148 being active). */
4150 f = x_window_to_frame (dpyinfo, hwnd);
4151 if (f
4152 && (f->output_data.w32->menubar_active
4153 /* We can receive this message even in the absence of a
4154 menubar (ie. when the system menu is activated) - in this
4155 case we do NOT want to forward the message, otherwise it
4156 will cause the menubar to suddenly appear when the user
4157 had requested it to be turned off! */
4158 || f->output_data.w32->menubar_widget == NULL))
4159 return 0;
4162 deferred_msg msg_buf;
4164 /* Detect if message has already been deferred; in this case
4165 we cannot return any sensible value to ignore this. */
4166 if (find_deferred_msg (hwnd, msg) != NULL)
4167 emacs_abort ();
4169 menubar_in_use = 1;
4171 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4174 case WM_EXITMENULOOP:
4175 f = x_window_to_frame (dpyinfo, hwnd);
4177 /* If a menu is still active, check again after a short delay,
4178 since Windows often (always?) sends the WM_EXITMENULOOP
4179 before the corresponding WM_COMMAND message.
4180 Don't do this if a popup menu is active, since it is only
4181 menubar menus that require cleaning up in this way.
4183 if (f && menubar_in_use && current_popup_menu == NULL)
4184 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4186 /* If hourglass cursor should be displayed, display it now. */
4187 if (f && f->output_data.w32->hourglass_p)
4188 SetCursor (f->output_data.w32->hourglass_cursor);
4190 goto dflt;
4192 case WM_MENUSELECT:
4193 /* Direct handling of help_echo in menus. Should be safe now
4194 that we generate the help_echo by placing a help event in the
4195 keyboard buffer. */
4197 HMENU menu = (HMENU) lParam;
4198 UINT menu_item = (UINT) LOWORD (wParam);
4199 UINT flags = (UINT) HIWORD (wParam);
4201 w32_menu_display_help (hwnd, menu, menu_item, flags);
4203 return 0;
4205 case WM_MEASUREITEM:
4206 f = x_window_to_frame (dpyinfo, hwnd);
4207 if (f)
4209 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4211 if (pMis->CtlType == ODT_MENU)
4213 /* Work out dimensions for popup menu titles. */
4214 char * title = (char *) pMis->itemData;
4215 HDC hdc = GetDC (hwnd);
4216 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4217 LOGFONT menu_logfont;
4218 HFONT old_font;
4219 SIZE size;
4221 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4222 menu_logfont.lfWeight = FW_BOLD;
4223 menu_font = CreateFontIndirect (&menu_logfont);
4224 old_font = SelectObject (hdc, menu_font);
4226 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4227 if (title)
4229 if (unicode_append_menu)
4230 GetTextExtentPoint32W (hdc, (WCHAR *) title,
4231 wcslen ((WCHAR *) title),
4232 &size);
4233 else
4234 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4236 pMis->itemWidth = size.cx;
4237 if (pMis->itemHeight < size.cy)
4238 pMis->itemHeight = size.cy;
4240 else
4241 pMis->itemWidth = 0;
4243 SelectObject (hdc, old_font);
4244 DeleteObject (menu_font);
4245 ReleaseDC (hwnd, hdc);
4246 return TRUE;
4249 return 0;
4251 case WM_DRAWITEM:
4252 f = x_window_to_frame (dpyinfo, hwnd);
4253 if (f)
4255 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4257 if (pDis->CtlType == ODT_MENU)
4259 /* Draw popup menu title. */
4260 char * title = (char *) pDis->itemData;
4261 if (title)
4263 HDC hdc = pDis->hDC;
4264 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4265 LOGFONT menu_logfont;
4266 HFONT old_font;
4268 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4269 menu_logfont.lfWeight = FW_BOLD;
4270 menu_font = CreateFontIndirect (&menu_logfont);
4271 old_font = SelectObject (hdc, menu_font);
4273 /* Always draw title as if not selected. */
4274 if (unicode_append_menu)
4275 ExtTextOutW (hdc,
4276 pDis->rcItem.left
4277 + GetSystemMetrics (SM_CXMENUCHECK),
4278 pDis->rcItem.top,
4279 ETO_OPAQUE, &pDis->rcItem,
4280 (WCHAR *) title,
4281 wcslen ((WCHAR *) title), NULL);
4282 else
4283 ExtTextOut (hdc,
4284 pDis->rcItem.left
4285 + GetSystemMetrics (SM_CXMENUCHECK),
4286 pDis->rcItem.top,
4287 ETO_OPAQUE, &pDis->rcItem,
4288 title, strlen (title), NULL);
4290 SelectObject (hdc, old_font);
4291 DeleteObject (menu_font);
4293 return TRUE;
4296 return 0;
4298 #if 0
4299 /* Still not right - can't distinguish between clicks in the
4300 client area of the frame from clicks forwarded from the scroll
4301 bars - may have to hook WM_NCHITTEST to remember the mouse
4302 position and then check if it is in the client area ourselves. */
4303 case WM_MOUSEACTIVATE:
4304 /* Discard the mouse click that activates a frame, allowing the
4305 user to click anywhere without changing point (or worse!).
4306 Don't eat mouse clicks on scrollbars though!! */
4307 if (LOWORD (lParam) == HTCLIENT )
4308 return MA_ACTIVATEANDEAT;
4309 goto dflt;
4310 #endif
4312 case WM_MOUSELEAVE:
4313 /* No longer tracking mouse. */
4314 track_mouse_window = NULL;
4316 case WM_ACTIVATEAPP:
4317 case WM_ACTIVATE:
4318 case WM_WINDOWPOSCHANGED:
4319 case WM_SHOWWINDOW:
4320 /* Inform lisp thread that a frame might have just been obscured
4321 or exposed, so should recheck visibility of all frames. */
4322 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4323 goto dflt;
4325 case WM_SETFOCUS:
4326 dpyinfo->faked_key = 0;
4327 reset_modifiers ();
4328 register_hot_keys (hwnd);
4329 goto command;
4330 case WM_KILLFOCUS:
4331 unregister_hot_keys (hwnd);
4332 button_state = 0;
4333 ReleaseCapture ();
4334 /* Relinquish the system caret. */
4335 if (w32_system_caret_hwnd)
4337 w32_visible_system_caret_hwnd = NULL;
4338 w32_system_caret_hwnd = NULL;
4339 DestroyCaret ();
4341 goto command;
4342 case WM_COMMAND:
4343 menubar_in_use = 0;
4344 f = x_window_to_frame (dpyinfo, hwnd);
4345 if (f && HIWORD (wParam) == 0)
4347 if (menu_free_timer)
4349 KillTimer (hwnd, menu_free_timer);
4350 menu_free_timer = 0;
4353 case WM_MOVE:
4354 case WM_SIZE:
4355 command:
4356 wmsg.dwModifiers = w32_get_modifiers ();
4357 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4358 goto dflt;
4360 case WM_DESTROY:
4361 CoUninitialize ();
4362 return 0;
4364 case WM_CLOSE:
4365 wmsg.dwModifiers = w32_get_modifiers ();
4366 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4367 return 0;
4369 case WM_WINDOWPOSCHANGING:
4370 /* Don't restrict the sizing of any kind of frames. If the window
4371 manager doesn't, there's no reason to do it ourselves. */
4372 #if 0
4373 if (frame_resize_pixelwise || hwnd == tip_window)
4374 #endif
4375 return 0;
4377 #if 0
4378 /* Don't restrict the sizing of fullscreened frames, allowing them to be
4379 flush with the sides of the screen. */
4380 f = x_window_to_frame (dpyinfo, hwnd);
4381 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
4382 return 0;
4385 WINDOWPLACEMENT wp;
4386 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
4388 wp.length = sizeof (WINDOWPLACEMENT);
4389 GetWindowPlacement (hwnd, &wp);
4391 if (wp.showCmd != SW_SHOWMAXIMIZED && wp.showCmd != SW_SHOWMINIMIZED
4392 && (lppos->flags & SWP_NOSIZE) == 0)
4394 RECT rect;
4395 int wdiff;
4396 int hdiff;
4397 DWORD font_width;
4398 DWORD line_height;
4399 DWORD internal_border;
4400 DWORD vscrollbar_extra;
4401 DWORD hscrollbar_extra;
4402 RECT wr;
4404 wp.length = sizeof (wp);
4405 GetWindowRect (hwnd, &wr);
4407 enter_crit ();
4409 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
4410 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
4411 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
4412 vscrollbar_extra = GetWindowLong (hwnd, WND_VSCROLLBAR_INDEX);
4413 hscrollbar_extra = GetWindowLong (hwnd, WND_HSCROLLBAR_INDEX);
4415 leave_crit ();
4417 memset (&rect, 0, sizeof (rect));
4418 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
4419 GetMenu (hwnd) != NULL);
4421 /* Force width and height of client area to be exact
4422 multiples of the character cell dimensions. */
4423 wdiff = (lppos->cx - (rect.right - rect.left)
4424 - 2 * internal_border - vscrollbar_extra)
4425 % font_width;
4426 hdiff = (lppos->cy - (rect.bottom - rect.top)
4427 - 2 * internal_border - hscrollbar_extra)
4428 % line_height;
4430 if (wdiff || hdiff)
4432 /* For right/bottom sizing we can just fix the sizes.
4433 However for top/left sizing we will need to fix the X
4434 and Y positions as well. */
4436 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
4437 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
4439 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
4440 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
4442 if (wp.showCmd != SW_SHOWMAXIMIZED
4443 && (lppos->flags & SWP_NOMOVE) == 0)
4445 if (lppos->x != wr.left || lppos->y != wr.top)
4447 lppos->x += wdiff;
4448 lppos->y += hdiff;
4450 else
4452 lppos->flags |= SWP_NOMOVE;
4456 return 0;
4461 goto dflt;
4462 #endif
4464 case WM_GETMINMAXINFO:
4465 /* Hack to allow resizing the Emacs frame above the screen size.
4466 Note that Windows 9x limits coordinates to 16-bits. */
4467 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
4468 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
4469 return 0;
4471 case WM_SETCURSOR:
4472 if (LOWORD (lParam) == HTCLIENT)
4474 f = x_window_to_frame (dpyinfo, hwnd);
4475 if (f)
4477 if (f->output_data.w32->hourglass_p
4478 && !menubar_in_use && !current_popup_menu)
4479 SetCursor (f->output_data.w32->hourglass_cursor);
4480 else if (f->pointer_invisible)
4481 SetCursor (NULL);
4482 else
4483 SetCursor (f->output_data.w32->current_cursor);
4486 return 0;
4488 goto dflt;
4490 case WM_EMACS_SETCURSOR:
4492 Cursor cursor = (Cursor) wParam;
4493 f = x_window_to_frame (dpyinfo, hwnd);
4494 if (f && cursor)
4496 f->output_data.w32->current_cursor = cursor;
4497 /* Don't change the cursor while menu-bar menu is in use. */
4498 if (!f->output_data.w32->menubar_active
4499 && !f->output_data.w32->hourglass_p)
4501 if (f->pointer_invisible)
4502 SetCursor (NULL);
4503 else
4504 SetCursor (cursor);
4507 return 0;
4510 case WM_EMACS_SHOWCURSOR:
4512 ShowCursor ((BOOL) wParam);
4514 return 0;
4517 case WM_EMACS_CREATEVSCROLLBAR:
4518 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
4519 (struct scroll_bar *) lParam);
4521 case WM_EMACS_CREATEHSCROLLBAR:
4522 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
4523 (struct scroll_bar *) lParam);
4525 case WM_EMACS_SHOWWINDOW:
4526 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4528 case WM_EMACS_BRINGTOTOP:
4529 case WM_EMACS_SETFOREGROUND:
4531 HWND foreground_window;
4532 DWORD foreground_thread, retval;
4534 /* On NT 5.0, and apparently Windows 98, it is necessary to
4535 attach to the thread that currently has focus in order to
4536 pull the focus away from it. */
4537 foreground_window = GetForegroundWindow ();
4538 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4539 if (!foreground_window
4540 || foreground_thread == GetCurrentThreadId ()
4541 || !AttachThreadInput (GetCurrentThreadId (),
4542 foreground_thread, TRUE))
4543 foreground_thread = 0;
4545 retval = SetForegroundWindow ((HWND) wParam);
4546 if (msg == WM_EMACS_BRINGTOTOP)
4547 retval = BringWindowToTop ((HWND) wParam);
4549 /* Detach from the previous foreground thread. */
4550 if (foreground_thread)
4551 AttachThreadInput (GetCurrentThreadId (),
4552 foreground_thread, FALSE);
4554 return retval;
4557 case WM_EMACS_SETWINDOWPOS:
4559 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4560 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4561 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4564 case WM_EMACS_DESTROYWINDOW:
4565 DragAcceptFiles ((HWND) wParam, FALSE);
4566 return DestroyWindow ((HWND) wParam);
4568 case WM_EMACS_HIDE_CARET:
4569 return HideCaret (hwnd);
4571 case WM_EMACS_SHOW_CARET:
4572 return ShowCaret (hwnd);
4574 case WM_EMACS_DESTROY_CARET:
4575 w32_system_caret_hwnd = NULL;
4576 w32_visible_system_caret_hwnd = NULL;
4577 return DestroyCaret ();
4579 case WM_EMACS_TRACK_CARET:
4580 /* If there is currently no system caret, create one. */
4581 if (w32_system_caret_hwnd == NULL)
4583 /* Use the default caret width, and avoid changing it
4584 unnecessarily, as it confuses screen reader software. */
4585 w32_system_caret_hwnd = hwnd;
4586 CreateCaret (hwnd, NULL, 0,
4587 w32_system_caret_height);
4590 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4591 return 0;
4592 /* Ensure visible caret gets turned on when requested. */
4593 else if (w32_use_visible_system_caret
4594 && w32_visible_system_caret_hwnd != hwnd)
4596 w32_visible_system_caret_hwnd = hwnd;
4597 return ShowCaret (hwnd);
4599 /* Ensure visible caret gets turned off when requested. */
4600 else if (!w32_use_visible_system_caret
4601 && w32_visible_system_caret_hwnd)
4603 w32_visible_system_caret_hwnd = NULL;
4604 return HideCaret (hwnd);
4606 else
4607 return 1;
4609 case WM_EMACS_TRACKPOPUPMENU:
4611 UINT flags;
4612 POINT *pos;
4613 int retval;
4614 pos = (POINT *)lParam;
4615 flags = TPM_CENTERALIGN;
4616 if (button_state & LMOUSE)
4617 flags |= TPM_LEFTBUTTON;
4618 else if (button_state & RMOUSE)
4619 flags |= TPM_RIGHTBUTTON;
4621 /* Remember we did a SetCapture on the initial mouse down event,
4622 so for safety, we make sure the capture is canceled now. */
4623 ReleaseCapture ();
4624 button_state = 0;
4626 /* Use menubar_active to indicate that WM_INITMENU is from
4627 TrackPopupMenu below, and should be ignored. */
4628 f = x_window_to_frame (dpyinfo, hwnd);
4629 if (f)
4630 f->output_data.w32->menubar_active = 1;
4632 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4633 0, hwnd, NULL))
4635 MSG amsg;
4636 /* Eat any mouse messages during popupmenu */
4637 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4638 PM_REMOVE));
4639 /* Get the menu selection, if any */
4640 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4642 retval = LOWORD (amsg.wParam);
4644 else
4646 retval = 0;
4649 else
4651 retval = -1;
4654 return retval;
4656 case WM_EMACS_FILENOTIFY:
4657 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4658 return 1;
4660 default:
4661 /* Check for messages registered at runtime. */
4662 if (msg == msh_mousewheel)
4664 wmsg.dwModifiers = w32_get_modifiers ();
4665 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4666 signal_user_input ();
4667 return 0;
4670 dflt:
4671 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4674 /* The most common default return code for handled messages is 0. */
4675 return 0;
4678 static void
4679 my_create_window (struct frame * f)
4681 MSG msg;
4682 static int coords[2];
4683 Lisp_Object left, top;
4684 struct w32_display_info *dpyinfo = &one_w32_display_info;
4686 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
4687 anything that is not a number and is not Qunbound. */
4688 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
4689 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
4690 if (EQ (left, Qunbound))
4691 coords[0] = CW_USEDEFAULT;
4692 else
4693 coords[0] = XINT (left);
4694 if (EQ (top, Qunbound))
4695 coords[1] = CW_USEDEFAULT;
4696 else
4697 coords[1] = XINT (top);
4699 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
4700 (WPARAM)f, (LPARAM)coords))
4701 emacs_abort ();
4702 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4706 /* Create a tooltip window. Unlike my_create_window, we do not do this
4707 indirectly via the Window thread, as we do not need to process Window
4708 messages for the tooltip. Creating tooltips indirectly also creates
4709 deadlocks when tooltips are created for menu items. */
4710 static void
4711 my_create_tip_window (struct frame *f)
4713 RECT rect;
4715 rect.left = rect.top = 0;
4716 rect.right = FRAME_PIXEL_WIDTH (f);
4717 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4719 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4720 FRAME_EXTERNAL_MENU_BAR (f));
4722 tip_window = FRAME_W32_WINDOW (f)
4723 = CreateWindow (EMACS_CLASS,
4724 f->namebuf,
4725 f->output_data.w32->dwStyle,
4726 f->left_pos,
4727 f->top_pos,
4728 rect.right - rect.left,
4729 rect.bottom - rect.top,
4730 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4731 NULL,
4732 hinst,
4733 NULL);
4735 if (tip_window)
4737 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4738 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4739 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4740 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4742 /* Tip frames have no scrollbars. */
4743 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
4744 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
4746 /* Do this to discard the default setting specified by our parent. */
4747 ShowWindow (tip_window, SW_HIDE);
4752 /* Create and set up the w32 window for frame F. */
4754 static void
4755 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
4757 block_input ();
4759 /* Use the resource name as the top-level window name
4760 for looking up resources. Make a non-Lisp copy
4761 for the window manager, so GC relocation won't bother it.
4763 Elsewhere we specify the window name for the window manager. */
4764 f->namebuf = xlispstrdup (Vx_resource_name);
4766 my_create_window (f);
4768 validate_x_resource_name ();
4770 /* x_set_name normally ignores requests to set the name if the
4771 requested name is the same as the current name. This is the one
4772 place where that assumption isn't correct; f->name is set, but
4773 the server hasn't been told. */
4775 Lisp_Object name;
4776 int explicit = f->explicit_name;
4778 f->explicit_name = 0;
4779 name = f->name;
4780 fset_name (f, Qnil);
4781 x_set_name (f, name, explicit);
4784 unblock_input ();
4786 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4787 initialize_frame_menubar (f);
4789 if (FRAME_W32_WINDOW (f) == 0)
4790 error ("Unable to create window");
4793 /* Handle the icon stuff for this window. Perhaps later we might
4794 want an x_set_icon_position which can be called interactively as
4795 well. */
4797 static void
4798 x_icon (struct frame *f, Lisp_Object parms)
4800 Lisp_Object icon_x, icon_y;
4801 struct w32_display_info *dpyinfo = &one_w32_display_info;
4803 /* Set the position of the icon. Note that Windows 95 groups all
4804 icons in the tray. */
4805 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4806 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4807 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4809 CHECK_NUMBER (icon_x);
4810 CHECK_NUMBER (icon_y);
4812 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4813 error ("Both left and top icon corners of icon must be specified");
4815 block_input ();
4817 #if 0 /* TODO */
4818 /* Start up iconic or window? */
4819 x_wm_set_window_state
4820 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4821 ? IconicState
4822 : NormalState));
4824 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4825 ? f->icon_name
4826 : f->name)));
4827 #endif
4829 unblock_input ();
4833 static void
4834 x_make_gc (struct frame *f)
4836 XGCValues gc_values;
4838 block_input ();
4840 /* Create the GC's of this frame.
4841 Note that many default values are used. */
4843 /* Normal video */
4844 gc_values.font = FRAME_FONT (f);
4846 /* Cursor has cursor-color background, background-color foreground. */
4847 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4848 gc_values.background = f->output_data.w32->cursor_pixel;
4849 f->output_data.w32->cursor_gc
4850 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4851 (GCFont | GCForeground | GCBackground),
4852 &gc_values);
4854 /* Reliefs. */
4855 f->output_data.w32->white_relief.gc = 0;
4856 f->output_data.w32->black_relief.gc = 0;
4858 unblock_input ();
4862 /* Handler for signals raised during x_create_frame and
4863 x_create_tip_frame. FRAME is the frame which is partially
4864 constructed. */
4866 static Lisp_Object
4867 unwind_create_frame (Lisp_Object frame)
4869 struct frame *f = XFRAME (frame);
4871 /* If frame is ``official'', nothing to do. */
4872 if (NILP (Fmemq (frame, Vframe_list)))
4874 #ifdef GLYPH_DEBUG
4875 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4877 /* If the frame's image cache refcount is still the same as our
4878 private shadow variable, it means we are unwinding a frame
4879 for which we didn't yet call init_frame_faces, where the
4880 refcount is incremented. Therefore, we increment it here, so
4881 that free_frame_faces, called in x_free_frame_resources
4882 below, will not mistakenly decrement the counter that was not
4883 incremented yet to account for this new frame. */
4884 if (FRAME_IMAGE_CACHE (f) != NULL
4885 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
4886 FRAME_IMAGE_CACHE (f)->refcount++;
4887 #endif
4889 x_free_frame_resources (f);
4890 free_glyphs (f);
4892 #ifdef GLYPH_DEBUG
4893 /* Check that reference counts are indeed correct. */
4894 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4895 eassert ((dpyinfo->terminal->image_cache == NULL
4896 && image_cache_refcount == 0)
4897 || (dpyinfo->terminal->image_cache != NULL
4898 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
4899 #endif
4900 return Qt;
4903 return Qnil;
4906 static void
4907 do_unwind_create_frame (Lisp_Object frame)
4909 unwind_create_frame (frame);
4912 static void
4913 unwind_create_frame_1 (Lisp_Object val)
4915 inhibit_lisp_code = val;
4918 static void
4919 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4921 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4922 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4923 RES_TYPE_STRING);
4924 Lisp_Object font;
4925 if (EQ (font_param, Qunbound))
4926 font_param = Qnil;
4927 font = !NILP (font_param) ? font_param
4928 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4930 if (!STRINGP (font))
4932 int i;
4933 static char *names[]
4934 = { "Courier New-10",
4935 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4936 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4937 "Fixedsys",
4938 NULL };
4940 for (i = 0; names[i]; i++)
4942 font = font_open_by_name (f, build_unibyte_string (names[i]));
4943 if (! NILP (font))
4944 break;
4946 if (NILP (font))
4947 error ("No suitable font was found");
4949 else if (!NILP (font_param))
4951 /* Remember the explicit font parameter, so we can re-apply it after
4952 we've applied the `default' face settings. */
4953 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4955 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4958 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4959 1, 1, 0,
4960 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4961 Return an Emacs frame object.
4962 PARAMETERS is an alist of frame parameters.
4963 If the parameters specify that the frame should not have a minibuffer,
4964 and do not specify a specific minibuffer window to use,
4965 then `default-minibuffer-frame' must be a frame whose minibuffer can
4966 be shared by the new frame.
4968 This function is an internal primitive--use `make-frame' instead. */)
4969 (Lisp_Object parameters)
4971 struct frame *f;
4972 Lisp_Object frame, tem;
4973 Lisp_Object name;
4974 bool minibuffer_only = false;
4975 long window_prompting = 0;
4976 ptrdiff_t count = SPECPDL_INDEX ();
4977 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4978 Lisp_Object display;
4979 struct w32_display_info *dpyinfo = NULL;
4980 Lisp_Object parent;
4981 struct kboard *kb;
4983 if (!FRAME_W32_P (SELECTED_FRAME ())
4984 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4985 error ("Cannot create a GUI frame in a -nw session");
4987 /* Make copy of frame parameters because the original is in pure
4988 storage now. */
4989 parameters = Fcopy_alist (parameters);
4991 /* Use this general default value to start with
4992 until we know if this frame has a specified name. */
4993 Vx_resource_name = Vinvocation_name;
4995 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4996 if (EQ (display, Qunbound))
4997 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4998 if (EQ (display, Qunbound))
4999 display = Qnil;
5000 dpyinfo = check_x_display_info (display);
5001 kb = dpyinfo->terminal->kboard;
5003 if (!dpyinfo->terminal->name)
5004 error ("Terminal is not live, can't create new frames on it");
5006 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5007 if (!STRINGP (name)
5008 && ! EQ (name, Qunbound)
5009 && ! NILP (name))
5010 error ("Invalid frame name--not a string or nil");
5012 if (STRINGP (name))
5013 Vx_resource_name = name;
5015 /* See if parent window is specified. */
5016 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5017 if (EQ (parent, Qunbound))
5018 parent = Qnil;
5019 if (! NILP (parent))
5020 CHECK_NUMBER (parent);
5022 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5023 /* No need to protect DISPLAY because that's not used after passing
5024 it to make_frame_without_minibuffer. */
5025 frame = Qnil;
5026 GCPRO4 (parameters, parent, name, frame);
5027 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5028 RES_TYPE_SYMBOL);
5029 if (EQ (tem, Qnone) || NILP (tem))
5030 f = make_frame_without_minibuffer (Qnil, kb, display);
5031 else if (EQ (tem, Qonly))
5033 f = make_minibuffer_frame ();
5034 minibuffer_only = true;
5036 else if (WINDOWP (tem))
5037 f = make_frame_without_minibuffer (tem, kb, display);
5038 else
5039 f = make_frame (true);
5041 XSETFRAME (frame, f);
5043 /* By default, make scrollbars the system standard width and height. */
5044 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5045 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5047 f->terminal = dpyinfo->terminal;
5049 f->output_method = output_w32;
5050 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5051 FRAME_FONTSET (f) = -1;
5053 fset_icon_name
5054 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5055 RES_TYPE_STRING));
5056 if (! STRINGP (f->icon_name))
5057 fset_icon_name (f, Qnil);
5059 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5061 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5062 record_unwind_protect (do_unwind_create_frame, frame);
5064 #ifdef GLYPH_DEBUG
5065 image_cache_refcount =
5066 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5067 dpyinfo_refcount = dpyinfo->reference_count;
5068 #endif /* GLYPH_DEBUG */
5070 /* Specify the parent under which to make this window. */
5071 if (!NILP (parent))
5073 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5074 pointer from integer of different size. */
5075 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5076 f->output_data.w32->explicit_parent = true;
5078 else
5080 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5081 f->output_data.w32->explicit_parent = false;
5084 /* Set the name; the functions to which we pass f expect the name to
5085 be set. */
5086 if (EQ (name, Qunbound) || NILP (name))
5088 fset_name (f, build_string (dpyinfo->w32_id_name));
5089 f->explicit_name = false;
5091 else
5093 fset_name (f, name);
5094 f->explicit_name = true;
5095 /* Use the frame's title when getting resources for this frame. */
5096 specbind (Qx_resource_name, name);
5099 if (uniscribe_available)
5100 register_font_driver (&uniscribe_font_driver, f);
5101 register_font_driver (&w32font_driver, f);
5103 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5104 "fontBackend", "FontBackend", RES_TYPE_STRING);
5106 /* Extract the window parameters from the supplied values
5107 that are needed to determine window geometry. */
5108 x_default_font_parameter (f, parameters);
5110 x_default_parameter (f, parameters, Qborder_width, make_number (2),
5111 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5113 /* We recognize either internalBorderWidth or internalBorder
5114 (which is what xterm calls it). */
5115 if (NILP (Fassq (Qinternal_border_width, parameters)))
5117 Lisp_Object value;
5119 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5120 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5121 if (! EQ (value, Qunbound))
5122 parameters = Fcons (Fcons (Qinternal_border_width, value),
5123 parameters);
5125 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5126 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5127 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5128 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5129 NULL, NULL, RES_TYPE_NUMBER);
5130 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5131 NULL, NULL, RES_TYPE_NUMBER);
5132 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5133 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5134 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5135 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5137 /* Also do the stuff which must be set before the window exists. */
5138 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5139 "foreground", "Foreground", RES_TYPE_STRING);
5140 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5141 "background", "Background", RES_TYPE_STRING);
5142 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5143 "pointerColor", "Foreground", RES_TYPE_STRING);
5144 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5145 "borderColor", "BorderColor", RES_TYPE_STRING);
5146 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5147 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5148 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5149 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5150 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5151 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5152 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5153 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5154 /* Process alpha here (Bug#16619). */
5155 x_default_parameter (f, parameters, Qalpha, Qnil,
5156 "alpha", "Alpha", RES_TYPE_NUMBER);
5158 /* Init faces first since we need the frame's column width/line
5159 height in various occasions. */
5160 init_frame_faces (f);
5162 /* The following call of change_frame_size is needed since otherwise
5163 x_set_tool_bar_lines will already work with the character sizes
5164 installed by init_frame_faces while the frame's pixel size is
5165 still calculated from a character size of 1 and we subsequently
5166 hit the (height >= 0) assertion in window_box_height.
5168 The non-pixelwise code apparently worked around this because it
5169 had one frame line vs one toolbar line which left us with a zero
5170 root window height which was obviously wrong as well ... */
5171 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5172 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5173 Qx_create_frame_1);
5175 /* The X resources controlling the menu-bar and tool-bar are
5176 processed specially at startup, and reflected in the mode
5177 variables; ignore them here. */
5178 x_default_parameter (f, parameters, Qmenu_bar_lines,
5179 NILP (Vmenu_bar_mode)
5180 ? make_number (0) : make_number (1),
5181 NULL, NULL, RES_TYPE_NUMBER);
5182 x_default_parameter (f, parameters, Qtool_bar_lines,
5183 NILP (Vtool_bar_mode)
5184 ? make_number (0) : make_number (1),
5185 NULL, NULL, RES_TYPE_NUMBER);
5187 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5188 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5189 x_default_parameter (f, parameters, Qtitle, Qnil,
5190 "title", "Title", RES_TYPE_STRING);
5192 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5193 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5195 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5196 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5197 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5198 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5199 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5200 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5201 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5203 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5205 window_prompting = x_figure_window_size (f, parameters, true);
5207 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5208 f->no_split = minibuffer_only || EQ (tem, Qt);
5210 w32_window (f, window_prompting, minibuffer_only);
5211 x_icon (f, parameters);
5213 x_make_gc (f);
5215 /* Now consider the frame official. */
5216 f->terminal->reference_count++;
5217 FRAME_DISPLAY_INFO (f)->reference_count++;
5218 Vframe_list = Fcons (frame, Vframe_list);
5220 /* We need to do this after creating the window, so that the
5221 icon-creation functions can say whose icon they're describing. */
5222 x_default_parameter (f, parameters, Qicon_type, Qnil,
5223 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5225 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5226 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5227 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5228 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5229 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5230 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5231 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5232 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5233 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
5234 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
5236 /* Allow x_set_window_size, now. */
5237 f->can_x_set_window_size = true;
5239 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
5240 Qx_create_frame_2);
5242 /* Tell the server what size and position, etc, we want, and how
5243 badly we want them. This should be done after we have the menu
5244 bar so that its size can be taken into account. */
5245 block_input ();
5246 x_wm_set_size_hint (f, window_prompting, false);
5247 unblock_input ();
5249 /* Process fullscreen parameter here in the hope that normalizing a
5250 fullheight/fullwidth frame will produce the size set by the last
5251 adjust_frame_size call. */
5252 x_default_parameter (f, parameters, Qfullscreen, Qnil,
5253 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5255 /* Make the window appear on the frame and enable display, unless
5256 the caller says not to. However, with explicit parent, Emacs
5257 cannot control visibility, so don't try. */
5258 if (! f->output_data.w32->explicit_parent)
5260 Lisp_Object visibility;
5262 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5263 if (EQ (visibility, Qunbound))
5264 visibility = Qt;
5266 if (EQ (visibility, Qicon))
5267 x_iconify_frame (f);
5268 else if (! NILP (visibility))
5269 x_make_frame_visible (f);
5270 else
5271 /* Must have been Qnil. */
5275 /* Initialize `default-minibuffer-frame' in case this is the first
5276 frame on this terminal. */
5277 if (FRAME_HAS_MINIBUF_P (f)
5278 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
5279 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
5280 kset_default_minibuffer_frame (kb, frame);
5282 /* All remaining specified parameters, which have not been "used"
5283 by x_get_arg and friends, now go in the misc. alist of the frame. */
5284 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
5285 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
5286 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
5288 UNGCPRO;
5290 /* Make sure windows on this frame appear in calls to next-window
5291 and similar functions. */
5292 Vwindow_list = Qnil;
5294 return unbind_to (count, frame);
5297 /* FRAME is used only to get a handle on the X display. We don't pass the
5298 display info directly because we're called from frame.c, which doesn't
5299 know about that structure. */
5300 Lisp_Object
5301 x_get_focus_frame (struct frame *frame)
5303 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
5304 Lisp_Object xfocus;
5305 if (! dpyinfo->w32_focus_frame)
5306 return Qnil;
5308 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5309 return xfocus;
5312 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
5313 doc: /* Internal function called by `color-defined-p', which see.
5314 \(Note that the Nextstep version of this function ignores FRAME.) */)
5315 (Lisp_Object color, Lisp_Object frame)
5317 XColor foo;
5318 struct frame *f = decode_window_system_frame (frame);
5320 CHECK_STRING (color);
5322 if (w32_defined_color (f, SDATA (color), &foo, false))
5323 return Qt;
5324 else
5325 return Qnil;
5328 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
5329 doc: /* Internal function called by `color-values', which see. */)
5330 (Lisp_Object color, Lisp_Object frame)
5332 XColor foo;
5333 struct frame *f = decode_window_system_frame (frame);
5335 CHECK_STRING (color);
5337 if (w32_defined_color (f, SDATA (color), &foo, false))
5338 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
5339 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
5340 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
5341 else
5342 return Qnil;
5345 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
5346 doc: /* Internal function called by `display-color-p', which see. */)
5347 (Lisp_Object display)
5349 struct w32_display_info *dpyinfo = check_x_display_info (display);
5351 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
5352 return Qnil;
5354 return Qt;
5357 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
5358 Sx_display_grayscale_p, 0, 1, 0,
5359 doc: /* Return t if DISPLAY supports shades of gray.
5360 Note that color displays do support shades of gray.
5361 The optional argument DISPLAY specifies which display to ask about.
5362 DISPLAY should be either a frame or a display name (a string).
5363 If omitted or nil, that stands for the selected frame's display. */)
5364 (Lisp_Object display)
5366 struct w32_display_info *dpyinfo = check_x_display_info (display);
5368 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
5369 return Qnil;
5371 return Qt;
5374 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
5375 Sx_display_pixel_width, 0, 1, 0,
5376 doc: /* Return the width in pixels of DISPLAY.
5377 The optional argument DISPLAY specifies which display to ask about.
5378 DISPLAY should be either a frame or a display name (a string).
5379 If omitted or nil, that stands for the selected frame's display.
5381 On \"multi-monitor\" setups this refers to the pixel width for all
5382 physical monitors associated with DISPLAY. To get information for
5383 each physical monitor, use `display-monitor-attributes-list'. */)
5384 (Lisp_Object display)
5386 struct w32_display_info *dpyinfo = check_x_display_info (display);
5388 return make_number (x_display_pixel_width (dpyinfo));
5391 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
5392 Sx_display_pixel_height, 0, 1, 0,
5393 doc: /* Return the height in pixels of DISPLAY.
5394 The optional argument DISPLAY specifies which display to ask about.
5395 DISPLAY should be either a frame or a display name (a string).
5396 If omitted or nil, that stands for the selected frame's display.
5398 On \"multi-monitor\" setups this refers to the pixel height for all
5399 physical monitors associated with DISPLAY. To get information for
5400 each physical monitor, use `display-monitor-attributes-list'. */)
5401 (Lisp_Object display)
5403 struct w32_display_info *dpyinfo = check_x_display_info (display);
5405 return make_number (x_display_pixel_height (dpyinfo));
5408 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
5409 0, 1, 0,
5410 doc: /* Return the number of bitplanes of DISPLAY.
5411 The optional argument DISPLAY specifies which display to ask about.
5412 DISPLAY should be either a frame or a display name (a string).
5413 If omitted or nil, that stands for the selected frame's display. */)
5414 (Lisp_Object display)
5416 struct w32_display_info *dpyinfo = check_x_display_info (display);
5418 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
5421 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
5422 0, 1, 0,
5423 doc: /* Return the number of color cells of DISPLAY.
5424 The optional argument DISPLAY specifies which display to ask about.
5425 DISPLAY should be either a frame or a display name (a string).
5426 If omitted or nil, that stands for the selected frame's display. */)
5427 (Lisp_Object display)
5429 struct w32_display_info *dpyinfo = check_x_display_info (display);
5430 int cap;
5432 /* Don't use NCOLORS: it returns incorrect results under remote
5433 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
5434 * overflow and because probably is more meaningful on Windows
5435 * anyway. */
5437 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
5438 return make_number (cap);
5441 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
5442 Sx_server_max_request_size,
5443 0, 1, 0,
5444 doc: /* Return the maximum request size of the server of DISPLAY.
5445 The optional argument DISPLAY specifies which display to ask about.
5446 DISPLAY should be either a frame or a display name (a string).
5447 If omitted or nil, that stands for the selected frame's display. */)
5448 (Lisp_Object display)
5450 return make_number (1);
5453 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
5454 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
5456 \(Labeling every distributor as a "vendor" embodies the false assumption
5457 that operating systems cannot be developed and distributed noncommercially.)
5459 For GNU and Unix systems, this queries the X server software; for
5460 MS-Windows, this queries the OS.
5462 The optional argument TERMINAL specifies which display to ask about.
5463 TERMINAL should be a terminal object, a frame or a display name (a string).
5464 If omitted or nil, that stands for the selected frame's display. */)
5465 (Lisp_Object terminal)
5467 return build_string ("Microsoft Corp.");
5470 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
5471 doc: /* Return the version numbers of the GUI software on TERMINAL.
5472 The value is a list of three integers specifying the version of the GUI
5473 software in use.
5475 For GNU and Unix system, the first 2 numbers are the version of the X
5476 Protocol used on TERMINAL and the 3rd number is the distributor-specific
5477 release number. For MS-Windows, the 3 numbers report the version and
5478 the build number of the OS.
5480 See also the function `x-server-vendor'.
5482 The optional argument TERMINAL specifies which display to ask about.
5483 TERMINAL should be a terminal object, a frame or a display name (a string).
5484 If omitted or nil, that stands for the selected frame's display. */)
5485 (Lisp_Object terminal)
5487 return list3i (w32_major_version, w32_minor_version, w32_build_number);
5490 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
5491 doc: /* Return the number of screens on the server of DISPLAY.
5492 The optional argument DISPLAY specifies which display to ask about.
5493 DISPLAY should be either a frame or a display name (a string).
5494 If omitted or nil, that stands for the selected frame's display. */)
5495 (Lisp_Object display)
5497 return make_number (1);
5500 DEFUN ("x-display-mm-height", Fx_display_mm_height,
5501 Sx_display_mm_height, 0, 1, 0,
5502 doc: /* Return the height in millimeters of DISPLAY.
5503 The optional argument DISPLAY specifies which display to ask about.
5504 DISPLAY should be either a frame or a display name (a string).
5505 If omitted or nil, that stands for the selected frame's display.
5507 On \"multi-monitor\" setups this refers to the height in millimeters for
5508 all physical monitors associated with DISPLAY. To get information
5509 for each physical monitor, use `display-monitor-attributes-list'. */)
5510 (Lisp_Object display)
5512 struct w32_display_info *dpyinfo = check_x_display_info (display);
5513 HDC hdc;
5514 double mm_per_pixel;
5516 hdc = GetDC (NULL);
5517 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5518 / GetDeviceCaps (hdc, VERTRES));
5519 ReleaseDC (NULL, hdc);
5521 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5524 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5525 doc: /* Return the width in millimeters of DISPLAY.
5526 The optional argument DISPLAY specifies which display to ask about.
5527 DISPLAY should be either a frame or a display name (a string).
5528 If omitted or nil, that stands for the selected frame's display.
5530 On \"multi-monitor\" setups this refers to the width in millimeters for
5531 all physical monitors associated with TERMINAL. To get information
5532 for each physical monitor, use `display-monitor-attributes-list'. */)
5533 (Lisp_Object display)
5535 struct w32_display_info *dpyinfo = check_x_display_info (display);
5536 HDC hdc;
5537 double mm_per_pixel;
5539 hdc = GetDC (NULL);
5540 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5541 / GetDeviceCaps (hdc, HORZRES));
5542 ReleaseDC (NULL, hdc);
5544 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5547 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5548 Sx_display_backing_store, 0, 1, 0,
5549 doc: /* Return an indication of whether DISPLAY does backing store.
5550 The value may be `always', `when-mapped', or `not-useful'.
5551 The optional argument DISPLAY specifies which display to ask about.
5552 DISPLAY should be either a frame or a display name (a string).
5553 If omitted or nil, that stands for the selected frame's display. */)
5554 (Lisp_Object display)
5556 return intern ("not-useful");
5559 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5560 Sx_display_visual_class, 0, 1, 0,
5561 doc: /* Return the visual class of DISPLAY.
5562 The value is one of the symbols `static-gray', `gray-scale',
5563 `static-color', `pseudo-color', `true-color', or `direct-color'.
5565 The optional argument DISPLAY specifies which display to ask about.
5566 DISPLAY should be either a frame or a display name (a string).
5567 If omitted or nil, that stands for the selected frame's display. */)
5568 (Lisp_Object display)
5570 struct w32_display_info *dpyinfo = check_x_display_info (display);
5571 Lisp_Object result = Qnil;
5573 if (dpyinfo->has_palette)
5574 result = intern ("pseudo-color");
5575 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5576 result = intern ("static-grey");
5577 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5578 result = intern ("static-color");
5579 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5580 result = intern ("true-color");
5582 return result;
5585 DEFUN ("x-display-save-under", Fx_display_save_under,
5586 Sx_display_save_under, 0, 1, 0,
5587 doc: /* Return t if DISPLAY supports the save-under feature.
5588 The optional argument DISPLAY specifies which display to ask about.
5589 DISPLAY should be either a frame or a display name (a string).
5590 If omitted or nil, that stands for the selected frame's display. */)
5591 (Lisp_Object display)
5593 return Qnil;
5596 static BOOL CALLBACK ALIGN_STACK
5597 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5599 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5601 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5603 return TRUE;
5606 static Lisp_Object
5607 w32_display_monitor_attributes_list (void)
5609 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5610 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5611 int i, n_monitors;
5612 HMONITOR *monitors;
5613 struct gcpro gcpro1, gcpro2, gcpro3;
5615 if (!(enum_display_monitors_fn && get_monitor_info_fn
5616 && monitor_from_window_fn))
5617 return Qnil;
5619 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5620 (LPARAM) &monitor_list)
5621 || NILP (monitor_list))
5622 return Qnil;
5624 n_monitors = 0;
5625 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5626 n_monitors++;
5628 monitors = xmalloc (n_monitors * sizeof (*monitors));
5629 for (i = 0; i < n_monitors; i++)
5631 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5632 monitor_list = XCDR (monitor_list);
5635 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5636 FOR_EACH_FRAME (rest, frame)
5638 struct frame *f = XFRAME (frame);
5640 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5642 HMONITOR monitor =
5643 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5644 MONITOR_DEFAULT_TO_NEAREST);
5646 for (i = 0; i < n_monitors; i++)
5647 if (monitors[i] == monitor)
5648 break;
5650 if (i < n_monitors)
5651 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5655 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5657 for (i = 0; i < n_monitors; i++)
5659 Lisp_Object geometry, workarea, name, attributes = Qnil;
5660 HDC hdc;
5661 int width_mm, height_mm;
5662 struct MONITOR_INFO_EX mi;
5664 mi.cbSize = sizeof (mi);
5665 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5666 continue;
5668 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5669 if (hdc == NULL)
5670 continue;
5671 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5672 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5673 DeleteDC (hdc);
5675 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5676 attributes);
5678 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5680 attributes = Fcons (Fcons (Qname, name), attributes);
5682 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5683 attributes);
5685 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5686 mi.rcWork.right - mi.rcWork.left,
5687 mi.rcWork.bottom - mi.rcWork.top);
5688 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5690 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5691 mi.rcMonitor.right - mi.rcMonitor.left,
5692 mi.rcMonitor.bottom - mi.rcMonitor.top);
5693 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5695 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5696 primary_monitor_attributes = attributes;
5697 else
5698 attributes_list = Fcons (attributes, attributes_list);
5701 if (!NILP (primary_monitor_attributes))
5702 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5704 UNGCPRO;
5706 xfree (monitors);
5708 return attributes_list;
5711 static Lisp_Object
5712 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5714 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5715 HDC hdc;
5716 double mm_per_pixel;
5717 int pixel_width, pixel_height, width_mm, height_mm;
5718 RECT workarea_rect;
5720 /* Fallback: treat (possibly) multiple physical monitors as if they
5721 formed a single monitor as a whole. This should provide a
5722 consistent result at least on single monitor environments. */
5723 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5724 attributes);
5726 frames = Qnil;
5727 FOR_EACH_FRAME (rest, frame)
5729 struct frame *f = XFRAME (frame);
5731 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5732 frames = Fcons (frame, frames);
5734 attributes = Fcons (Fcons (Qframes, frames), attributes);
5736 pixel_width = x_display_pixel_width (dpyinfo);
5737 pixel_height = x_display_pixel_height (dpyinfo);
5739 hdc = GetDC (NULL);
5740 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5741 / GetDeviceCaps (hdc, HORZRES));
5742 width_mm = pixel_width * mm_per_pixel + 0.5;
5743 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5744 / GetDeviceCaps (hdc, VERTRES));
5745 height_mm = pixel_height * mm_per_pixel + 0.5;
5746 ReleaseDC (NULL, hdc);
5747 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5748 attributes);
5750 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5751 we don't care. */
5752 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5753 GetSystemMetrics (SM_YVIRTUALSCREEN),
5754 pixel_width, pixel_height);
5755 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5756 workarea = list4i (workarea_rect.left, workarea_rect.top,
5757 workarea_rect.right - workarea_rect.left,
5758 workarea_rect.bottom - workarea_rect.top);
5759 else
5760 workarea = geometry;
5761 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5763 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5765 return list1 (attributes);
5768 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5769 Sw32_display_monitor_attributes_list,
5770 0, 1, 0,
5771 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5773 The optional argument DISPLAY specifies which display to ask about.
5774 DISPLAY should be either a frame or a display name (a string).
5775 If omitted or nil, that stands for the selected frame's display.
5777 Internal use only, use `display-monitor-attributes-list' instead. */)
5778 (Lisp_Object display)
5780 struct w32_display_info *dpyinfo = check_x_display_info (display);
5781 Lisp_Object attributes_list;
5783 block_input ();
5784 attributes_list = w32_display_monitor_attributes_list ();
5785 if (NILP (attributes_list))
5786 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5787 unblock_input ();
5789 return attributes_list;
5792 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5793 doc: /* Set the sound generated when the bell is rung.
5794 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5795 to use the corresponding system sound for the bell. The 'silent sound
5796 prevents Emacs from making any sound at all.
5797 SOUND is nil to use the normal beep. */)
5798 (Lisp_Object sound)
5800 CHECK_SYMBOL (sound);
5802 if (NILP (sound))
5803 sound_type = 0xFFFFFFFF;
5804 else if (EQ (sound, intern ("asterisk")))
5805 sound_type = MB_ICONASTERISK;
5806 else if (EQ (sound, intern ("exclamation")))
5807 sound_type = MB_ICONEXCLAMATION;
5808 else if (EQ (sound, intern ("hand")))
5809 sound_type = MB_ICONHAND;
5810 else if (EQ (sound, intern ("question")))
5811 sound_type = MB_ICONQUESTION;
5812 else if (EQ (sound, intern ("ok")))
5813 sound_type = MB_OK;
5814 else if (EQ (sound, intern ("silent")))
5815 sound_type = MB_EMACS_SILENT;
5816 else
5817 sound_type = 0xFFFFFFFF;
5819 return sound;
5823 x_screen_planes (register struct frame *f)
5825 return FRAME_DISPLAY_INFO (f)->n_planes;
5828 /* Return the display structure for the display named NAME.
5829 Open a new connection if necessary. */
5831 struct w32_display_info *
5832 x_display_info_for_name (Lisp_Object name)
5834 struct w32_display_info *dpyinfo;
5836 CHECK_STRING (name);
5838 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5839 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5840 return dpyinfo;
5842 /* Use this general default value to start with. */
5843 Vx_resource_name = Vinvocation_name;
5845 validate_x_resource_name ();
5847 dpyinfo = w32_term_init (name, (unsigned char *)0,
5848 SSDATA (Vx_resource_name));
5850 if (dpyinfo == 0)
5851 error ("Cannot connect to server %s", SDATA (name));
5853 XSETFASTINT (Vwindow_system_version, w32_major_version);
5855 return dpyinfo;
5858 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5859 1, 3, 0, doc: /* Open a connection to a display server.
5860 DISPLAY is the name of the display to connect to.
5861 Optional second arg XRM-STRING is a string of resources in xrdb format.
5862 If the optional third arg MUST-SUCCEED is non-nil,
5863 terminate Emacs if we can't open the connection.
5864 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5865 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5867 unsigned char *xrm_option;
5868 struct w32_display_info *dpyinfo;
5870 CHECK_STRING (display);
5872 /* Signal an error in order to encourage correct use from callers.
5873 * If we ever support multiple window systems in the same Emacs,
5874 * we'll need callers to be precise about what window system they
5875 * want. */
5877 if (strcmp (SSDATA (display), "w32") != 0)
5878 error ("The name of the display in this Emacs must be \"w32\"");
5880 /* If initialization has already been done, return now to avoid
5881 overwriting critical parts of one_w32_display_info. */
5882 if (window_system_available (NULL))
5883 return Qnil;
5885 if (! NILP (xrm_string))
5886 CHECK_STRING (xrm_string);
5888 /* Allow color mapping to be defined externally; first look in user's
5889 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5891 Lisp_Object color_file;
5892 struct gcpro gcpro1;
5894 color_file = build_string ("~/rgb.txt");
5896 GCPRO1 (color_file);
5898 if (NILP (Ffile_readable_p (color_file)))
5899 color_file =
5900 Fexpand_file_name (build_string ("rgb.txt"),
5901 Fsymbol_value (intern ("data-directory")));
5903 Vw32_color_map = Fx_load_color_file (color_file);
5905 UNGCPRO;
5907 if (NILP (Vw32_color_map))
5908 Vw32_color_map = w32_default_color_map ();
5910 /* Merge in system logical colors. */
5911 add_system_logical_colors_to_map (&Vw32_color_map);
5913 if (! NILP (xrm_string))
5914 xrm_option = SDATA (xrm_string);
5915 else
5916 xrm_option = (unsigned char *) 0;
5918 /* Use this general default value to start with. */
5919 /* First remove .exe suffix from invocation-name - it looks ugly. */
5921 char basename[ MAX_PATH ], *str;
5923 lispstpcpy (basename, Vinvocation_name);
5924 str = strrchr (basename, '.');
5925 if (str) *str = 0;
5926 Vinvocation_name = build_string (basename);
5928 Vx_resource_name = Vinvocation_name;
5930 validate_x_resource_name ();
5932 /* This is what opens the connection and sets x_current_display.
5933 This also initializes many symbols, such as those used for input. */
5934 dpyinfo = w32_term_init (display, xrm_option,
5935 SSDATA (Vx_resource_name));
5937 if (dpyinfo == 0)
5939 if (!NILP (must_succeed))
5940 fatal ("Cannot connect to server %s.\n",
5941 SDATA (display));
5942 else
5943 error ("Cannot connect to server %s", SDATA (display));
5946 XSETFASTINT (Vwindow_system_version, w32_major_version);
5947 return Qnil;
5950 DEFUN ("x-close-connection", Fx_close_connection,
5951 Sx_close_connection, 1, 1, 0,
5952 doc: /* Close the connection to DISPLAY's server.
5953 For DISPLAY, specify either a frame or a display name (a string).
5954 If DISPLAY is nil, that stands for the selected frame's display. */)
5955 (Lisp_Object display)
5957 struct w32_display_info *dpyinfo = check_x_display_info (display);
5959 if (dpyinfo->reference_count > 0)
5960 error ("Display still has frames on it");
5962 block_input ();
5963 x_destroy_all_bitmaps (dpyinfo);
5965 x_delete_display (dpyinfo);
5966 unblock_input ();
5968 return Qnil;
5971 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5972 doc: /* Return the list of display names that Emacs has connections to. */)
5973 (void)
5975 Lisp_Object result = Qnil;
5976 struct w32_display_info *wdi;
5978 for (wdi = x_display_list; wdi; wdi = wdi->next)
5979 result = Fcons (XCAR (wdi->name_list_element), result);
5981 return result;
5984 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5985 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5986 This function only has an effect on X Windows. With MS Windows, it is
5987 defined but does nothing.
5989 If ON is nil, allow buffering of requests.
5990 Turning on synchronization prohibits the Xlib routines from buffering
5991 requests and seriously degrades performance, but makes debugging much
5992 easier.
5993 The optional second argument TERMINAL specifies which display to act on.
5994 TERMINAL should be a terminal object, a frame or a display name (a string).
5995 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5996 (Lisp_Object on, Lisp_Object display)
5998 return Qnil;
6003 /***********************************************************************
6004 Window properties
6005 ***********************************************************************/
6007 #if 0 /* TODO : port window properties to W32 */
6009 DEFUN ("x-change-window-property", Fx_change_window_property,
6010 Sx_change_window_property, 2, 6, 0,
6011 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6012 PROP must be a string. VALUE may be a string or a list of conses,
6013 numbers and/or strings. If an element in the list is a string, it is
6014 converted to an atom and the value of the Atom is used. If an element
6015 is a cons, it is converted to a 32 bit number where the car is the 16
6016 top bits and the cdr is the lower 16 bits.
6018 FRAME nil or omitted means use the selected frame.
6019 If TYPE is given and non-nil, it is the name of the type of VALUE.
6020 If TYPE is not given or nil, the type is STRING.
6021 FORMAT gives the size in bits of each element if VALUE is a list.
6022 It must be one of 8, 16 or 32.
6023 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6024 If OUTER-P is non-nil, the property is changed for the outer X window of
6025 FRAME. Default is to change on the edit X window. */)
6026 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6027 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6029 struct frame *f = decode_window_system_frame (frame);
6030 Atom prop_atom;
6032 CHECK_STRING (prop);
6033 CHECK_STRING (value);
6035 block_input ();
6036 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6037 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6038 prop_atom, XA_STRING, 8, PropModeReplace,
6039 SDATA (value), SCHARS (value));
6041 /* Make sure the property is set when we return. */
6042 XFlush (FRAME_W32_DISPLAY (f));
6043 unblock_input ();
6045 return value;
6049 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6050 Sx_delete_window_property, 1, 2, 0,
6051 doc: /* Remove window property PROP from X window of FRAME.
6052 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6053 (Lisp_Object prop, Lisp_Object frame)
6055 struct frame *f = decode_window_system_frame (frame);
6056 Atom prop_atom;
6058 CHECK_STRING (prop);
6059 block_input ();
6060 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6061 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6063 /* Make sure the property is removed when we return. */
6064 XFlush (FRAME_W32_DISPLAY (f));
6065 unblock_input ();
6067 return prop;
6071 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6072 1, 6, 0,
6073 doc: /* Value is the value of window property PROP on FRAME.
6074 If FRAME is nil or omitted, use the selected frame.
6076 On X Windows, the following optional arguments are also accepted:
6077 If TYPE is nil or omitted, get the property as a string.
6078 Otherwise TYPE is the name of the atom that denotes the type expected.
6079 If SOURCE is non-nil, get the property on that window instead of from
6080 FRAME. The number 0 denotes the root window.
6081 If DELETE-P is non-nil, delete the property after retrieving it.
6082 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6084 On MS Windows, this function accepts but ignores those optional arguments.
6086 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6087 no value of TYPE (always string in the MS Windows case). */)
6088 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6089 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6091 struct frame *f = decode_window_system_frame (frame);
6092 Atom prop_atom;
6093 int rc;
6094 Lisp_Object prop_value = Qnil;
6095 char *tmp_data = NULL;
6096 Atom actual_type;
6097 int actual_format;
6098 unsigned long actual_size, bytes_remaining;
6100 CHECK_STRING (prop);
6101 block_input ();
6102 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6103 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6104 prop_atom, 0, 0, False, XA_STRING,
6105 &actual_type, &actual_format, &actual_size,
6106 &bytes_remaining, (unsigned char **) &tmp_data);
6107 if (rc == Success)
6109 int size = bytes_remaining;
6111 XFree (tmp_data);
6112 tmp_data = NULL;
6114 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6115 prop_atom, 0, bytes_remaining,
6116 False, XA_STRING,
6117 &actual_type, &actual_format,
6118 &actual_size, &bytes_remaining,
6119 (unsigned char **) &tmp_data);
6120 if (rc == Success)
6121 prop_value = make_string (tmp_data, size);
6123 XFree (tmp_data);
6126 unblock_input ();
6128 return prop_value;
6130 return Qnil;
6133 #endif /* TODO */
6135 /***********************************************************************
6136 Tool tips
6137 ***********************************************************************/
6139 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
6140 Lisp_Object, Lisp_Object);
6141 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6142 Lisp_Object, int, int, int *, int *);
6144 /* The frame of a currently visible tooltip. */
6146 Lisp_Object tip_frame;
6148 /* If non-nil, a timer started that hides the last tooltip when it
6149 fires. */
6151 Lisp_Object tip_timer;
6152 Window tip_window;
6154 /* If non-nil, a vector of 3 elements containing the last args
6155 with which x-show-tip was called. See there. */
6157 Lisp_Object last_show_tip_args;
6160 static void
6161 unwind_create_tip_frame (Lisp_Object frame)
6163 Lisp_Object deleted;
6165 deleted = unwind_create_frame (frame);
6166 if (EQ (deleted, Qt))
6168 tip_window = NULL;
6169 tip_frame = Qnil;
6174 /* Create a frame for a tooltip on the display described by DPYINFO.
6175 PARMS is a list of frame parameters. TEXT is the string to
6176 display in the tip frame. Value is the frame.
6178 Note that functions called here, esp. x_default_parameter can
6179 signal errors, for instance when a specified color name is
6180 undefined. We have to make sure that we're in a consistent state
6181 when this happens. */
6183 static Lisp_Object
6184 x_create_tip_frame (struct w32_display_info *dpyinfo,
6185 Lisp_Object parms, Lisp_Object text)
6187 struct frame *f;
6188 Lisp_Object frame;
6189 Lisp_Object name;
6190 long window_prompting = 0;
6191 int width, height;
6192 ptrdiff_t count = SPECPDL_INDEX ();
6193 struct gcpro gcpro1, gcpro2, gcpro3;
6194 struct kboard *kb;
6195 bool face_change_before = face_change;
6196 Lisp_Object buffer;
6197 struct buffer *old_buffer;
6199 /* Use this general default value to start with until we know if
6200 this frame has a specified name. */
6201 Vx_resource_name = Vinvocation_name;
6203 kb = dpyinfo->terminal->kboard;
6205 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6206 avoid destructive changes behind our caller's back. */
6207 parms = Fcopy_alist (parms);
6209 /* Get the name of the frame to use for resource lookup. */
6210 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6211 if (!STRINGP (name)
6212 && !EQ (name, Qunbound)
6213 && !NILP (name))
6214 error ("Invalid frame name--not a string or nil");
6215 Vx_resource_name = name;
6217 frame = Qnil;
6218 GCPRO3 (parms, name, frame);
6219 /* Make a frame without minibuffer nor mode-line. */
6220 f = make_frame (false);
6221 f->wants_modeline = 0;
6222 XSETFRAME (frame, f);
6224 AUTO_STRING (tip, " *tip*");
6225 buffer = Fget_buffer_create (tip);
6226 /* Use set_window_buffer instead of Fset_window_buffer (see
6227 discussion of bug#11984, bug#12025, bug#12026). */
6228 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, false, false);
6229 old_buffer = current_buffer;
6230 set_buffer_internal_1 (XBUFFER (buffer));
6231 bset_truncate_lines (current_buffer, Qnil);
6232 specbind (Qinhibit_read_only, Qt);
6233 specbind (Qinhibit_modification_hooks, Qt);
6234 Ferase_buffer ();
6235 Finsert (1, &text);
6236 set_buffer_internal_1 (old_buffer);
6238 record_unwind_protect (unwind_create_tip_frame, frame);
6240 /* By setting the output method, we're essentially saying that
6241 the frame is live, as per FRAME_LIVE_P. If we get a signal
6242 from this point on, x_destroy_window might screw up reference
6243 counts etc. */
6244 f->terminal = dpyinfo->terminal;
6245 f->output_method = output_w32;
6246 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6248 FRAME_FONTSET (f) = -1;
6249 fset_icon_name (f, Qnil);
6251 #ifdef GLYPH_DEBUG
6252 image_cache_refcount =
6253 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6254 dpyinfo_refcount = dpyinfo->reference_count;
6255 #endif /* GLYPH_DEBUG */
6256 FRAME_KBOARD (f) = kb;
6257 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6258 f->output_data.w32->explicit_parent = false;
6260 /* Set the name; the functions to which we pass f expect the name to
6261 be set. */
6262 if (EQ (name, Qunbound) || NILP (name))
6264 fset_name (f, build_string (dpyinfo->w32_id_name));
6265 f->explicit_name = false;
6267 else
6269 fset_name (f, name);
6270 f->explicit_name = true;
6271 /* use the frame's title when getting resources for this frame. */
6272 specbind (Qx_resource_name, name);
6275 if (uniscribe_available)
6276 register_font_driver (&uniscribe_font_driver, f);
6277 register_font_driver (&w32font_driver, f);
6279 x_default_parameter (f, parms, Qfont_backend, Qnil,
6280 "fontBackend", "FontBackend", RES_TYPE_STRING);
6282 /* Extract the window parameters from the supplied values
6283 that are needed to determine window geometry. */
6284 x_default_font_parameter (f, parms);
6286 x_default_parameter (f, parms, Qborder_width, make_number (2),
6287 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6288 /* This defaults to 2 in order to match xterm. We recognize either
6289 internalBorderWidth or internalBorder (which is what xterm calls
6290 it). */
6291 if (NILP (Fassq (Qinternal_border_width, parms)))
6293 Lisp_Object value;
6295 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6296 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
6297 if (! EQ (value, Qunbound))
6298 parms = Fcons (Fcons (Qinternal_border_width, value),
6299 parms);
6301 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6302 "internalBorderWidth", "internalBorderWidth",
6303 RES_TYPE_NUMBER);
6304 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
6305 NULL, NULL, RES_TYPE_NUMBER);
6306 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
6307 NULL, NULL, RES_TYPE_NUMBER);
6309 /* Also do the stuff which must be set before the window exists. */
6310 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6311 "foreground", "Foreground", RES_TYPE_STRING);
6312 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6313 "background", "Background", RES_TYPE_STRING);
6314 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6315 "pointerColor", "Foreground", RES_TYPE_STRING);
6316 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6317 "cursorColor", "Foreground", RES_TYPE_STRING);
6318 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6319 "borderColor", "BorderColor", RES_TYPE_STRING);
6321 /* Init faces before x_default_parameter is called for the
6322 scroll-bar-width parameter because otherwise we end up in
6323 init_iterator with a null face cache, which should not happen. */
6324 init_frame_faces (f);
6326 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6327 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6329 window_prompting = x_figure_window_size (f, parms, false);
6331 /* No fringes on tip frame. */
6332 f->fringe_cols = 0;
6333 f->left_fringe_width = 0;
6334 f->right_fringe_width = 0;
6336 block_input ();
6337 my_create_tip_window (f);
6338 unblock_input ();
6340 x_make_gc (f);
6342 x_default_parameter (f, parms, Qauto_raise, Qnil,
6343 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6344 x_default_parameter (f, parms, Qauto_lower, Qnil,
6345 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6346 x_default_parameter (f, parms, Qcursor_type, Qbox,
6347 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6348 /* Process alpha here (Bug#17344). */
6349 x_default_parameter (f, parms, Qalpha, Qnil,
6350 "alpha", "Alpha", RES_TYPE_NUMBER);
6352 /* Dimensions, especially FRAME_LINES (f), must be done via
6353 change_frame_size. Change will not be effected unless different
6354 from the current FRAME_LINES (f). */
6355 width = FRAME_COLS (f);
6356 height = FRAME_LINES (f);
6357 SET_FRAME_COLS (f, 0);
6358 SET_FRAME_LINES (f, 0);
6359 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
6360 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
6362 /* Add `tooltip' frame parameter's default value. */
6363 if (NILP (Fframe_parameter (frame, Qtooltip)))
6364 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
6366 /* Set up faces after all frame parameters are known. This call
6367 also merges in face attributes specified for new frames.
6369 Frame parameters may be changed if .Xdefaults contains
6370 specifications for the default font. For example, if there is an
6371 `Emacs.default.attributeBackground: pink', the `background-color'
6372 attribute of the frame get's set, which let's the internal border
6373 of the tooltip frame appear in pink. Prevent this. */
6375 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
6376 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
6377 Lisp_Object colors = Qnil;
6379 /* Set tip_frame here, so that */
6380 tip_frame = frame;
6381 call2 (Qface_set_after_frame_default, frame, Qnil);
6383 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
6384 colors = Fcons (Fcons (Qbackground_color, bg), colors);
6385 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
6386 colors = Fcons (Fcons (Qforeground_color, fg), colors);
6388 if (!NILP (colors))
6389 Fmodify_frame_parameters (frame, colors);
6392 f->no_split = true;
6394 UNGCPRO;
6396 /* Now that the frame is official, it counts as a reference to
6397 its display. */
6398 FRAME_DISPLAY_INFO (f)->reference_count++;
6399 f->terminal->reference_count++;
6401 /* It is now ok to make the frame official even if we get an error
6402 below. And the frame needs to be on Vframe_list or making it
6403 visible won't work. */
6404 Vframe_list = Fcons (frame, Vframe_list);
6405 f->can_x_set_window_size = true;
6407 /* Setting attributes of faces of the tooltip frame from resources
6408 and similar will set face_change, which leads to the
6409 clearing of all current matrices. Since this isn't necessary
6410 here, avoid it by resetting face_change to the value it
6411 had before we created the tip frame. */
6412 face_change = face_change_before;
6414 /* Discard the unwind_protect. */
6415 return unbind_to (count, frame);
6419 /* Compute where to display tip frame F. PARMS is the list of frame
6420 parameters for F. DX and DY are specified offsets from the current
6421 location of the mouse. WIDTH and HEIGHT are the width and height
6422 of the tooltip. Return coordinates relative to the root window of
6423 the display in *ROOT_X and *ROOT_Y. */
6425 static void
6426 compute_tip_xy (struct frame *f,
6427 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
6428 int width, int height, int *root_x, int *root_y)
6430 Lisp_Object left, top, right, bottom;
6431 int min_x, min_y, max_x, max_y;
6433 /* User-specified position? */
6434 left = Fcdr (Fassq (Qleft, parms));
6435 top = Fcdr (Fassq (Qtop, parms));
6436 right = Fcdr (Fassq (Qright, parms));
6437 bottom = Fcdr (Fassq (Qbottom, parms));
6439 /* Move the tooltip window where the mouse pointer is. Resize and
6440 show it. */
6441 if ((!INTEGERP (left) && !INTEGERP (right))
6442 || (!INTEGERP (top) && !INTEGERP (bottom)))
6444 POINT pt;
6446 /* Default min and max values. */
6447 min_x = 0;
6448 min_y = 0;
6449 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
6450 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
6452 block_input ();
6453 GetCursorPos (&pt);
6454 *root_x = pt.x;
6455 *root_y = pt.y;
6456 unblock_input ();
6458 /* If multiple monitor support is available, constrain the tip onto
6459 the current monitor. This improves the above by allowing negative
6460 co-ordinates if monitor positions are such that they are valid, and
6461 snaps a tooltip onto a single monitor if we are close to the edge
6462 where it would otherwise flow onto the other monitor (or into
6463 nothingness if there is a gap in the overlap). */
6464 if (monitor_from_point_fn && get_monitor_info_fn)
6466 struct MONITOR_INFO info;
6467 HMONITOR monitor
6468 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
6469 info.cbSize = sizeof (info);
6471 if (get_monitor_info_fn (monitor, &info))
6473 min_x = info.rcWork.left;
6474 min_y = info.rcWork.top;
6475 max_x = info.rcWork.right;
6476 max_y = info.rcWork.bottom;
6481 if (INTEGERP (top))
6482 *root_y = XINT (top);
6483 else if (INTEGERP (bottom))
6484 *root_y = XINT (bottom) - height;
6485 else if (*root_y + XINT (dy) <= min_y)
6486 *root_y = min_y; /* Can happen for negative dy */
6487 else if (*root_y + XINT (dy) + height <= max_y)
6488 /* It fits below the pointer */
6489 *root_y += XINT (dy);
6490 else if (height + XINT (dy) + min_y <= *root_y)
6491 /* It fits above the pointer. */
6492 *root_y -= height + XINT (dy);
6493 else
6494 /* Put it on the top. */
6495 *root_y = min_y;
6497 if (INTEGERP (left))
6498 *root_x = XINT (left);
6499 else if (INTEGERP (right))
6500 *root_y = XINT (right) - width;
6501 else if (*root_x + XINT (dx) <= min_x)
6502 *root_x = 0; /* Can happen for negative dx */
6503 else if (*root_x + XINT (dx) + width <= max_x)
6504 /* It fits to the right of the pointer. */
6505 *root_x += XINT (dx);
6506 else if (width + XINT (dx) + min_x <= *root_x)
6507 /* It fits to the left of the pointer. */
6508 *root_x -= width + XINT (dx);
6509 else
6510 /* Put it left justified on the screen -- it ought to fit that way. */
6511 *root_x = min_x;
6515 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
6516 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
6517 A tooltip window is a small window displaying a string.
6519 This is an internal function; Lisp code should call `tooltip-show'.
6521 FRAME nil or omitted means use the selected frame.
6523 PARMS is an optional list of frame parameters which can be
6524 used to change the tooltip's appearance.
6526 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6527 means use the default timeout of 5 seconds.
6529 If the list of frame parameters PARMS contains a `left' parameter,
6530 display the tooltip at that x-position. If the list of frame parameters
6531 PARMS contains no `left' but a `right' parameter, display the tooltip
6532 right-adjusted at that x-position. Otherwise display it at the
6533 x-position of the mouse, with offset DX added (default is 5 if DX isn't
6534 specified).
6536 Likewise for the y-position: If a `top' frame parameter is specified, it
6537 determines the position of the upper edge of the tooltip window. If a
6538 `bottom' parameter but no `top' frame parameter is specified, it
6539 determines the position of the lower edge of the tooltip window.
6540 Otherwise display the tooltip window at the y-position of the mouse,
6541 with offset DY added (default is -10).
6543 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6544 Text larger than the specified size is clipped. */)
6545 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6547 struct frame *f;
6548 struct window *w;
6549 int root_x, root_y;
6550 struct buffer *old_buffer;
6551 struct text_pos pos;
6552 int i, width, height;
6553 bool seen_reversed_p;
6554 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
6555 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6556 ptrdiff_t count = SPECPDL_INDEX ();
6558 specbind (Qinhibit_redisplay, Qt);
6560 GCPRO4 (string, parms, frame, timeout);
6562 CHECK_STRING (string);
6563 f = decode_window_system_frame (frame);
6564 if (NILP (timeout))
6565 timeout = make_number (5);
6566 else
6567 CHECK_NATNUM (timeout);
6569 if (NILP (dx))
6570 dx = make_number (5);
6571 else
6572 CHECK_NUMBER (dx);
6574 if (NILP (dy))
6575 dy = make_number (-10);
6576 else
6577 CHECK_NUMBER (dy);
6579 if (NILP (last_show_tip_args))
6580 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6582 if (!NILP (tip_frame))
6584 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6585 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6586 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6588 if (EQ (frame, last_frame)
6589 && !NILP (Fequal (last_string, string))
6590 && !NILP (Fequal (last_parms, parms)))
6592 struct frame *f = XFRAME (tip_frame);
6594 /* Only DX and DY have changed. */
6595 if (!NILP (tip_timer))
6597 Lisp_Object timer = tip_timer;
6598 tip_timer = Qnil;
6599 call1 (Qcancel_timer, timer);
6602 block_input ();
6603 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6604 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6606 /* Put tooltip in topmost group and in position. */
6607 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6608 root_x, root_y, 0, 0,
6609 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6611 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6612 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6613 0, 0, 0, 0,
6614 SWP_NOMOVE | SWP_NOSIZE
6615 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6617 unblock_input ();
6618 goto start_timer;
6622 /* Hide a previous tip, if any. */
6623 Fx_hide_tip ();
6625 ASET (last_show_tip_args, 0, string);
6626 ASET (last_show_tip_args, 1, frame);
6627 ASET (last_show_tip_args, 2, parms);
6629 /* Add default values to frame parameters. */
6630 if (NILP (Fassq (Qname, parms)))
6631 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6632 if (NILP (Fassq (Qinternal_border_width, parms)))
6633 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6634 if (NILP (Fassq (Qright_divider_width, parms)))
6635 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6636 if (NILP (Fassq (Qbottom_divider_width, parms)))
6637 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6638 if (NILP (Fassq (Qborder_width, parms)))
6639 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6640 if (NILP (Fassq (Qborder_color, parms)))
6641 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6642 if (NILP (Fassq (Qbackground_color, parms)))
6643 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6644 parms);
6646 /* Block input until the tip has been fully drawn, to avoid crashes
6647 when drawing tips in menus. */
6648 block_input ();
6650 /* Create a frame for the tooltip, and record it in the global
6651 variable tip_frame. */
6652 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6653 f = XFRAME (frame);
6655 /* Set up the frame's root window. */
6656 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6657 w->left_col = 0;
6658 w->top_line = 0;
6659 w->pixel_left = 0;
6660 w->pixel_top = 0;
6662 if (CONSP (Vx_max_tooltip_size)
6663 && INTEGERP (XCAR (Vx_max_tooltip_size))
6664 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6665 && INTEGERP (XCDR (Vx_max_tooltip_size))
6666 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6668 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6669 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6671 else
6673 w->total_cols = 80;
6674 w->total_lines = 40;
6677 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6678 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6680 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6681 adjust_frame_glyphs (f);
6682 w->pseudo_window_p = true;
6684 /* Display the tooltip text in a temporary buffer. */
6685 old_buffer = current_buffer;
6686 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6687 bset_truncate_lines (current_buffer, Qnil);
6688 clear_glyph_matrix (w->desired_matrix);
6689 clear_glyph_matrix (w->current_matrix);
6690 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6691 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6693 /* Compute width and height of the tooltip. */
6694 width = height = 0;
6695 seen_reversed_p = false;
6696 for (i = 0; i < w->desired_matrix->nrows; ++i)
6698 struct glyph_row *row = &w->desired_matrix->rows[i];
6699 struct glyph *last;
6700 int row_width;
6702 /* Stop at the first empty row at the end. */
6703 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6704 break;
6706 /* Let the row go over the full width of the frame. */
6707 row->full_width_p = true;
6709 row_width = row->pixel_width;
6710 if (row->used[TEXT_AREA])
6712 if (!row->reversed_p)
6714 /* There's a glyph at the end of rows that is used to
6715 place the cursor there. Don't include the width of
6716 this glyph. */
6717 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6718 if (NILP (last->object))
6719 row_width -= last->pixel_width;
6721 else
6723 /* There could be a stretch glyph at the beginning of R2L
6724 rows that is produced by extend_face_to_end_of_line.
6725 Don't count that glyph. */
6726 struct glyph *g = row->glyphs[TEXT_AREA];
6728 if (g->type == STRETCH_GLYPH && NILP (g->object))
6730 row_width -= g->pixel_width;
6731 seen_reversed_p = true;
6736 height += row->height;
6737 width = max (width, row_width);
6740 /* If we've seen partial-length R2L rows, we need to re-adjust the
6741 tool-tip frame width and redisplay it again, to avoid over-wide
6742 tips due to the stretch glyph that extends R2L lines to full
6743 width of the frame. */
6744 if (seen_reversed_p)
6746 /* PXW: Why do we do the pixel-to-cols conversion only if
6747 seen_reversed_p holds? Don't we have to set other fields of
6748 the window/frame structure?
6750 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6751 not in pixels. */
6752 w->pixel_width = width;
6753 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6754 w->total_cols = width;
6755 FRAME_TOTAL_COLS (f) = width;
6756 SET_FRAME_WIDTH (f, width);
6757 adjust_frame_glyphs (f);
6758 w->pseudo_window_p = 1;
6759 clear_glyph_matrix (w->desired_matrix);
6760 clear_glyph_matrix (w->current_matrix);
6761 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6762 width = height = 0;
6763 /* Recompute width and height of the tooltip. */
6764 for (i = 0; i < w->desired_matrix->nrows; ++i)
6766 struct glyph_row *row = &w->desired_matrix->rows[i];
6767 struct glyph *last;
6768 int row_width;
6770 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6771 break;
6772 row->full_width_p = true;
6773 row_width = row->pixel_width;
6774 if (row->used[TEXT_AREA] && !row->reversed_p)
6776 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6777 if (NILP (last->object))
6778 row_width -= last->pixel_width;
6781 height += row->height;
6782 width = max (width, row_width);
6786 /* Add the frame's internal border to the width and height the w32
6787 window should have. */
6788 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6789 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6791 /* Move the tooltip window where the mouse pointer is. Resize and
6792 show it.
6794 PXW: This should use the frame's pixel coordinates. */
6795 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6798 /* Adjust Window size to take border into account. */
6799 RECT rect;
6800 rect.left = rect.top = 0;
6801 rect.right = width;
6802 rect.bottom = height;
6803 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6804 FRAME_EXTERNAL_MENU_BAR (f));
6806 /* Position and size tooltip, and put it in the topmost group.
6807 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6808 peculiarity of w32 display: without it, some fonts cause the
6809 last character of the tip to be truncated or wrapped around to
6810 the next line. */
6811 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6812 root_x, root_y,
6813 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6814 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6816 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6817 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6818 0, 0, 0, 0,
6819 SWP_NOMOVE | SWP_NOSIZE
6820 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6822 /* Let redisplay know that we have made the frame visible already. */
6823 SET_FRAME_VISIBLE (f, 1);
6825 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6828 /* Draw into the window. */
6829 w->must_be_updated_p = true;
6830 update_single_window (w);
6832 unblock_input ();
6834 /* Restore original current buffer. */
6835 set_buffer_internal_1 (old_buffer);
6836 windows_or_buffers_changed = old_windows_or_buffers_changed;
6838 start_timer:
6839 /* Let the tip disappear after timeout seconds. */
6840 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6841 intern ("x-hide-tip"));
6843 UNGCPRO;
6844 return unbind_to (count, Qnil);
6848 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6849 doc: /* Hide the current tooltip window, if there is any.
6850 Value is t if tooltip was open, nil otherwise. */)
6851 (void)
6853 ptrdiff_t count;
6854 Lisp_Object deleted, frame, timer;
6855 struct gcpro gcpro1, gcpro2;
6857 /* Return quickly if nothing to do. */
6858 if (NILP (tip_timer) && NILP (tip_frame))
6859 return Qnil;
6861 frame = tip_frame;
6862 timer = tip_timer;
6863 GCPRO2 (frame, timer);
6864 tip_frame = tip_timer = deleted = Qnil;
6866 count = SPECPDL_INDEX ();
6867 specbind (Qinhibit_redisplay, Qt);
6868 specbind (Qinhibit_quit, Qt);
6870 if (!NILP (timer))
6871 call1 (Qcancel_timer, timer);
6873 if (FRAMEP (frame))
6875 delete_frame (frame, Qnil);
6876 deleted = Qt;
6879 UNGCPRO;
6880 return unbind_to (count, deleted);
6883 /***********************************************************************
6884 File selection dialog
6885 ***********************************************************************/
6887 #define FILE_NAME_TEXT_FIELD edt1
6888 #define FILE_NAME_COMBO_BOX cmb13
6889 #define FILE_NAME_LIST lst1
6891 /* Callback for altering the behavior of the Open File dialog.
6892 Makes the Filename text field contain "Current Directory" and be
6893 read-only when "Directories" is selected in the filter. This
6894 allows us to work around the fact that the standard Open File
6895 dialog does not support directories. */
6896 static UINT_PTR CALLBACK
6897 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6899 if (msg == WM_NOTIFY)
6901 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6902 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6903 int dropdown_changed;
6904 int dir_index;
6905 #ifdef NTGUI_UNICODE
6906 const int use_unicode = 1;
6907 #else /* !NTGUI_UNICODE */
6908 int use_unicode = w32_unicode_filenames;
6909 #endif /* NTGUI_UNICODE */
6911 /* Detect when the Filter dropdown is changed. */
6912 if (use_unicode)
6913 dropdown_changed =
6914 notify_w->hdr.code == CDN_TYPECHANGE
6915 || notify_w->hdr.code == CDN_INITDONE;
6916 else
6917 dropdown_changed =
6918 notify_a->hdr.code == CDN_TYPECHANGE
6919 || notify_a->hdr.code == CDN_INITDONE;
6920 if (dropdown_changed)
6922 HWND dialog = GetParent (hwnd);
6923 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6924 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6925 int hdr_code;
6927 /* At least on Windows 7, the above attempt to get the window handle
6928 to the File Name Text Field fails. The following code does the
6929 job though. Note that this code is based on my examination of the
6930 window hierarchy using Microsoft Spy++. bk */
6931 if (edit_control == NULL)
6933 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6934 if (tmp)
6936 tmp = GetWindow (tmp, GW_CHILD);
6937 if (tmp)
6938 edit_control = GetWindow (tmp, GW_CHILD);
6942 /* Directories is in index 2. */
6943 if (use_unicode)
6945 dir_index = notify_w->lpOFN->nFilterIndex;
6946 hdr_code = notify_w->hdr.code;
6948 else
6950 dir_index = notify_a->lpOFN->nFilterIndex;
6951 hdr_code = notify_a->hdr.code;
6953 if (dir_index == 2)
6955 if (use_unicode)
6956 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6957 (LPARAM)L"Current Directory");
6958 else
6959 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6960 (LPARAM)"Current Directory");
6961 EnableWindow (edit_control, FALSE);
6962 /* Note that at least on Windows 7, the above call to EnableWindow
6963 disables the window that would ordinarily have focus. If we
6964 do not set focus to some other window here, focus will land in
6965 no man's land and the user will be unable to tab through the
6966 dialog box (pressing tab will only result in a beep).
6967 Avoid that problem by setting focus to the list here. */
6968 if (hdr_code == CDN_INITDONE)
6969 SetFocus (list);
6971 else
6973 /* Don't override default filename on init done. */
6974 if (hdr_code == CDN_TYPECHANGE)
6976 if (use_unicode)
6977 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6978 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6979 else
6980 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6981 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6983 EnableWindow (edit_control, TRUE);
6987 return 0;
6990 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6991 doc: /* Read file name, prompting with PROMPT in directory DIR.
6992 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6993 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6994 or directory must exist.
6996 This function is only defined on NS, MS Windows, and X Windows with the
6997 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6998 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6999 On Windows 7 and later, the file selection dialog "remembers" the last
7000 directory where the user selected a file, and will open that directory
7001 instead of DIR on subsequent invocations of this function with the same
7002 value of DIR as in previous invocations; this is standard Windows behavior. */)
7003 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
7005 /* Filter index: 1: All Files, 2: Directories only */
7006 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
7007 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
7009 Lisp_Object filename = default_filename;
7010 struct frame *f = SELECTED_FRAME ();
7011 BOOL file_opened = FALSE;
7012 Lisp_Object orig_dir = dir;
7013 Lisp_Object orig_prompt = prompt;
7015 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
7016 compatibility) we end up with the old file dialogs. Define a big
7017 enough struct for the new dialog to trick GetOpenFileName into
7018 giving us the new dialogs on newer versions of Windows. */
7019 struct {
7020 OPENFILENAMEW details;
7021 #if _WIN32_WINNT < 0x500 /* < win2k */
7022 PVOID pvReserved;
7023 DWORD dwReserved;
7024 DWORD FlagsEx;
7025 #endif /* < win2k */
7026 } new_file_details_w;
7028 #ifdef NTGUI_UNICODE
7029 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
7030 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7031 const int use_unicode = 1;
7032 #else /* not NTGUI_UNICODE */
7033 struct {
7034 OPENFILENAMEA details;
7035 #if _WIN32_WINNT < 0x500 /* < win2k */
7036 PVOID pvReserved;
7037 DWORD dwReserved;
7038 DWORD FlagsEx;
7039 #endif /* < win2k */
7040 } new_file_details_a;
7041 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7042 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7043 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7044 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7045 int use_unicode = w32_unicode_filenames;
7046 wchar_t *prompt_w;
7047 char *prompt_a;
7048 int len;
7049 char fname_ret[MAX_UTF8_PATH];
7050 #endif /* NTGUI_UNICODE */
7052 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
7053 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
7056 struct gcpro gcpro1, gcpro2;
7057 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
7059 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7060 system file encoding expected by the platform APIs (e.g. Cygwin's
7061 POSIX implementation) may not be the same as the encoding expected
7062 by the Windows "ANSI" APIs! */
7064 CHECK_STRING (prompt);
7065 CHECK_STRING (dir);
7067 dir = Fexpand_file_name (dir, Qnil);
7069 if (STRINGP (filename))
7070 filename = Ffile_name_nondirectory (filename);
7071 else
7072 filename = empty_unibyte_string;
7074 #ifdef CYGWIN
7075 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7076 if (SCHARS (filename) > 0)
7077 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7078 #endif
7080 CHECK_STRING (dir);
7081 CHECK_STRING (filename);
7083 /* The code in file_dialog_callback that attempts to set the text
7084 of the file name edit window when handling the CDN_INITDONE
7085 WM_NOTIFY message does not work. Setting filename to "Current
7086 Directory" in the only_dir_p case here does work however. */
7087 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7088 filename = build_string ("Current Directory");
7090 /* Convert the values we've computed so far to system form. */
7091 #ifdef NTGUI_UNICODE
7092 to_unicode (prompt, &prompt);
7093 to_unicode (dir, &dir);
7094 to_unicode (filename, &filename);
7095 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7096 report_file_error ("filename too long", default_filename);
7098 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7099 #else /* !NTGUI_UNICODE */
7100 prompt = ENCODE_FILE (prompt);
7101 dir = ENCODE_FILE (dir);
7102 filename = ENCODE_FILE (filename);
7104 /* We modify these in-place, so make copies for safety. */
7105 dir = Fcopy_sequence (dir);
7106 unixtodos_filename (SDATA (dir));
7107 filename = Fcopy_sequence (filename);
7108 unixtodos_filename (SDATA (filename));
7109 if (SBYTES (filename) >= MAX_UTF8_PATH)
7110 report_file_error ("filename too long", default_filename);
7111 if (w32_unicode_filenames)
7113 filename_to_utf16 (SSDATA (dir), dir_w);
7114 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7116 /* filename_to_utf16 sets errno to ENOENT when the file
7117 name is too long or cannot be converted to UTF-16. */
7118 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7119 report_file_error ("filename too long", default_filename);
7121 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7122 SSDATA (prompt), -1, NULL, 0);
7123 if (len > 32768)
7124 len = 32768;
7125 prompt_w = alloca (len * sizeof (wchar_t));
7126 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7127 SSDATA (prompt), -1, prompt_w, len);
7129 else
7131 filename_to_ansi (SSDATA (dir), dir_a);
7132 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7134 /* filename_to_ansi sets errno to ENOENT when the file
7135 name is too long or cannot be converted to UTF-16. */
7136 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7137 report_file_error ("filename too long", default_filename);
7139 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7140 SSDATA (prompt), -1, NULL, 0);
7141 if (len > 32768)
7142 len = 32768;
7143 prompt_w = alloca (len * sizeof (wchar_t));
7144 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7145 SSDATA (prompt), -1, prompt_w, len);
7146 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7147 if (len > 32768)
7148 len = 32768;
7149 prompt_a = alloca (len);
7150 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7152 #endif /* NTGUI_UNICODE */
7154 /* Fill in the structure for the call to GetOpenFileName below.
7155 For NTGUI_UNICODE builds (which run only on NT), we just use
7156 the actual size of the structure. For non-NTGUI_UNICODE
7157 builds, we tell the OS we're using an old version of the
7158 structure if the OS isn't new enough to support the newer
7159 version. */
7160 if (use_unicode)
7162 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7163 if (w32_major_version > 4 && w32_major_version < 95)
7164 file_details_w->lStructSize = sizeof (new_file_details_w);
7165 else
7166 file_details_w->lStructSize = sizeof (*file_details_w);
7167 /* Set up the inout parameter for the selected file name. */
7168 file_details_w->lpstrFile = filename_buf_w;
7169 file_details_w->nMaxFile =
7170 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7171 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7172 /* Undocumented Bug in Common File Dialog:
7173 If a filter is not specified, shell links are not resolved. */
7174 file_details_w->lpstrFilter = filter_w;
7175 #ifdef NTGUI_UNICODE
7176 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7177 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7178 #else
7179 file_details_w->lpstrInitialDir = dir_w;
7180 file_details_w->lpstrTitle = prompt_w;
7181 #endif
7182 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7183 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7184 | OFN_EXPLORER | OFN_ENABLEHOOK);
7185 if (!NILP (mustmatch))
7187 /* Require that the path to the parent directory exists. */
7188 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7189 /* If we are looking for a file, require that it exists. */
7190 if (NILP (only_dir_p))
7191 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7194 #ifndef NTGUI_UNICODE
7195 else
7197 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7198 if (w32_major_version > 4 && w32_major_version < 95)
7199 file_details_a->lStructSize = sizeof (new_file_details_a);
7200 else
7201 file_details_a->lStructSize = sizeof (*file_details_a);
7202 file_details_a->lpstrFile = filename_buf_a;
7203 file_details_a->nMaxFile =
7204 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7205 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7206 file_details_a->lpstrFilter = filter_a;
7207 file_details_a->lpstrInitialDir = dir_a;
7208 file_details_a->lpstrTitle = prompt_a;
7209 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7210 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7211 | OFN_EXPLORER | OFN_ENABLEHOOK);
7212 if (!NILP (mustmatch))
7214 /* Require that the path to the parent directory exists. */
7215 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7216 /* If we are looking for a file, require that it exists. */
7217 if (NILP (only_dir_p))
7218 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7221 #endif /* !NTGUI_UNICODE */
7224 int count = SPECPDL_INDEX ();
7225 /* Prevent redisplay. */
7226 specbind (Qinhibit_redisplay, Qt);
7227 block_input ();
7228 if (use_unicode)
7230 file_details_w->lpfnHook = file_dialog_callback;
7232 file_opened = GetOpenFileNameW (file_details_w);
7234 #ifndef NTGUI_UNICODE
7235 else
7237 file_details_a->lpfnHook = file_dialog_callback;
7239 file_opened = GetOpenFileNameA (file_details_a);
7241 #endif /* !NTGUI_UNICODE */
7242 unblock_input ();
7243 unbind_to (count, Qnil);
7246 if (file_opened)
7248 /* Get an Emacs string from the value Windows gave us. */
7249 #ifdef NTGUI_UNICODE
7250 filename = from_unicode_buffer (filename_buf_w);
7251 #else /* !NTGUI_UNICODE */
7252 if (use_unicode)
7253 filename_from_utf16 (filename_buf_w, fname_ret);
7254 else
7255 filename_from_ansi (filename_buf_a, fname_ret);
7256 dostounix_filename (fname_ret);
7257 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7258 #endif /* NTGUI_UNICODE */
7260 #ifdef CYGWIN
7261 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7262 #endif /* CYGWIN */
7264 /* Strip the dummy filename off the end of the string if we
7265 added it to select a directory. */
7266 if ((use_unicode && file_details_w->nFilterIndex == 2)
7267 #ifndef NTGUI_UNICODE
7268 || (!use_unicode && file_details_a->nFilterIndex == 2)
7269 #endif
7271 filename = Ffile_name_directory (filename);
7273 /* User canceled the dialog without making a selection. */
7274 else if (!CommDlgExtendedError ())
7275 filename = Qnil;
7276 /* An error occurred, fallback on reading from the mini-buffer. */
7277 else
7278 filename = Fcompleting_read (
7279 orig_prompt,
7280 intern ("read-file-name-internal"),
7281 orig_dir,
7282 mustmatch,
7283 orig_dir,
7284 Qfile_name_history,
7285 default_filename,
7286 Qnil);
7288 UNGCPRO;
7291 /* Make "Cancel" equivalent to C-g. */
7292 if (NILP (filename))
7293 Fsignal (Qquit, Qnil);
7295 RETURN_UNGCPRO (filename);
7299 #ifdef WINDOWSNT
7300 /* Moving files to the system recycle bin.
7301 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
7302 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
7303 Ssystem_move_file_to_trash, 1, 1, 0,
7304 doc: /* Move file or directory named FILENAME to the recycle bin. */)
7305 (Lisp_Object filename)
7307 Lisp_Object handler;
7308 Lisp_Object encoded_file;
7309 Lisp_Object operation;
7311 operation = Qdelete_file;
7312 if (!NILP (Ffile_directory_p (filename))
7313 && NILP (Ffile_symlink_p (filename)))
7315 operation = intern ("delete-directory");
7316 filename = Fdirectory_file_name (filename);
7319 /* Must have fully qualified file names for moving files to Recycle
7320 Bin. */
7321 filename = Fexpand_file_name (filename, Qnil);
7323 handler = Ffind_file_name_handler (filename, operation);
7324 if (!NILP (handler))
7325 return call2 (handler, operation, filename);
7326 else
7328 const char * path;
7329 int result;
7331 encoded_file = ENCODE_FILE (filename);
7333 path = map_w32_filename (SDATA (encoded_file), NULL);
7335 /* The Unicode version of SHFileOperation is not supported on
7336 Windows 9X. */
7337 if (w32_unicode_filenames && os_subtype != OS_9X)
7339 SHFILEOPSTRUCTW file_op_w;
7340 /* We need one more element beyond MAX_PATH because this is
7341 a list of file names, with the last element double-null
7342 terminated. */
7343 wchar_t tmp_path_w[MAX_PATH + 1];
7345 memset (tmp_path_w, 0, sizeof (tmp_path_w));
7346 filename_to_utf16 (path, tmp_path_w);
7348 /* On Windows, write permission is required to delete/move files. */
7349 _wchmod (tmp_path_w, 0666);
7351 memset (&file_op_w, 0, sizeof (file_op_w));
7352 file_op_w.hwnd = HWND_DESKTOP;
7353 file_op_w.wFunc = FO_DELETE;
7354 file_op_w.pFrom = tmp_path_w;
7355 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7356 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7357 file_op_w.fAnyOperationsAborted = FALSE;
7359 result = SHFileOperationW (&file_op_w);
7361 else
7363 SHFILEOPSTRUCTA file_op_a;
7364 char tmp_path_a[MAX_PATH + 1];
7366 memset (tmp_path_a, 0, sizeof (tmp_path_a));
7367 filename_to_ansi (path, tmp_path_a);
7369 /* If a file cannot be represented in ANSI codepage, don't
7370 let them inadvertently delete other files because some
7371 characters are interpreted as a wildcards. */
7372 if (_mbspbrk (tmp_path_a, "?*"))
7373 result = ERROR_FILE_NOT_FOUND;
7374 else
7376 _chmod (tmp_path_a, 0666);
7378 memset (&file_op_a, 0, sizeof (file_op_a));
7379 file_op_a.hwnd = HWND_DESKTOP;
7380 file_op_a.wFunc = FO_DELETE;
7381 file_op_a.pFrom = tmp_path_a;
7382 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7383 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7384 file_op_a.fAnyOperationsAborted = FALSE;
7386 result = SHFileOperationA (&file_op_a);
7389 if (result != 0)
7390 report_file_error ("Removing old name", list1 (filename));
7392 return Qnil;
7395 #endif /* WINDOWSNT */
7398 /***********************************************************************
7399 w32 specialized functions
7400 ***********************************************************************/
7402 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
7403 Sw32_send_sys_command, 1, 2, 0,
7404 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
7405 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
7406 to minimize), #xf120 to restore frame to original size, and #xf100
7407 to activate the menubar for keyboard access. #xf140 activates the
7408 screen saver if defined.
7410 If optional parameter FRAME is not specified, use selected frame. */)
7411 (Lisp_Object command, Lisp_Object frame)
7413 struct frame *f = decode_window_system_frame (frame);
7415 CHECK_NUMBER (command);
7417 if (FRAME_W32_P (f))
7418 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
7420 return Qnil;
7423 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
7424 doc: /* Get Windows to perform OPERATION on DOCUMENT.
7425 This is a wrapper around the ShellExecute system function, which
7426 invokes the application registered to handle OPERATION for DOCUMENT.
7428 OPERATION is either nil or a string that names a supported operation.
7429 What operations can be used depends on the particular DOCUMENT and its
7430 handler application, but typically it is one of the following common
7431 operations:
7433 \"open\" - open DOCUMENT, which could be a file, a directory, or an
7434 executable program (application). If it is an application,
7435 that application is launched in the current buffer's default
7436 directory. Otherwise, the application associated with
7437 DOCUMENT is launched in the buffer's default directory.
7438 \"opennew\" - like \"open\", but instruct the application to open
7439 DOCUMENT in a new window.
7440 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
7441 \"print\" - print DOCUMENT, which must be a file.
7442 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
7443 The printer should be provided in PARAMETERS, see below.
7444 \"explore\" - start the Windows Explorer on DOCUMENT.
7445 \"edit\" - launch an editor and open DOCUMENT for editing; which
7446 editor is launched depends on the association for the
7447 specified DOCUMENT.
7448 \"find\" - initiate search starting from DOCUMENT, which must specify
7449 a directory.
7450 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
7451 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
7452 the clipboard.
7453 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
7454 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
7455 which must be a directory.
7456 \"pastelink\"
7457 - create a shortcut in DOCUMENT (which must be a directory)
7458 the file or directory whose name is in the clipboard.
7459 \"runas\" - run DOCUMENT, which must be an excutable file, with
7460 elevated privileges (a.k.a. \"as Administrator\").
7461 \"properties\"
7462 - open the property sheet dialog for DOCUMENT.
7463 nil - invoke the default OPERATION, or \"open\" if default is
7464 not defined or unavailable.
7466 DOCUMENT is typically the name of a document file or a URL, but can
7467 also be an executable program to run, or a directory to open in the
7468 Windows Explorer. If it is a file or a directory, it must be a local
7469 one; this function does not support remote file names.
7471 If DOCUMENT is an executable program, the optional third arg PARAMETERS
7472 can be a string containing command line parameters, separated by blanks,
7473 that will be passed to the program. Some values of OPERATION also require
7474 parameters (e.g., \"printto\" requires the printer address). Otherwise,
7475 PARAMETERS should be nil or unspecified. Note that double quote characters
7476 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
7478 Optional fourth argument SHOW-FLAG can be used to control how the
7479 application will be displayed when it is invoked. If SHOW-FLAG is nil
7480 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
7481 specified, otherwise it is an integer between 0 and 11 representing
7482 a ShowWindow flag:
7484 0 - start hidden
7485 1 - start as normal-size window
7486 3 - start in a maximized window
7487 6 - start in a minimized window
7488 10 - start as the application itself specifies; this is the default. */)
7489 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
7491 char *errstr;
7492 Lisp_Object current_dir = BVAR (current_buffer, directory);;
7493 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
7494 #ifdef CYGWIN
7495 intptr_t result;
7496 #else
7497 int use_unicode = w32_unicode_filenames;
7498 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
7499 Lisp_Object absdoc, handler;
7500 BOOL success;
7501 struct gcpro gcpro1;
7502 #endif
7504 CHECK_STRING (document);
7506 #ifdef CYGWIN
7507 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
7508 document = Fcygwin_convert_file_name_to_windows (document, Qt);
7510 /* Encode filename, current directory and parameters. */
7511 current_dir = GUI_ENCODE_FILE (current_dir);
7512 document = GUI_ENCODE_FILE (document);
7513 doc_w = GUI_SDATA (document);
7514 if (STRINGP (parameters))
7516 parameters = GUI_ENCODE_SYSTEM (parameters);
7517 params_w = GUI_SDATA (parameters);
7519 if (STRINGP (operation))
7521 operation = GUI_ENCODE_SYSTEM (operation);
7522 ops_w = GUI_SDATA (operation);
7524 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7525 GUI_SDATA (current_dir),
7526 (INTEGERP (show_flag)
7527 ? XINT (show_flag) : SW_SHOWDEFAULT));
7529 if (result > 32)
7530 return Qt;
7532 switch (result)
7534 case SE_ERR_ACCESSDENIED:
7535 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7536 break;
7537 case SE_ERR_ASSOCINCOMPLETE:
7538 case SE_ERR_NOASSOC:
7539 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7540 break;
7541 case SE_ERR_DDEBUSY:
7542 case SE_ERR_DDEFAIL:
7543 errstr = w32_strerror (ERROR_DDE_FAIL);
7544 break;
7545 case SE_ERR_DDETIMEOUT:
7546 errstr = w32_strerror (ERROR_TIMEOUT);
7547 break;
7548 case SE_ERR_DLLNOTFOUND:
7549 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7550 break;
7551 case SE_ERR_FNF:
7552 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7553 break;
7554 case SE_ERR_OOM:
7555 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7556 break;
7557 case SE_ERR_PNF:
7558 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7559 break;
7560 case SE_ERR_SHARE:
7561 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7562 break;
7563 default:
7564 errstr = w32_strerror (0);
7565 break;
7568 #else /* !CYGWIN */
7570 const char file_url_str[] = "file:///";
7571 const int file_url_len = sizeof (file_url_str) - 1;
7572 int doclen;
7574 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
7576 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
7577 start a thread in some rare system configurations, for
7578 unknown reasons. That thread is started in the context of
7579 the Emacs process, but out of control of our code, and seems
7580 to never exit afterwards. Each such thread reserves 8MB of
7581 stack space (because that's the value recorded in the Emacs
7582 executable at link time: Emacs needs a large stack). So a
7583 large enough number of invocations of w32-shell-execute can
7584 potentially cause the Emacs process to run out of available
7585 address space, which is nasty. To work around this, we
7586 convert such URLs to local file names, which seems to prevent
7587 those threads from starting. See bug #20220. */
7588 char *p = SSDATA (document) + file_url_len;
7590 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
7591 document = Fsubstring_no_properties (document,
7592 make_number (file_url_len), Qnil);
7594 /* We have a situation here. If DOCUMENT is a relative file name,
7595 but its name includes leading directories, i.e. it lives not in
7596 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7597 will fail to find it. So we need to make the file name is
7598 absolute. But DOCUMENT does not have to be a file, it can be a
7599 URL, for example. So we make it absolute only if it is an
7600 existing file; if it is a file that does not exist, tough. */
7601 GCPRO1 (absdoc);
7602 absdoc = Fexpand_file_name (document, Qnil);
7603 /* Don't call file handlers for file-exists-p, since they might
7604 attempt to access the file, which could fail or produce undesired
7605 consequences, see bug#16558 for an example. */
7606 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7607 if (NILP (handler))
7609 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7611 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7613 /* ShellExecute fails if DOCUMENT is a UNC with forward
7614 slashes (expand-file-name above converts all backslashes
7615 to forward slashes). Now that we know DOCUMENT is a
7616 file, we can mirror all forward slashes into backslashes. */
7617 unixtodos_filename (SSDATA (absdoc_encoded));
7618 document = absdoc_encoded;
7620 else
7621 document = ENCODE_FILE (document);
7623 else
7624 document = ENCODE_FILE (document);
7625 UNGCPRO;
7627 current_dir = ENCODE_FILE (current_dir);
7628 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
7629 be a URL that is not limited to MAX_PATH chararcters. */
7630 doclen = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7631 SSDATA (document), -1, NULL, 0);
7632 doc_w = xmalloc (doclen * sizeof (wchar_t));
7633 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7634 SSDATA (document), -1, doc_w, doclen);
7635 if (use_unicode)
7637 wchar_t current_dir_w[MAX_PATH];
7638 SHELLEXECUTEINFOW shexinfo_w;
7640 /* Encode the current directory and parameters, and convert
7641 operation to UTF-16. */
7642 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7643 if (STRINGP (parameters))
7645 int len;
7647 parameters = ENCODE_SYSTEM (parameters);
7648 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7649 SSDATA (parameters), -1, NULL, 0);
7650 if (len > 32768)
7651 len = 32768;
7652 params_w = alloca (len * sizeof (wchar_t));
7653 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7654 SSDATA (parameters), -1, params_w, len);
7655 params_w[len - 1] = 0;
7657 if (STRINGP (operation))
7659 /* Assume OPERATION is pure ASCII. */
7660 const char *s = SSDATA (operation);
7661 wchar_t *d;
7662 int len = SBYTES (operation) + 1;
7664 if (len > 32768)
7665 len = 32768;
7666 d = ops_w = alloca (len * sizeof (wchar_t));
7667 while (d < ops_w + len - 1)
7668 *d++ = *s++;
7669 *d = 0;
7672 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7673 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7674 able to invoke verbs from shortcut menu extensions, not just
7675 static verbs listed in the Registry. */
7676 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7677 shexinfo_w.cbSize = sizeof (shexinfo_w);
7678 shexinfo_w.fMask =
7679 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7680 shexinfo_w.hwnd = NULL;
7681 shexinfo_w.lpVerb = ops_w;
7682 shexinfo_w.lpFile = doc_w;
7683 shexinfo_w.lpParameters = params_w;
7684 shexinfo_w.lpDirectory = current_dir_w;
7685 shexinfo_w.nShow =
7686 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7687 success = ShellExecuteExW (&shexinfo_w);
7688 xfree (doc_w);
7690 else
7692 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7693 SHELLEXECUTEINFOA shexinfo_a;
7694 int codepage = codepage_for_filenames (NULL);
7695 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
7696 NULL, NULL);
7698 doc_a = xmalloc (ldoc_a);
7699 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
7700 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7701 if (STRINGP (parameters))
7703 parameters = ENCODE_SYSTEM (parameters);
7704 params_a = SSDATA (parameters);
7706 if (STRINGP (operation))
7708 /* Assume OPERATION is pure ASCII. */
7709 ops_a = SSDATA (operation);
7711 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7712 shexinfo_a.cbSize = sizeof (shexinfo_a);
7713 shexinfo_a.fMask =
7714 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7715 shexinfo_a.hwnd = NULL;
7716 shexinfo_a.lpVerb = ops_a;
7717 shexinfo_a.lpFile = doc_a;
7718 shexinfo_a.lpParameters = params_a;
7719 shexinfo_a.lpDirectory = current_dir_a;
7720 shexinfo_a.nShow =
7721 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7722 success = ShellExecuteExA (&shexinfo_a);
7723 xfree (doc_w);
7724 xfree (doc_a);
7727 if (success)
7728 return Qt;
7730 errstr = w32_strerror (0);
7732 #endif /* !CYGWIN */
7734 /* The error string might be encoded in the locale's encoding. */
7735 if (!NILP (Vlocale_coding_system))
7737 Lisp_Object decoded =
7738 code_convert_string_norecord (build_unibyte_string (errstr),
7739 Vlocale_coding_system, 0);
7740 errstr = SSDATA (decoded);
7742 error ("ShellExecute failed: %s", errstr);
7745 /* Lookup virtual keycode from string representing the name of a
7746 non-ascii keystroke into the corresponding virtual key, using
7747 lispy_function_keys. */
7748 static int
7749 lookup_vk_code (char *key)
7751 int i;
7753 for (i = 0; i < 256; i++)
7754 if (lispy_function_keys[i]
7755 && strcmp (lispy_function_keys[i], key) == 0)
7756 return i;
7758 return -1;
7761 /* Convert a one-element vector style key sequence to a hot key
7762 definition. */
7763 static Lisp_Object
7764 w32_parse_hot_key (Lisp_Object key)
7766 /* Copied from Fdefine_key and store_in_keymap. */
7767 register Lisp_Object c;
7768 int vk_code;
7769 int lisp_modifiers;
7770 int w32_modifiers;
7771 struct gcpro gcpro1;
7773 CHECK_VECTOR (key);
7775 if (ASIZE (key) != 1)
7776 return Qnil;
7778 GCPRO1 (key);
7780 c = AREF (key, 0);
7782 if (CONSP (c) && lucid_event_type_list_p (c))
7783 c = Fevent_convert_list (c);
7785 UNGCPRO;
7787 if (! INTEGERP (c) && ! SYMBOLP (c))
7788 error ("Key definition is invalid");
7790 /* Work out the base key and the modifiers. */
7791 if (SYMBOLP (c))
7793 c = parse_modifiers (c);
7794 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7795 c = Fcar (c);
7796 if (!SYMBOLP (c))
7797 emacs_abort ();
7798 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7800 else if (INTEGERP (c))
7802 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7803 /* Many ascii characters are their own virtual key code. */
7804 vk_code = XINT (c) & CHARACTERBITS;
7807 if (vk_code < 0 || vk_code > 255)
7808 return Qnil;
7810 if ((lisp_modifiers & meta_modifier) != 0
7811 && !NILP (Vw32_alt_is_meta))
7812 lisp_modifiers |= alt_modifier;
7814 /* Supply defs missing from mingw32. */
7815 #ifndef MOD_ALT
7816 #define MOD_ALT 0x0001
7817 #define MOD_CONTROL 0x0002
7818 #define MOD_SHIFT 0x0004
7819 #define MOD_WIN 0x0008
7820 #endif
7822 /* Convert lisp modifiers to Windows hot-key form. */
7823 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7824 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7825 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7826 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7828 return HOTKEY (vk_code, w32_modifiers);
7831 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7832 Sw32_register_hot_key, 1, 1, 0,
7833 doc: /* Register KEY as a hot-key combination.
7834 Certain key combinations like Alt-Tab are reserved for system use on
7835 Windows, and therefore are normally intercepted by the system. However,
7836 most of these key combinations can be received by registering them as
7837 hot-keys, overriding their special meaning.
7839 KEY must be a one element key definition in vector form that would be
7840 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7841 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7842 is always interpreted as the Windows modifier keys.
7844 The return value is the hotkey-id if registered, otherwise nil. */)
7845 (Lisp_Object key)
7847 key = w32_parse_hot_key (key);
7849 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7851 /* Reuse an empty slot if possible. */
7852 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7854 /* Safe to add new key to list, even if we have focus. */
7855 if (NILP (item))
7856 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7857 else
7858 XSETCAR (item, key);
7860 /* Notify input thread about new hot-key definition, so that it
7861 takes effect without needing to switch focus. */
7862 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7863 (WPARAM) XINT (key), 0);
7866 return key;
7869 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7870 Sw32_unregister_hot_key, 1, 1, 0,
7871 doc: /* Unregister KEY as a hot-key combination. */)
7872 (Lisp_Object key)
7874 Lisp_Object item;
7876 if (!INTEGERP (key))
7877 key = w32_parse_hot_key (key);
7879 item = Fmemq (key, w32_grabbed_keys);
7881 if (!NILP (item))
7883 LPARAM lparam;
7885 eassert (CONSP (item));
7886 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
7887 so that it works in a --with-wide-int build as well. */
7888 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
7890 /* Notify input thread about hot-key definition being removed, so
7891 that it takes effect without needing focus switch. */
7892 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7893 (WPARAM) XINT (XCAR (item)), lparam))
7895 MSG msg;
7896 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7898 return Qt;
7900 return Qnil;
7903 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7904 Sw32_registered_hot_keys, 0, 0, 0,
7905 doc: /* Return list of registered hot-key IDs. */)
7906 (void)
7908 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7911 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7912 Sw32_reconstruct_hot_key, 1, 1, 0,
7913 doc: /* Convert hot-key ID to a lisp key combination.
7914 usage: (w32-reconstruct-hot-key ID) */)
7915 (Lisp_Object hotkeyid)
7917 int vk_code, w32_modifiers;
7918 Lisp_Object key;
7920 CHECK_NUMBER (hotkeyid);
7922 vk_code = HOTKEY_VK_CODE (hotkeyid);
7923 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7925 if (vk_code < 256 && lispy_function_keys[vk_code])
7926 key = intern (lispy_function_keys[vk_code]);
7927 else
7928 key = make_number (vk_code);
7930 key = Fcons (key, Qnil);
7931 if (w32_modifiers & MOD_SHIFT)
7932 key = Fcons (Qshift, key);
7933 if (w32_modifiers & MOD_CONTROL)
7934 key = Fcons (Qctrl, key);
7935 if (w32_modifiers & MOD_ALT)
7936 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7937 if (w32_modifiers & MOD_WIN)
7938 key = Fcons (Qhyper, key);
7940 return key;
7943 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7944 Sw32_toggle_lock_key, 1, 2, 0,
7945 doc: /* Toggle the state of the lock key KEY.
7946 KEY can be `capslock', `kp-numlock', or `scroll'.
7947 If the optional parameter NEW-STATE is a number, then the state of KEY
7948 is set to off if the low bit of NEW-STATE is zero, otherwise on.
7949 If NEW-STATE is omitted or nil, the function toggles the state,
7951 Value is the new state of the key, or nil if the function failed
7952 to change the state. */)
7953 (Lisp_Object key, Lisp_Object new_state)
7955 int vk_code;
7956 LPARAM lparam;
7958 if (EQ (key, intern ("capslock")))
7959 vk_code = VK_CAPITAL;
7960 else if (EQ (key, intern ("kp-numlock")))
7961 vk_code = VK_NUMLOCK;
7962 else if (EQ (key, intern ("scroll")))
7963 vk_code = VK_SCROLL;
7964 else
7965 return Qnil;
7967 if (!dwWindowsThreadId)
7968 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7970 if (NILP (new_state))
7971 lparam = -1;
7972 else
7973 lparam = (XUINT (new_state)) & 1;
7974 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7975 (WPARAM) vk_code, lparam))
7977 MSG msg;
7978 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7979 return make_number (msg.wParam);
7981 return Qnil;
7984 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7985 2, 2, 0,
7986 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7988 This is a direct interface to the Windows API FindWindow function. */)
7989 (Lisp_Object class, Lisp_Object name)
7991 HWND hnd;
7993 if (!NILP (class))
7994 CHECK_STRING (class);
7995 if (!NILP (name))
7996 CHECK_STRING (name);
7998 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7999 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8000 if (!hnd)
8001 return Qnil;
8002 return Qt;
8005 DEFUN ("x-frame-geometry", Fx_frame_geometry, Sx_frame_geometry, 0, 1, 0,
8006 doc: /* Return geometric attributes of FRAME.
8007 FRAME must be a live frame and defaults to the selected one. The return
8008 value is an association list of the attributes listed below. All height
8009 and width values are in pixels.
8011 `outer-position' is a cons of the outer left and top edges of FRAME
8012 relative to the origin - the position (0, 0) - of FRAME's display.
8014 `outer-size' is a cons of the outer width and height of FRAME. The
8015 outer size includes the title bar and the external borders as well as
8016 any menu and/or tool bar of frame.
8018 `external-border-size' is a cons of the horizontal and vertical width of
8019 FRAME's external borders as supplied by the window manager.
8021 `title-bar-size' is a cons of the width and height of the title bar of
8022 FRAME as supplied by the window manager. If both of them are zero,
8023 FRAME has no title bar. If only the width is zero, Emacs was not
8024 able to retrieve the width information.
8026 `menu-bar-external', if non-nil, means the menu bar is external (never
8027 included in the inner edges of FRAME).
8029 `menu-bar-size' is a cons of the width and height of the menu bar of
8030 FRAME.
8032 `tool-bar-external', if non-nil, means the tool bar is external (never
8033 included in the inner edges of FRAME).
8035 `tool-bar-position' tells on which side the tool bar on FRAME is and can
8036 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
8037 has no tool bar.
8039 `tool-bar-size' is a cons of the width and height of the tool bar of
8040 FRAME.
8042 `internal-border-width' is the width of the internal border of
8043 FRAME. */)
8044 (Lisp_Object frame)
8046 struct frame *f = decode_live_frame (frame);
8048 MENUBARINFO menu_bar;
8049 WINDOWINFO window;
8050 int left, top, right, bottom;
8051 unsigned int external_border_width, external_border_height;
8052 int title_bar_width = 0, title_bar_height = 0;
8053 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8054 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8055 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8056 bool fullboth = EQ (get_frame_param (f, Qfullscreen), Qfullboth);
8058 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8059 return Qnil;
8061 block_input ();
8062 /* Outer rectangle and borders. */
8063 window.cbSize = sizeof (window);
8064 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8065 external_border_width = window.cxWindowBorders;
8066 external_border_height = window.cyWindowBorders;
8067 /* Title bar. */
8068 if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8070 if (get_title_bar_info_fn)
8072 TITLEBAR_INFO title_bar;
8074 title_bar.cbSize = sizeof (title_bar);
8075 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8076 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8077 get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar);
8078 title_bar_width
8079 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8080 title_bar_height
8081 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8083 else
8084 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8086 /* Menu bar. */
8087 menu_bar.cbSize = sizeof (menu_bar);
8088 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8089 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8090 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8091 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8092 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8093 unblock_input ();
8095 left = window.rcWindow.left;
8096 top = window.rcWindow.top;
8097 right = window.rcWindow.right;
8098 bottom = window.rcWindow.bottom;
8100 /* Menu bar. */
8101 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8102 /* Fix menu bar height reported by GetMenuBarInfo. */
8103 if (menu_bar_height > single_menu_bar_height)
8104 /* A wrapped menu bar. */
8105 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8106 else if (menu_bar_height > 0)
8107 /* A single line menu bar. */
8108 menu_bar_height = single_menu_bar_height;
8110 return listn (CONSTYPE_HEAP, 10,
8111 Fcons (Qouter_position,
8112 Fcons (make_number (left), make_number (top))),
8113 Fcons (Qouter_size,
8114 Fcons (make_number (right - left),
8115 make_number (bottom - top))),
8116 Fcons (Qexternal_border_size,
8117 Fcons (make_number (external_border_width),
8118 make_number (external_border_height))),
8119 Fcons (Qtitle_bar_size,
8120 Fcons (make_number (title_bar_width),
8121 make_number (title_bar_height))),
8122 Fcons (Qmenu_bar_external, Qt),
8123 Fcons (Qmenu_bar_size,
8124 Fcons (make_number
8125 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8126 make_number (menu_bar_height))),
8127 Fcons (Qtool_bar_external, Qnil),
8128 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8129 Fcons (Qtool_bar_size,
8130 Fcons (make_number
8131 (tool_bar_height
8132 ? right - left - 2 * internal_border_width
8133 : 0),
8134 make_number (tool_bar_height))),
8135 Fcons (Qinternal_border_width,
8136 make_number (internal_border_width)));
8139 DEFUN ("x-frame-edges", Fx_frame_edges, Sx_frame_edges, 0, 2, 0,
8140 doc: /* Return edge coordinates of FRAME.
8141 FRAME must be a live frame and defaults to the selected one. The return
8142 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8143 in pixels relative to the origin - the position (0, 0) - of FRAME's
8144 display.
8146 If optional argument TYPE is the symbol `outer-edges', return the outer
8147 edges of FRAME. The outer edges comprise the decorations of the window
8148 manager (like the title bar or external borders) as well as any external
8149 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8150 `native-edges' or nil, return the native edges of FRAME. The native
8151 edges exclude the decorations of the window manager and any external
8152 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8153 the inner edges of FRAME. These edges exclude title bar, any borders,
8154 menu bar or tool bar of FRAME. */)
8155 (Lisp_Object frame, Lisp_Object type)
8157 struct frame *f = decode_live_frame (frame);
8159 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8160 return Qnil;
8162 if (EQ (type, Qouter_edges))
8164 RECT rectangle;
8166 block_input ();
8167 /* Outer frame rectangle, including outer borders and title bar. */
8168 GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8169 unblock_input ();
8171 return list4 (make_number (rectangle.left),
8172 make_number (rectangle.top),
8173 make_number (rectangle.right),
8174 make_number (rectangle.bottom));
8176 else
8178 RECT rectangle;
8179 POINT pt;
8180 int left, top, right, bottom;
8182 block_input ();
8183 /* Inner frame rectangle, excluding borders and title bar. */
8184 GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
8185 /* Get top-left corner of native rectangle in screen
8186 coordinates. */
8187 pt.x = 0;
8188 pt.y = 0;
8189 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
8190 unblock_input ();
8192 left = pt.x;
8193 top = pt.y;
8194 right = left + rectangle.right;
8195 bottom = top + rectangle.bottom;
8197 if (EQ (type, Qinner_edges))
8199 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8201 return list4 (make_number (left + internal_border_width),
8202 make_number (top
8203 + FRAME_TOOL_BAR_HEIGHT (f)
8204 + internal_border_width),
8205 make_number (right - internal_border_width),
8206 make_number (bottom - internal_border_width));
8208 else
8209 return list4 (make_number (left), make_number (top),
8210 make_number (right), make_number (bottom));
8214 DEFUN ("x-mouse-absolute-pixel-position", Fx_mouse_absolute_pixel_position,
8215 Sx_mouse_absolute_pixel_position, 0, 0, 0,
8216 doc: /* Return absolute position of mouse cursor in pixels.
8217 The position is returned as a cons cell (X . Y) of the coordinates of
8218 the mouse cursor position in pixels relative to a position (0, 0) of the
8219 selected frame's display. */)
8220 (void)
8222 POINT pt;
8224 block_input ();
8225 GetCursorPos (&pt);
8226 unblock_input ();
8228 return Fcons (make_number (pt.x), make_number (pt.y));
8231 DEFUN ("x-set-mouse-absolute-pixel-position", Fx_set_mouse_absolute_pixel_position,
8232 Sx_set_mouse_absolute_pixel_position, 2, 2, 0,
8233 doc: /* Move mouse pointer to absolute pixel position (X, Y).
8234 The coordinates X and Y are interpreted in pixels relative to a position
8235 (0, 0) of the selected frame's display. */)
8236 (Lisp_Object x, Lisp_Object y)
8238 CHECK_TYPE_RANGED_INTEGER (int, x);
8239 CHECK_TYPE_RANGED_INTEGER (int, y);
8241 block_input ();
8242 SetCursorPos (XINT (x), XINT (y));
8243 unblock_input ();
8245 return Qnil;
8248 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
8249 doc: /* Get power status information from Windows system.
8251 The following %-sequences are provided:
8252 %L AC line status (verbose)
8253 %B Battery status (verbose)
8254 %b Battery status, empty means high, `-' means low,
8255 `!' means critical, and `+' means charging
8256 %p Battery load percentage
8257 %s Remaining time (to charge or discharge) in seconds
8258 %m Remaining time (to charge or discharge) in minutes
8259 %h Remaining time (to charge or discharge) in hours
8260 %t Remaining time (to charge or discharge) in the form `h:min' */)
8261 (void)
8263 Lisp_Object status = Qnil;
8265 SYSTEM_POWER_STATUS system_status;
8266 if (GetSystemPowerStatus (&system_status))
8268 Lisp_Object line_status, battery_status, battery_status_symbol;
8269 Lisp_Object load_percentage, seconds, minutes, hours, remain;
8271 long seconds_left = (long) system_status.BatteryLifeTime;
8273 if (system_status.ACLineStatus == 0)
8274 line_status = build_string ("off-line");
8275 else if (system_status.ACLineStatus == 1)
8276 line_status = build_string ("on-line");
8277 else
8278 line_status = build_string ("N/A");
8280 if (system_status.BatteryFlag & 128)
8282 battery_status = build_string ("N/A");
8283 battery_status_symbol = empty_unibyte_string;
8285 else if (system_status.BatteryFlag & 8)
8287 battery_status = build_string ("charging");
8288 battery_status_symbol = build_string ("+");
8289 if (system_status.BatteryFullLifeTime != -1L)
8290 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
8292 else if (system_status.BatteryFlag & 4)
8294 battery_status = build_string ("critical");
8295 battery_status_symbol = build_string ("!");
8297 else if (system_status.BatteryFlag & 2)
8299 battery_status = build_string ("low");
8300 battery_status_symbol = build_string ("-");
8302 else if (system_status.BatteryFlag & 1)
8304 battery_status = build_string ("high");
8305 battery_status_symbol = empty_unibyte_string;
8307 else
8309 battery_status = build_string ("medium");
8310 battery_status_symbol = empty_unibyte_string;
8313 if (system_status.BatteryLifePercent > 100)
8314 load_percentage = build_string ("N/A");
8315 else
8317 char buffer[16];
8318 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
8319 load_percentage = build_string (buffer);
8322 if (seconds_left < 0)
8323 seconds = minutes = hours = remain = build_string ("N/A");
8324 else
8326 long m;
8327 float h;
8328 char buffer[16];
8329 snprintf (buffer, 16, "%ld", seconds_left);
8330 seconds = build_string (buffer);
8332 m = seconds_left / 60;
8333 snprintf (buffer, 16, "%ld", m);
8334 minutes = build_string (buffer);
8336 h = seconds_left / 3600.0;
8337 snprintf (buffer, 16, "%3.1f", h);
8338 hours = build_string (buffer);
8340 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
8341 remain = build_string (buffer);
8344 status = listn (CONSTYPE_HEAP, 8,
8345 Fcons (make_number ('L'), line_status),
8346 Fcons (make_number ('B'), battery_status),
8347 Fcons (make_number ('b'), battery_status_symbol),
8348 Fcons (make_number ('p'), load_percentage),
8349 Fcons (make_number ('s'), seconds),
8350 Fcons (make_number ('m'), minutes),
8351 Fcons (make_number ('h'), hours),
8352 Fcons (make_number ('t'), remain));
8354 return status;
8358 #ifdef WINDOWSNT
8359 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
8360 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8361 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
8362 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8364 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8365 doc: /* Return storage information about the file system FILENAME is on.
8366 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8367 storage of the file system, FREE is the free storage, and AVAIL is the
8368 storage available to a non-superuser. All 3 numbers are in bytes.
8369 If the underlying system call fails, value is nil. */)
8370 (Lisp_Object filename)
8372 Lisp_Object encoded, value;
8374 CHECK_STRING (filename);
8375 filename = Fexpand_file_name (filename, Qnil);
8376 encoded = ENCODE_FILE (filename);
8378 value = Qnil;
8380 /* Determining the required information on Windows turns out, sadly,
8381 to be more involved than one would hope. The original Windows API
8382 call for this will return bogus information on some systems, but we
8383 must dynamically probe for the replacement api, since that was
8384 added rather late on. */
8386 HMODULE hKernel = GetModuleHandle ("kernel32");
8387 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
8388 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
8389 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
8390 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
8391 bool have_pfn_GetDiskFreeSpaceEx =
8392 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
8393 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
8395 /* On Windows, we may need to specify the root directory of the
8396 volume holding FILENAME. */
8397 char rootname[MAX_UTF8_PATH];
8398 wchar_t rootname_w[MAX_PATH];
8399 char rootname_a[MAX_PATH];
8400 char *name = SDATA (encoded);
8401 BOOL result;
8403 /* find the root name of the volume if given */
8404 if (isalpha (name[0]) && name[1] == ':')
8406 rootname[0] = name[0];
8407 rootname[1] = name[1];
8408 rootname[2] = '\\';
8409 rootname[3] = 0;
8411 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8413 char *str = rootname;
8414 int slashes = 4;
8417 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8418 break;
8419 *str++ = *name++;
8421 while ( *name );
8423 *str++ = '\\';
8424 *str = 0;
8427 if (w32_unicode_filenames)
8428 filename_to_utf16 (rootname, rootname_w);
8429 else
8430 filename_to_ansi (rootname, rootname_a);
8432 if (have_pfn_GetDiskFreeSpaceEx)
8434 /* Unsigned large integers cannot be cast to double, so
8435 use signed ones instead. */
8436 LARGE_INTEGER availbytes;
8437 LARGE_INTEGER freebytes;
8438 LARGE_INTEGER totalbytes;
8440 if (w32_unicode_filenames)
8441 result = pfn_GetDiskFreeSpaceExW (rootname_w,
8442 (ULARGE_INTEGER *)&availbytes,
8443 (ULARGE_INTEGER *)&totalbytes,
8444 (ULARGE_INTEGER *)&freebytes);
8445 else
8446 result = pfn_GetDiskFreeSpaceExA (rootname_a,
8447 (ULARGE_INTEGER *)&availbytes,
8448 (ULARGE_INTEGER *)&totalbytes,
8449 (ULARGE_INTEGER *)&freebytes);
8450 if (result)
8451 value = list3 (make_float ((double) totalbytes.QuadPart),
8452 make_float ((double) freebytes.QuadPart),
8453 make_float ((double) availbytes.QuadPart));
8455 else
8457 DWORD sectors_per_cluster;
8458 DWORD bytes_per_sector;
8459 DWORD free_clusters;
8460 DWORD total_clusters;
8462 if (w32_unicode_filenames)
8463 result = GetDiskFreeSpaceW (rootname_w,
8464 &sectors_per_cluster,
8465 &bytes_per_sector,
8466 &free_clusters,
8467 &total_clusters);
8468 else
8469 result = GetDiskFreeSpaceA (rootname_a,
8470 &sectors_per_cluster,
8471 &bytes_per_sector,
8472 &free_clusters,
8473 &total_clusters);
8474 if (result)
8475 value = list3 (make_float ((double) total_clusters
8476 * sectors_per_cluster * bytes_per_sector),
8477 make_float ((double) free_clusters
8478 * sectors_per_cluster * bytes_per_sector),
8479 make_float ((double) free_clusters
8480 * sectors_per_cluster * bytes_per_sector));
8484 return value;
8486 #endif /* WINDOWSNT */
8489 #ifdef WINDOWSNT
8490 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8491 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8492 (void)
8494 static char pname_buf[256];
8495 int err;
8496 HANDLE hPrn;
8497 PRINTER_INFO_2W *ppi2w = NULL;
8498 PRINTER_INFO_2A *ppi2a = NULL;
8499 DWORD dwNeeded = 0, dwReturned = 0;
8500 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
8501 char port_name[MAX_UTF8_PATH];
8503 /* Retrieve the default string from Win.ini (the registry).
8504 * String will be in form "printername,drivername,portname".
8505 * This is the most portable way to get the default printer. */
8506 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8507 return Qnil;
8508 /* printername precedes first "," character */
8509 strtok (pname_buf, ",");
8510 /* We want to know more than the printer name */
8511 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8512 return Qnil;
8513 /* GetPrinterW is not supported by unicows.dll. */
8514 if (w32_unicode_filenames && os_subtype != OS_9X)
8515 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
8516 else
8517 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
8518 if (dwNeeded == 0)
8520 ClosePrinter (hPrn);
8521 return Qnil;
8523 /* Call GetPrinter again with big enough memory block. */
8524 if (w32_unicode_filenames && os_subtype != OS_9X)
8526 /* Allocate memory for the PRINTER_INFO_2 struct. */
8527 ppi2w = xmalloc (dwNeeded);
8528 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
8529 ClosePrinter (hPrn);
8530 if (!err)
8532 xfree (ppi2w);
8533 return Qnil;
8536 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
8537 && ppi2w->pServerName)
8539 filename_from_utf16 (ppi2w->pServerName, server_name);
8540 filename_from_utf16 (ppi2w->pShareName, share_name);
8542 else
8544 server_name[0] = '\0';
8545 filename_from_utf16 (ppi2w->pPortName, port_name);
8548 else
8550 ppi2a = xmalloc (dwNeeded);
8551 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
8552 ClosePrinter (hPrn);
8553 if (!err)
8555 xfree (ppi2a);
8556 return Qnil;
8559 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
8560 && ppi2a->pServerName)
8562 filename_from_ansi (ppi2a->pServerName, server_name);
8563 filename_from_ansi (ppi2a->pShareName, share_name);
8565 else
8567 server_name[0] = '\0';
8568 filename_from_ansi (ppi2a->pPortName, port_name);
8572 if (server_name[0])
8574 /* a remote printer */
8575 if (server_name[0] == '\\')
8576 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
8577 share_name);
8578 else
8579 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
8580 share_name);
8581 pname_buf[sizeof (pname_buf) - 1] = '\0';
8583 else
8585 /* a local printer */
8586 strncpy (pname_buf, port_name, sizeof (pname_buf));
8587 pname_buf[sizeof (pname_buf) - 1] = '\0';
8588 /* `pPortName' can include several ports, delimited by ','.
8589 * we only use the first one. */
8590 strtok (pname_buf, ",");
8593 return DECODE_FILE (build_unibyte_string (pname_buf));
8595 #endif /* WINDOWSNT */
8598 /* Equivalent of strerror for W32 error codes. */
8599 char *
8600 w32_strerror (int error_no)
8602 static char buf[500];
8603 DWORD ret;
8605 if (error_no == 0)
8606 error_no = GetLastError ();
8608 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
8609 FORMAT_MESSAGE_IGNORE_INSERTS,
8610 NULL,
8611 error_no,
8612 0, /* choose most suitable language */
8613 buf, sizeof (buf), NULL);
8615 while (ret > 0 && (buf[ret - 1] == '\n' ||
8616 buf[ret - 1] == '\r' ))
8617 --ret;
8618 buf[ret] = '\0';
8619 if (!ret)
8620 sprintf (buf, "w32 error %u", error_no);
8622 return buf;
8625 /* For convenience when debugging. (You cannot call GetLastError
8626 directly from GDB: it will crash, because it uses the __stdcall
8627 calling convention, not the _cdecl convention assumed by GDB.) */
8628 DWORD
8629 w32_last_error (void)
8631 return GetLastError ();
8634 /* Cache information describing the NT system for later use. */
8635 void
8636 cache_system_info (void)
8638 union
8640 struct info
8642 char major;
8643 char minor;
8644 short platform;
8645 } info;
8646 DWORD data;
8647 } version;
8649 /* Cache the module handle of Emacs itself. */
8650 hinst = GetModuleHandle (NULL);
8652 /* Cache the version of the operating system. */
8653 version.data = GetVersion ();
8654 w32_major_version = version.info.major;
8655 w32_minor_version = version.info.minor;
8657 if (version.info.platform & 0x8000)
8658 os_subtype = OS_9X;
8659 else
8660 os_subtype = OS_NT;
8662 /* Cache page size, allocation unit, processor type, etc. */
8663 GetSystemInfo (&sysinfo_cache);
8664 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
8666 /* Cache os info. */
8667 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
8668 GetVersionEx (&osinfo_cache);
8670 w32_build_number = osinfo_cache.dwBuildNumber;
8671 if (os_subtype == OS_9X)
8672 w32_build_number &= 0xffff;
8674 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
8677 #ifdef EMACSDEBUG
8678 void
8679 _DebPrint (const char *fmt, ...)
8681 char buf[1024];
8682 va_list args;
8684 va_start (args, fmt);
8685 vsprintf (buf, fmt, args);
8686 va_end (args);
8687 #if CYGWIN
8688 fprintf (stderr, "%s", buf);
8689 #endif
8690 OutputDebugString (buf);
8692 #endif
8695 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
8697 int cur_state = (GetKeyState (vk_code) & 1);
8699 if (NILP (new_state)
8700 || (NUMBERP (new_state)
8701 && ((XUINT (new_state)) & 1) != cur_state))
8703 #ifdef WINDOWSNT
8704 faked_key = vk_code;
8705 #endif /* WINDOWSNT */
8707 keybd_event ((BYTE) vk_code,
8708 (BYTE) MapVirtualKey (vk_code, 0),
8709 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8710 keybd_event ((BYTE) vk_code,
8711 (BYTE) MapVirtualKey (vk_code, 0),
8712 KEYEVENTF_EXTENDEDKEY | 0, 0);
8713 keybd_event ((BYTE) vk_code,
8714 (BYTE) MapVirtualKey (vk_code, 0),
8715 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8716 cur_state = !cur_state;
8719 return cur_state;
8722 /* Translate console modifiers to emacs modifiers.
8723 German keyboard support (Kai Morgan Zeise 2/18/95). */
8725 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
8727 int retval = 0;
8729 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
8730 pressed, first remove those modifiers. */
8731 if (!NILP (Vw32_recognize_altgr)
8732 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8733 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8734 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
8736 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
8737 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
8739 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8741 retval |= ctrl_modifier;
8742 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8743 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8744 retval |= meta_modifier;
8747 if (mods & LEFT_WIN_PRESSED)
8748 retval |= w32_key_to_modifier (VK_LWIN);
8749 if (mods & RIGHT_WIN_PRESSED)
8750 retval |= w32_key_to_modifier (VK_RWIN);
8751 if (mods & APPS_PRESSED)
8752 retval |= w32_key_to_modifier (VK_APPS);
8753 if (mods & SCROLLLOCK_ON)
8754 retval |= w32_key_to_modifier (VK_SCROLL);
8756 /* Just in case someone wanted the original behavior, make it
8757 optional by setting w32-capslock-is-shiftlock to t. */
8758 if (NILP (Vw32_capslock_is_shiftlock)
8759 /* Keys that should _not_ be affected by CapsLock. */
8760 && ( (key == VK_BACK)
8761 || (key == VK_TAB)
8762 || (key == VK_CLEAR)
8763 || (key == VK_RETURN)
8764 || (key == VK_ESCAPE)
8765 || ((key >= VK_SPACE) && (key <= VK_HELP))
8766 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
8767 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
8770 /* Only consider shift state. */
8771 if ((mods & SHIFT_PRESSED) != 0)
8772 retval |= shift_modifier;
8774 else
8776 /* Ignore CapsLock state if not enabled. */
8777 if (NILP (Vw32_enable_caps_lock))
8778 mods &= ~CAPSLOCK_ON;
8779 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
8780 retval |= shift_modifier;
8783 return retval;
8786 /* The return code indicates key code size. cpID is the codepage to
8787 use for translation to Unicode; -1 means use the current console
8788 input codepage. */
8790 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
8792 unsigned int key_code = event->wVirtualKeyCode;
8793 unsigned int mods = event->dwControlKeyState;
8794 BYTE keystate[256];
8795 static BYTE ansi_code[4];
8796 static int isdead = 0;
8798 if (isdead == 2)
8800 event->uChar.AsciiChar = ansi_code[2];
8801 isdead = 0;
8802 return 1;
8804 if (event->uChar.AsciiChar != 0)
8805 return 1;
8807 memset (keystate, 0, sizeof (keystate));
8808 keystate[key_code] = 0x80;
8809 if (mods & SHIFT_PRESSED)
8810 keystate[VK_SHIFT] = 0x80;
8811 if (mods & CAPSLOCK_ON)
8812 keystate[VK_CAPITAL] = 1;
8813 /* If we recognize right-alt and left-ctrl as AltGr, set the key
8814 states accordingly before invoking ToAscii. */
8815 if (!NILP (Vw32_recognize_altgr)
8816 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
8818 keystate[VK_CONTROL] = 0x80;
8819 keystate[VK_LCONTROL] = 0x80;
8820 keystate[VK_MENU] = 0x80;
8821 keystate[VK_RMENU] = 0x80;
8824 #if 0
8825 /* Because of an OS bug, ToAscii corrupts the stack when called to
8826 convert a dead key in console mode on NT4. Unfortunately, trying
8827 to check for dead keys using MapVirtualKey doesn't work either -
8828 these functions apparently use internal information about keyboard
8829 layout which doesn't get properly updated in console programs when
8830 changing layout (though apparently it gets partly updated,
8831 otherwise ToAscii wouldn't crash). */
8832 if (is_dead_key (event->wVirtualKeyCode))
8833 return 0;
8834 #endif
8836 /* On NT, call ToUnicode instead and then convert to the current
8837 console input codepage. */
8838 if (os_subtype == OS_NT)
8840 WCHAR buf[128];
8842 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
8843 keystate, buf, 128, 0);
8844 if (isdead > 0)
8846 /* When we are called from the GUI message processing code,
8847 we are passed the current keyboard codepage, a positive
8848 number, to use below. */
8849 if (cpId == -1)
8850 cpId = GetConsoleCP ();
8852 event->uChar.UnicodeChar = buf[isdead - 1];
8853 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8854 ansi_code, 4, NULL, NULL);
8856 else
8857 isdead = 0;
8859 else
8861 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8862 keystate, (LPWORD) ansi_code, 0);
8865 if (isdead == 0)
8866 return 0;
8867 event->uChar.AsciiChar = ansi_code[0];
8868 return isdead;
8872 void
8873 w32_sys_ring_bell (struct frame *f)
8875 if (sound_type == 0xFFFFFFFF)
8877 Beep (666, 100);
8879 else if (sound_type == MB_EMACS_SILENT)
8881 /* Do nothing. */
8883 else
8884 MessageBeep (sound_type);
8887 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
8888 0, 0, 0,
8889 doc: /* Return non-nil when a menu-bar menu is being used.
8890 Internal use only. */)
8891 (void)
8893 return menubar_in_use ? Qt : Qnil;
8897 /***********************************************************************
8898 Initialization
8899 ***********************************************************************/
8901 /* Keep this list in the same order as frame_parms in frame.c.
8902 Use 0 for unsupported frame parameters. */
8904 frame_parm_handler w32_frame_parm_handlers[] =
8906 x_set_autoraise,
8907 x_set_autolower,
8908 x_set_background_color,
8909 x_set_border_color,
8910 x_set_border_width,
8911 x_set_cursor_color,
8912 x_set_cursor_type,
8913 x_set_font,
8914 x_set_foreground_color,
8915 x_set_icon_name,
8916 x_set_icon_type,
8917 x_set_internal_border_width,
8918 x_set_right_divider_width,
8919 x_set_bottom_divider_width,
8920 x_set_menu_bar_lines,
8921 x_set_mouse_color,
8922 x_explicitly_set_name,
8923 x_set_scroll_bar_width,
8924 x_set_scroll_bar_height,
8925 x_set_title,
8926 x_set_unsplittable,
8927 x_set_vertical_scroll_bars,
8928 x_set_horizontal_scroll_bars,
8929 x_set_visibility,
8930 x_set_tool_bar_lines,
8931 0, /* x_set_scroll_bar_foreground, */
8932 0, /* x_set_scroll_bar_background, */
8933 x_set_screen_gamma,
8934 x_set_line_spacing,
8935 x_set_left_fringe,
8936 x_set_right_fringe,
8937 0, /* x_set_wait_for_wm, */
8938 x_set_fullscreen,
8939 x_set_font_backend,
8940 x_set_alpha,
8941 0, /* x_set_sticky */
8942 0, /* x_set_tool_bar_position */
8945 void
8946 syms_of_w32fns (void)
8948 globals_of_w32fns ();
8949 track_mouse_window = NULL;
8951 w32_visible_system_caret_hwnd = NULL;
8953 DEFSYM (Qundefined_color, "undefined-color");
8954 DEFSYM (Qcancel_timer, "cancel-timer");
8955 DEFSYM (Qhyper, "hyper");
8956 DEFSYM (Qsuper, "super");
8957 DEFSYM (Qmeta, "meta");
8958 DEFSYM (Qalt, "alt");
8959 DEFSYM (Qctrl, "ctrl");
8960 DEFSYM (Qcontrol, "control");
8961 DEFSYM (Qshift, "shift");
8962 DEFSYM (Qfont_param, "font-parameter");
8963 DEFSYM (Qgeometry, "geometry");
8964 DEFSYM (Qworkarea, "workarea");
8965 DEFSYM (Qmm_size, "mm-size");
8966 DEFSYM (Qframes, "frames");
8967 DEFSYM (Qtip_frame, "tip-frame");
8968 DEFSYM (Qunicode_sip, "unicode-sip");
8970 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
8971 DEFSYM (Qgnutls_dll, "gnutls");
8972 DEFSYM (Qlibxml2_dll, "libxml2");
8973 DEFSYM (Qserif, "serif");
8974 DEFSYM (Qzlib_dll, "zlib");
8976 Fput (Qundefined_color, Qerror_conditions,
8977 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8978 Fput (Qundefined_color, Qerror_message,
8979 build_pure_c_string ("Undefined color"));
8981 staticpro (&w32_grabbed_keys);
8982 w32_grabbed_keys = Qnil;
8984 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8985 doc: /* An array of color name mappings for Windows. */);
8986 Vw32_color_map = Qnil;
8988 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8989 doc: /* Non-nil if Alt key presses are passed on to Windows.
8990 When non-nil, for example, Alt pressed and released and then space will
8991 open the System menu. When nil, Emacs processes the Alt key events, and
8992 then silently swallows them. */);
8993 Vw32_pass_alt_to_system = Qnil;
8995 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8996 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8997 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8998 Vw32_alt_is_meta = Qt;
9000 DEFVAR_INT ("w32-quit-key", w32_quit_key,
9001 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
9002 w32_quit_key = 0;
9004 DEFVAR_LISP ("w32-pass-lwindow-to-system",
9005 Vw32_pass_lwindow_to_system,
9006 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
9008 When non-nil, the Start menu is opened by tapping the key.
9009 If you set this to nil, the left \"Windows\" key is processed by Emacs
9010 according to the value of `w32-lwindow-modifier', which see.
9012 Note that some combinations of the left \"Windows\" key with other keys are
9013 caught by Windows at low level, and so binding them in Emacs will have no
9014 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
9015 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
9016 the doc string of `w32-phantom-key-code'. */);
9017 Vw32_pass_lwindow_to_system = Qt;
9019 DEFVAR_LISP ("w32-pass-rwindow-to-system",
9020 Vw32_pass_rwindow_to_system,
9021 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
9023 When non-nil, the Start menu is opened by tapping the key.
9024 If you set this to nil, the right \"Windows\" key is processed by Emacs
9025 according to the value of `w32-rwindow-modifier', which see.
9027 Note that some combinations of the right \"Windows\" key with other keys are
9028 caught by Windows at low level, and so binding them in Emacs will have no
9029 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
9030 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
9031 the doc string of `w32-phantom-key-code'. */);
9032 Vw32_pass_rwindow_to_system = Qt;
9034 DEFVAR_LISP ("w32-phantom-key-code",
9035 Vw32_phantom_key_code,
9036 doc: /* Virtual key code used to generate \"phantom\" key presses.
9037 Value is a number between 0 and 255.
9039 Phantom key presses are generated in order to stop the system from
9040 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
9041 `w32-pass-rwindow-to-system' is nil. */);
9042 /* Although 255 is technically not a valid key code, it works and
9043 means that this hack won't interfere with any real key code. */
9044 XSETINT (Vw32_phantom_key_code, 255);
9046 DEFVAR_LISP ("w32-enable-num-lock",
9047 Vw32_enable_num_lock,
9048 doc: /* If non-nil, the Num Lock key acts normally.
9049 Set to nil to handle Num Lock as the `kp-numlock' key. */);
9050 Vw32_enable_num_lock = Qt;
9052 DEFVAR_LISP ("w32-enable-caps-lock",
9053 Vw32_enable_caps_lock,
9054 doc: /* If non-nil, the Caps Lock key acts normally.
9055 Set to nil to handle Caps Lock as the `capslock' key. */);
9056 Vw32_enable_caps_lock = Qt;
9058 DEFVAR_LISP ("w32-scroll-lock-modifier",
9059 Vw32_scroll_lock_modifier,
9060 doc: /* Modifier to use for the Scroll Lock ON state.
9061 The value can be hyper, super, meta, alt, control or shift for the
9062 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
9063 Any other value will cause the Scroll Lock key to be ignored. */);
9064 Vw32_scroll_lock_modifier = Qnil;
9066 DEFVAR_LISP ("w32-lwindow-modifier",
9067 Vw32_lwindow_modifier,
9068 doc: /* Modifier to use for the left \"Windows\" key.
9069 The value can be hyper, super, meta, alt, control or shift for the
9070 respective modifier, or nil to appear as the `lwindow' key.
9071 Any other value will cause the key to be ignored. */);
9072 Vw32_lwindow_modifier = Qnil;
9074 DEFVAR_LISP ("w32-rwindow-modifier",
9075 Vw32_rwindow_modifier,
9076 doc: /* Modifier to use for the right \"Windows\" key.
9077 The value can be hyper, super, meta, alt, control or shift for the
9078 respective modifier, or nil to appear as the `rwindow' key.
9079 Any other value will cause the key to be ignored. */);
9080 Vw32_rwindow_modifier = Qnil;
9082 DEFVAR_LISP ("w32-apps-modifier",
9083 Vw32_apps_modifier,
9084 doc: /* Modifier to use for the \"Apps\" key.
9085 The value can be hyper, super, meta, alt, control or shift for the
9086 respective modifier, or nil to appear as the `apps' key.
9087 Any other value will cause the key to be ignored. */);
9088 Vw32_apps_modifier = Qnil;
9090 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
9091 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
9092 w32_enable_synthesized_fonts = 0;
9094 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
9095 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
9096 Vw32_enable_palette = Qt;
9098 DEFVAR_INT ("w32-mouse-button-tolerance",
9099 w32_mouse_button_tolerance,
9100 doc: /* Analogue of double click interval for faking middle mouse events.
9101 The value is the minimum time in milliseconds that must elapse between
9102 left and right button down events before they are considered distinct events.
9103 If both mouse buttons are depressed within this interval, a middle mouse
9104 button down event is generated instead. */);
9105 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
9107 DEFVAR_INT ("w32-mouse-move-interval",
9108 w32_mouse_move_interval,
9109 doc: /* Minimum interval between mouse move events.
9110 The value is the minimum time in milliseconds that must elapse between
9111 successive mouse move (or scroll bar drag) events before they are
9112 reported as lisp events. */);
9113 w32_mouse_move_interval = 0;
9115 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
9116 w32_pass_extra_mouse_buttons_to_system,
9117 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
9118 Recent versions of Windows support mice with up to five buttons.
9119 Since most applications don't support these extra buttons, most mouse
9120 drivers will allow you to map them to functions at the system level.
9121 If this variable is non-nil, Emacs will pass them on, allowing the
9122 system to handle them. */);
9123 w32_pass_extra_mouse_buttons_to_system = 0;
9125 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
9126 w32_pass_multimedia_buttons_to_system,
9127 doc: /* If non-nil, media buttons are passed to Windows.
9128 Some modern keyboards contain buttons for controlling media players, web
9129 browsers and other applications. Generally these buttons are handled on a
9130 system wide basis, but by setting this to nil they are made available
9131 to Emacs for binding. Depending on your keyboard, additional keys that
9132 may be available are:
9134 browser-back, browser-forward, browser-refresh, browser-stop,
9135 browser-search, browser-favorites, browser-home,
9136 mail, mail-reply, mail-forward, mail-send,
9137 app-1, app-2,
9138 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
9139 spell-check, correction-list, toggle-dictate-command,
9140 media-next, media-previous, media-stop, media-play-pause, media-select,
9141 media-play, media-pause, media-record, media-fast-forward, media-rewind,
9142 media-channel-up, media-channel-down,
9143 volume-mute, volume-up, volume-down,
9144 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
9145 bass-down, bass-boost, bass-up, treble-down, treble-up */);
9146 w32_pass_multimedia_buttons_to_system = 1;
9148 #if 0 /* TODO: Mouse cursor customization. */
9149 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
9150 doc: /* The shape of the pointer when over text.
9151 Changing the value does not affect existing frames
9152 unless you set the mouse color. */);
9153 Vx_pointer_shape = Qnil;
9155 Vx_nontext_pointer_shape = Qnil;
9157 Vx_mode_pointer_shape = Qnil;
9159 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
9160 doc: /* The shape of the pointer when Emacs is busy.
9161 This variable takes effect when you create a new frame
9162 or when you set the mouse color. */);
9163 Vx_hourglass_pointer_shape = Qnil;
9165 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
9166 Vx_sensitive_text_pointer_shape,
9167 doc: /* The shape of the pointer when over mouse-sensitive text.
9168 This variable takes effect when you create a new frame
9169 or when you set the mouse color. */);
9170 Vx_sensitive_text_pointer_shape = Qnil;
9172 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
9173 Vx_window_horizontal_drag_shape,
9174 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
9175 This variable takes effect when you create a new frame
9176 or when you set the mouse color. */);
9177 Vx_window_horizontal_drag_shape = Qnil;
9179 DEFVAR_LISP ("x-window-vertical-drag-cursor",
9180 Vx_window_vertical_drag_shape,
9181 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
9182 This variable takes effect when you create a new frame
9183 or when you set the mouse color. */);
9184 Vx_window_vertical_drag_shape = Qnil;
9185 #endif
9187 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
9188 doc: /* A string indicating the foreground color of the cursor box. */);
9189 Vx_cursor_fore_pixel = Qnil;
9191 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
9192 doc: /* Maximum size for tooltips.
9193 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
9194 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
9196 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
9197 doc: /* Non-nil if no window manager is in use.
9198 Emacs doesn't try to figure this out; this is always nil
9199 unless you set it to something else. */);
9200 /* We don't have any way to find this out, so set it to nil
9201 and maybe the user would like to set it to t. */
9202 Vx_no_window_manager = Qnil;
9204 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
9205 Vx_pixel_size_width_font_regexp,
9206 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
9208 Since Emacs gets width of a font matching with this regexp from
9209 PIXEL_SIZE field of the name, font finding mechanism gets faster for
9210 such a font. This is especially effective for such large fonts as
9211 Chinese, Japanese, and Korean. */);
9212 Vx_pixel_size_width_font_regexp = Qnil;
9214 DEFVAR_LISP ("w32-bdf-filename-alist",
9215 Vw32_bdf_filename_alist,
9216 doc: /* List of bdf fonts and their corresponding filenames. */);
9217 Vw32_bdf_filename_alist = Qnil;
9219 DEFVAR_BOOL ("w32-strict-fontnames",
9220 w32_strict_fontnames,
9221 doc: /* Non-nil means only use fonts that are exact matches for those requested.
9222 Default is nil, which allows old fontnames that are not XLFD compliant,
9223 and allows third-party CJK display to work by specifying false charset
9224 fields to trick Emacs into translating to Big5, SJIS etc.
9225 Setting this to t will prevent wrong fonts being selected when
9226 fontsets are automatically created. */);
9227 w32_strict_fontnames = 0;
9229 DEFVAR_BOOL ("w32-strict-painting",
9230 w32_strict_painting,
9231 doc: /* Non-nil means use strict rules for repainting frames.
9232 Set this to nil to get the old behavior for repainting; this should
9233 only be necessary if the default setting causes problems. */);
9234 w32_strict_painting = 1;
9236 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
9237 w32_use_fallback_wm_chars_method,
9238 doc: /* Non-nil means use old method of processing character keys.
9239 This is intended only for debugging of the new processing method.
9240 Default is nil.
9242 This variable has effect only on NT family of systems, not on Windows 9X. */);
9243 w32_use_fallback_wm_chars_method = 0;
9245 #if 0 /* TODO: Port to W32 */
9246 defsubr (&Sx_change_window_property);
9247 defsubr (&Sx_delete_window_property);
9248 defsubr (&Sx_window_property);
9249 #endif
9250 defsubr (&Sxw_display_color_p);
9251 defsubr (&Sx_display_grayscale_p);
9252 defsubr (&Sxw_color_defined_p);
9253 defsubr (&Sxw_color_values);
9254 defsubr (&Sx_server_max_request_size);
9255 defsubr (&Sx_server_vendor);
9256 defsubr (&Sx_server_version);
9257 defsubr (&Sx_display_pixel_width);
9258 defsubr (&Sx_display_pixel_height);
9259 defsubr (&Sx_display_mm_width);
9260 defsubr (&Sx_display_mm_height);
9261 defsubr (&Sx_display_screens);
9262 defsubr (&Sx_display_planes);
9263 defsubr (&Sx_display_color_cells);
9264 defsubr (&Sx_display_visual_class);
9265 defsubr (&Sx_display_backing_store);
9266 defsubr (&Sx_display_save_under);
9267 defsubr (&Sx_create_frame);
9268 defsubr (&Sx_open_connection);
9269 defsubr (&Sx_close_connection);
9270 defsubr (&Sx_display_list);
9271 defsubr (&Sx_frame_geometry);
9272 defsubr (&Sx_frame_edges);
9273 defsubr (&Sx_mouse_absolute_pixel_position);
9274 defsubr (&Sx_set_mouse_absolute_pixel_position);
9275 defsubr (&Sx_synchronize);
9277 /* W32 specific functions */
9279 defsubr (&Sw32_define_rgb_color);
9280 defsubr (&Sw32_default_color_map);
9281 defsubr (&Sw32_display_monitor_attributes_list);
9282 defsubr (&Sw32_send_sys_command);
9283 defsubr (&Sw32_shell_execute);
9284 defsubr (&Sw32_register_hot_key);
9285 defsubr (&Sw32_unregister_hot_key);
9286 defsubr (&Sw32_registered_hot_keys);
9287 defsubr (&Sw32_reconstruct_hot_key);
9288 defsubr (&Sw32_toggle_lock_key);
9289 defsubr (&Sw32_window_exists_p);
9290 defsubr (&Sw32_battery_status);
9291 defsubr (&Sw32__menu_bar_in_use);
9293 #ifdef WINDOWSNT
9294 defsubr (&Sfile_system_info);
9295 defsubr (&Sdefault_printer_name);
9296 #endif
9298 defsubr (&Sset_message_beep);
9299 defsubr (&Sx_show_tip);
9300 defsubr (&Sx_hide_tip);
9301 tip_timer = Qnil;
9302 staticpro (&tip_timer);
9303 tip_frame = Qnil;
9304 staticpro (&tip_frame);
9306 last_show_tip_args = Qnil;
9307 staticpro (&last_show_tip_args);
9309 defsubr (&Sx_file_dialog);
9310 #ifdef WINDOWSNT
9311 defsubr (&Ssystem_move_file_to_trash);
9312 #endif
9317 /* Crashing and reporting backtrace. */
9319 #ifndef CYGWIN
9320 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
9321 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
9322 #endif
9323 static DWORD except_code;
9324 static PVOID except_addr;
9326 #ifndef CYGWIN
9328 /* Stack overflow recovery. */
9330 /* Re-establish the guard page at stack limit. This is needed because
9331 when a stack overflow is detected, Windows removes the guard bit
9332 from the guard page, so if we don't re-establish that protection,
9333 the next stack overflow will cause a crash. */
9334 void
9335 w32_reset_stack_overflow_guard (void)
9337 /* MinGW headers don't declare this (should be in malloc.h). */
9338 _CRTIMP int __cdecl _resetstkoflw (void);
9340 /* We ignore the return value. If _resetstkoflw fails, the next
9341 stack overflow will crash the program. */
9342 (void)_resetstkoflw ();
9345 static void
9346 stack_overflow_handler (void)
9348 /* Hard GC error may lead to stack overflow caused by
9349 too nested calls to mark_object. No way to survive. */
9350 if (gc_in_progress)
9351 terminate_due_to_signal (SIGSEGV, 40);
9352 #ifdef _WIN64
9353 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
9354 __builtin_longjmp (return_to_command_loop, 1);
9355 #else
9356 sys_longjmp (return_to_command_loop, 1);
9357 #endif
9360 /* This handler records the exception code and the address where it
9361 was triggered so that this info could be included in the backtrace.
9362 Without that, the backtrace in some cases has no information
9363 whatsoever about the offending code, and looks as if the top-level
9364 exception handler in the MinGW startup code was the one that
9365 crashed. We also recover from stack overflow, by calling our stack
9366 overflow handler that jumps back to top level. */
9367 static LONG CALLBACK
9368 my_exception_handler (EXCEPTION_POINTERS * exception_data)
9370 except_code = exception_data->ExceptionRecord->ExceptionCode;
9371 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
9373 /* If this is a stack overflow exception, attempt to recover. */
9374 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
9375 && exception_data->ExceptionRecord->NumberParameters == 2
9376 /* We can only longjmp to top level from the main thread. */
9377 && GetCurrentThreadId () == dwMainThreadId)
9379 /* Call stack_overflow_handler (). */
9380 #ifdef _WIN64
9381 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
9382 #else
9383 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
9384 #endif
9385 /* Zero this out, so the stale address of the stack overflow
9386 exception we handled is not displayed in some future
9387 unrelated crash. */
9388 except_addr = 0;
9389 return EXCEPTION_CONTINUE_EXECUTION;
9392 if (prev_exception_handler)
9393 return prev_exception_handler (exception_data);
9394 return EXCEPTION_EXECUTE_HANDLER;
9396 #endif
9398 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
9399 PULONG);
9401 #define BACKTRACE_LIMIT_MAX 62
9404 w32_backtrace (void **buffer, int limit)
9406 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
9407 HMODULE hm_kernel32 = NULL;
9409 if (!s_pfn_CaptureStackBackTrace)
9411 hm_kernel32 = LoadLibrary ("Kernel32.dll");
9412 s_pfn_CaptureStackBackTrace =
9413 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
9414 "RtlCaptureStackBackTrace");
9416 if (s_pfn_CaptureStackBackTrace)
9417 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
9418 buffer, NULL);
9419 return 0;
9422 void
9423 emacs_abort (void)
9425 int button;
9426 button = MessageBox (NULL,
9427 "A fatal error has occurred!\n\n"
9428 "Would you like to attach a debugger?\n\n"
9429 "Select:\n"
9430 "YES -- to debug Emacs, or\n"
9431 "NO -- to abort Emacs and produce a backtrace\n"
9432 " (emacs_backtrace.txt in current directory)."
9433 #if __GNUC__
9434 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
9435 "\"continue\" inside GDB before clicking YES.)"
9436 #endif
9437 , "Emacs Abort Dialog",
9438 MB_ICONEXCLAMATION | MB_TASKMODAL
9439 | MB_SETFOREGROUND | MB_YESNO);
9440 switch (button)
9442 case IDYES:
9443 DebugBreak ();
9444 exit (2); /* tell the compiler we will never return */
9445 case IDNO:
9446 default:
9448 void *stack[BACKTRACE_LIMIT_MAX + 1];
9449 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
9451 if (i)
9453 int errfile_fd = -1;
9454 int j;
9455 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
9456 /* The type below should really be 'void *', but
9457 INT_BUFSIZE_BOUND cannot handle that without
9458 triggering compiler warnings (under certain
9459 pedantic warning switches), it wants an
9460 integer type. */
9461 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
9462 #ifdef CYGWIN
9463 int stderr_fd = 2;
9464 #else
9465 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
9466 int stderr_fd = -1;
9468 if (errout && errout != INVALID_HANDLE_VALUE)
9469 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
9470 #endif
9472 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
9473 but not on Windows 7. addr2line doesn't mind a missing
9474 "0x", but will be confused by an extra one. */
9475 if (except_addr)
9476 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
9477 except_code, except_addr);
9478 if (stderr_fd >= 0)
9480 if (except_addr)
9481 write (stderr_fd, buf, strlen (buf));
9482 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
9484 #ifdef CYGWIN
9485 #define _open open
9486 #endif
9487 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
9488 if (errfile_fd >= 0)
9490 lseek (errfile_fd, 0L, SEEK_END);
9491 if (except_addr)
9492 write (errfile_fd, buf, strlen (buf));
9493 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
9496 for (j = 0; j < i; j++)
9498 /* stack[] gives the return addresses, whereas we want
9499 the address of the call, so decrease each address
9500 by approximate size of 1 CALL instruction. */
9501 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
9502 if (stderr_fd >= 0)
9503 write (stderr_fd, buf, strlen (buf));
9504 if (errfile_fd >= 0)
9505 write (errfile_fd, buf, strlen (buf));
9507 if (i == BACKTRACE_LIMIT_MAX)
9509 if (stderr_fd >= 0)
9510 write (stderr_fd, "...\r\n", 5);
9511 if (errfile_fd >= 0)
9512 write (errfile_fd, "...\r\n", 5);
9514 if (errfile_fd >= 0)
9515 close (errfile_fd);
9517 abort ();
9518 break;
9525 /* Initialization. */
9528 globals_of_w32fns is used to initialize those global variables that
9529 must always be initialized on startup even when the global variable
9530 initialized is non zero (see the function main in emacs.c).
9531 globals_of_w32fns is called from syms_of_w32fns when the global
9532 variable initialized is 0 and directly from main when initialized
9533 is non zero.
9535 void
9536 globals_of_w32fns (void)
9538 HMODULE user32_lib = GetModuleHandle ("user32.dll");
9540 TrackMouseEvent not available in all versions of Windows, so must load
9541 it dynamically. Do it once, here, instead of every time it is used.
9543 track_mouse_event_fn = (TrackMouseEvent_Proc)
9544 GetProcAddress (user32_lib, "TrackMouseEvent");
9546 monitor_from_point_fn = (MonitorFromPoint_Proc)
9547 GetProcAddress (user32_lib, "MonitorFromPoint");
9548 get_monitor_info_fn = (GetMonitorInfo_Proc)
9549 GetProcAddress (user32_lib, "GetMonitorInfoA");
9550 monitor_from_window_fn = (MonitorFromWindow_Proc)
9551 GetProcAddress (user32_lib, "MonitorFromWindow");
9552 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
9553 GetProcAddress (user32_lib, "EnumDisplayMonitors");
9554 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
9555 GetProcAddress (user32_lib, "GetTitleBarInfo");
9558 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
9559 get_composition_string_fn = (ImmGetCompositionString_Proc)
9560 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
9561 get_ime_context_fn = (ImmGetContext_Proc)
9562 GetProcAddress (imm32_lib, "ImmGetContext");
9563 release_ime_context_fn = (ImmReleaseContext_Proc)
9564 GetProcAddress (imm32_lib, "ImmReleaseContext");
9565 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
9566 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
9569 except_code = 0;
9570 except_addr = 0;
9571 #ifndef CYGWIN
9572 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
9573 #endif
9575 DEFVAR_INT ("w32-ansi-code-page",
9576 w32_ansi_code_page,
9577 doc: /* The ANSI code page used by the system. */);
9578 w32_ansi_code_page = GetACP ();
9580 if (os_subtype == OS_NT)
9581 w32_unicode_gui = 1;
9582 else
9583 w32_unicode_gui = 0;
9585 after_deadkey = -1;
9587 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
9588 InitCommonControls ();
9590 syms_of_w32uniscribe ();
9592 /* Needed for recovery from C stack overflows in batch mode. */
9593 if (noninteractive)
9594 dwMainThreadId = GetCurrentThreadId ();
9597 #ifdef NTGUI_UNICODE
9599 Lisp_Object
9600 ntgui_encode_system (Lisp_Object str)
9602 Lisp_Object encoded;
9603 to_unicode (str, &encoded);
9604 return encoded;
9607 #endif /* NTGUI_UNICODE */