Assume GC_MARK_STACK == GC_MAKE_GCPROS_NOOPS
[emacs.git] / src / w32fns.c
blobf279fb86c2f67f0ff161bab5949d610107a673a0
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 Lisp_Object display;
4978 struct w32_display_info *dpyinfo = NULL;
4979 Lisp_Object parent;
4980 struct kboard *kb;
4982 if (!FRAME_W32_P (SELECTED_FRAME ())
4983 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4984 error ("Cannot create a GUI frame in a -nw session");
4986 /* Make copy of frame parameters because the original is in pure
4987 storage now. */
4988 parameters = Fcopy_alist (parameters);
4990 /* Use this general default value to start with
4991 until we know if this frame has a specified name. */
4992 Vx_resource_name = Vinvocation_name;
4994 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4995 if (EQ (display, Qunbound))
4996 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4997 if (EQ (display, Qunbound))
4998 display = Qnil;
4999 dpyinfo = check_x_display_info (display);
5000 kb = dpyinfo->terminal->kboard;
5002 if (!dpyinfo->terminal->name)
5003 error ("Terminal is not live, can't create new frames on it");
5005 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5006 if (!STRINGP (name)
5007 && ! EQ (name, Qunbound)
5008 && ! NILP (name))
5009 error ("Invalid frame name--not a string or nil");
5011 if (STRINGP (name))
5012 Vx_resource_name = name;
5014 /* See if parent window is specified. */
5015 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5016 if (EQ (parent, Qunbound))
5017 parent = Qnil;
5018 if (! NILP (parent))
5019 CHECK_NUMBER (parent);
5021 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5022 /* No need to protect DISPLAY because that's not used after passing
5023 it to make_frame_without_minibuffer. */
5024 frame = Qnil;
5025 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5026 RES_TYPE_SYMBOL);
5027 if (EQ (tem, Qnone) || NILP (tem))
5028 f = make_frame_without_minibuffer (Qnil, kb, display);
5029 else if (EQ (tem, Qonly))
5031 f = make_minibuffer_frame ();
5032 minibuffer_only = true;
5034 else if (WINDOWP (tem))
5035 f = make_frame_without_minibuffer (tem, kb, display);
5036 else
5037 f = make_frame (true);
5039 XSETFRAME (frame, f);
5041 /* By default, make scrollbars the system standard width and height. */
5042 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5043 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5045 f->terminal = dpyinfo->terminal;
5047 f->output_method = output_w32;
5048 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5049 FRAME_FONTSET (f) = -1;
5051 fset_icon_name
5052 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5053 RES_TYPE_STRING));
5054 if (! STRINGP (f->icon_name))
5055 fset_icon_name (f, Qnil);
5057 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5059 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5060 record_unwind_protect (do_unwind_create_frame, frame);
5062 #ifdef GLYPH_DEBUG
5063 image_cache_refcount =
5064 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5065 dpyinfo_refcount = dpyinfo->reference_count;
5066 #endif /* GLYPH_DEBUG */
5068 /* Specify the parent under which to make this window. */
5069 if (!NILP (parent))
5071 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5072 pointer from integer of different size. */
5073 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5074 f->output_data.w32->explicit_parent = true;
5076 else
5078 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5079 f->output_data.w32->explicit_parent = false;
5082 /* Set the name; the functions to which we pass f expect the name to
5083 be set. */
5084 if (EQ (name, Qunbound) || NILP (name))
5086 fset_name (f, build_string (dpyinfo->w32_id_name));
5087 f->explicit_name = false;
5089 else
5091 fset_name (f, name);
5092 f->explicit_name = true;
5093 /* Use the frame's title when getting resources for this frame. */
5094 specbind (Qx_resource_name, name);
5097 if (uniscribe_available)
5098 register_font_driver (&uniscribe_font_driver, f);
5099 register_font_driver (&w32font_driver, f);
5101 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5102 "fontBackend", "FontBackend", RES_TYPE_STRING);
5104 /* Extract the window parameters from the supplied values
5105 that are needed to determine window geometry. */
5106 x_default_font_parameter (f, parameters);
5108 x_default_parameter (f, parameters, Qborder_width, make_number (2),
5109 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5111 /* We recognize either internalBorderWidth or internalBorder
5112 (which is what xterm calls it). */
5113 if (NILP (Fassq (Qinternal_border_width, parameters)))
5115 Lisp_Object value;
5117 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5118 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5119 if (! EQ (value, Qunbound))
5120 parameters = Fcons (Fcons (Qinternal_border_width, value),
5121 parameters);
5123 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5124 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5125 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5126 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5127 NULL, NULL, RES_TYPE_NUMBER);
5128 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5129 NULL, NULL, RES_TYPE_NUMBER);
5130 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5131 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5132 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5133 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5135 /* Also do the stuff which must be set before the window exists. */
5136 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5137 "foreground", "Foreground", RES_TYPE_STRING);
5138 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5139 "background", "Background", RES_TYPE_STRING);
5140 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5141 "pointerColor", "Foreground", RES_TYPE_STRING);
5142 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5143 "borderColor", "BorderColor", RES_TYPE_STRING);
5144 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5145 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5146 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5147 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5148 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5149 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5150 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5151 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5152 /* Process alpha here (Bug#16619). */
5153 x_default_parameter (f, parameters, Qalpha, Qnil,
5154 "alpha", "Alpha", RES_TYPE_NUMBER);
5156 /* Init faces first since we need the frame's column width/line
5157 height in various occasions. */
5158 init_frame_faces (f);
5160 /* The following call of change_frame_size is needed since otherwise
5161 x_set_tool_bar_lines will already work with the character sizes
5162 installed by init_frame_faces while the frame's pixel size is
5163 still calculated from a character size of 1 and we subsequently
5164 hit the (height >= 0) assertion in window_box_height.
5166 The non-pixelwise code apparently worked around this because it
5167 had one frame line vs one toolbar line which left us with a zero
5168 root window height which was obviously wrong as well ... */
5169 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5170 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5171 Qx_create_frame_1);
5173 /* The X resources controlling the menu-bar and tool-bar are
5174 processed specially at startup, and reflected in the mode
5175 variables; ignore them here. */
5176 x_default_parameter (f, parameters, Qmenu_bar_lines,
5177 NILP (Vmenu_bar_mode)
5178 ? make_number (0) : make_number (1),
5179 NULL, NULL, RES_TYPE_NUMBER);
5180 x_default_parameter (f, parameters, Qtool_bar_lines,
5181 NILP (Vtool_bar_mode)
5182 ? make_number (0) : make_number (1),
5183 NULL, NULL, RES_TYPE_NUMBER);
5185 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5186 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5187 x_default_parameter (f, parameters, Qtitle, Qnil,
5188 "title", "Title", RES_TYPE_STRING);
5190 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5191 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5193 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5194 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5195 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5196 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5197 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5198 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5199 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5201 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5203 window_prompting = x_figure_window_size (f, parameters, true);
5205 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5206 f->no_split = minibuffer_only || EQ (tem, Qt);
5208 w32_window (f, window_prompting, minibuffer_only);
5209 x_icon (f, parameters);
5211 x_make_gc (f);
5213 /* Now consider the frame official. */
5214 f->terminal->reference_count++;
5215 FRAME_DISPLAY_INFO (f)->reference_count++;
5216 Vframe_list = Fcons (frame, Vframe_list);
5218 /* We need to do this after creating the window, so that the
5219 icon-creation functions can say whose icon they're describing. */
5220 x_default_parameter (f, parameters, Qicon_type, Qnil,
5221 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5223 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5224 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5225 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5226 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5227 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5228 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5229 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5230 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5231 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
5232 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
5234 /* Allow x_set_window_size, now. */
5235 f->can_x_set_window_size = true;
5237 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
5238 Qx_create_frame_2);
5240 /* Tell the server what size and position, etc, we want, and how
5241 badly we want them. This should be done after we have the menu
5242 bar so that its size can be taken into account. */
5243 block_input ();
5244 x_wm_set_size_hint (f, window_prompting, false);
5245 unblock_input ();
5247 /* Process fullscreen parameter here in the hope that normalizing a
5248 fullheight/fullwidth frame will produce the size set by the last
5249 adjust_frame_size call. */
5250 x_default_parameter (f, parameters, Qfullscreen, Qnil,
5251 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5253 /* Make the window appear on the frame and enable display, unless
5254 the caller says not to. However, with explicit parent, Emacs
5255 cannot control visibility, so don't try. */
5256 if (! f->output_data.w32->explicit_parent)
5258 Lisp_Object visibility;
5260 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5261 if (EQ (visibility, Qunbound))
5262 visibility = Qt;
5264 if (EQ (visibility, Qicon))
5265 x_iconify_frame (f);
5266 else if (! NILP (visibility))
5267 x_make_frame_visible (f);
5268 else
5269 /* Must have been Qnil. */
5273 /* Initialize `default-minibuffer-frame' in case this is the first
5274 frame on this terminal. */
5275 if (FRAME_HAS_MINIBUF_P (f)
5276 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
5277 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
5278 kset_default_minibuffer_frame (kb, frame);
5280 /* All remaining specified parameters, which have not been "used"
5281 by x_get_arg and friends, now go in the misc. alist of the frame. */
5282 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
5283 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
5284 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
5286 /* Make sure windows on this frame appear in calls to next-window
5287 and similar functions. */
5288 Vwindow_list = Qnil;
5290 return unbind_to (count, frame);
5293 /* FRAME is used only to get a handle on the X display. We don't pass the
5294 display info directly because we're called from frame.c, which doesn't
5295 know about that structure. */
5296 Lisp_Object
5297 x_get_focus_frame (struct frame *frame)
5299 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
5300 Lisp_Object xfocus;
5301 if (! dpyinfo->w32_focus_frame)
5302 return Qnil;
5304 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5305 return xfocus;
5308 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
5309 doc: /* Internal function called by `color-defined-p', which see.
5310 \(Note that the Nextstep version of this function ignores FRAME.) */)
5311 (Lisp_Object color, Lisp_Object frame)
5313 XColor foo;
5314 struct frame *f = decode_window_system_frame (frame);
5316 CHECK_STRING (color);
5318 if (w32_defined_color (f, SDATA (color), &foo, false))
5319 return Qt;
5320 else
5321 return Qnil;
5324 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
5325 doc: /* Internal function called by `color-values', which see. */)
5326 (Lisp_Object color, Lisp_Object frame)
5328 XColor foo;
5329 struct frame *f = decode_window_system_frame (frame);
5331 CHECK_STRING (color);
5333 if (w32_defined_color (f, SDATA (color), &foo, false))
5334 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
5335 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
5336 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
5337 else
5338 return Qnil;
5341 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
5342 doc: /* Internal function called by `display-color-p', which see. */)
5343 (Lisp_Object display)
5345 struct w32_display_info *dpyinfo = check_x_display_info (display);
5347 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
5348 return Qnil;
5350 return Qt;
5353 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
5354 Sx_display_grayscale_p, 0, 1, 0,
5355 doc: /* Return t if DISPLAY supports shades of gray.
5356 Note that color displays do support shades of gray.
5357 The optional argument DISPLAY specifies which display to ask about.
5358 DISPLAY should be either a frame or a display name (a string).
5359 If omitted or nil, that stands for the selected frame's display. */)
5360 (Lisp_Object display)
5362 struct w32_display_info *dpyinfo = check_x_display_info (display);
5364 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
5365 return Qnil;
5367 return Qt;
5370 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
5371 Sx_display_pixel_width, 0, 1, 0,
5372 doc: /* Return the width in pixels of DISPLAY.
5373 The optional argument DISPLAY specifies which display to ask about.
5374 DISPLAY should be either a frame or a display name (a string).
5375 If omitted or nil, that stands for the selected frame's display.
5377 On \"multi-monitor\" setups this refers to the pixel width for all
5378 physical monitors associated with DISPLAY. To get information for
5379 each physical monitor, use `display-monitor-attributes-list'. */)
5380 (Lisp_Object display)
5382 struct w32_display_info *dpyinfo = check_x_display_info (display);
5384 return make_number (x_display_pixel_width (dpyinfo));
5387 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
5388 Sx_display_pixel_height, 0, 1, 0,
5389 doc: /* Return the height in pixels of DISPLAY.
5390 The optional argument DISPLAY specifies which display to ask about.
5391 DISPLAY should be either a frame or a display name (a string).
5392 If omitted or nil, that stands for the selected frame's display.
5394 On \"multi-monitor\" setups this refers to the pixel height for all
5395 physical monitors associated with DISPLAY. To get information for
5396 each physical monitor, use `display-monitor-attributes-list'. */)
5397 (Lisp_Object display)
5399 struct w32_display_info *dpyinfo = check_x_display_info (display);
5401 return make_number (x_display_pixel_height (dpyinfo));
5404 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
5405 0, 1, 0,
5406 doc: /* Return the number of bitplanes of DISPLAY.
5407 The optional argument DISPLAY specifies which display to ask about.
5408 DISPLAY should be either a frame or a display name (a string).
5409 If omitted or nil, that stands for the selected frame's display. */)
5410 (Lisp_Object display)
5412 struct w32_display_info *dpyinfo = check_x_display_info (display);
5414 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
5417 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
5418 0, 1, 0,
5419 doc: /* Return the number of color cells of DISPLAY.
5420 The optional argument DISPLAY specifies which display to ask about.
5421 DISPLAY should be either a frame or a display name (a string).
5422 If omitted or nil, that stands for the selected frame's display. */)
5423 (Lisp_Object display)
5425 struct w32_display_info *dpyinfo = check_x_display_info (display);
5426 int cap;
5428 /* Don't use NCOLORS: it returns incorrect results under remote
5429 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
5430 * overflow and because probably is more meaningful on Windows
5431 * anyway. */
5433 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
5434 return make_number (cap);
5437 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
5438 Sx_server_max_request_size,
5439 0, 1, 0,
5440 doc: /* Return the maximum request size of the server of DISPLAY.
5441 The optional argument DISPLAY specifies which display to ask about.
5442 DISPLAY should be either a frame or a display name (a string).
5443 If omitted or nil, that stands for the selected frame's display. */)
5444 (Lisp_Object display)
5446 return make_number (1);
5449 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
5450 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
5452 \(Labeling every distributor as a "vendor" embodies the false assumption
5453 that operating systems cannot be developed and distributed noncommercially.)
5455 For GNU and Unix systems, this queries the X server software; for
5456 MS-Windows, this queries the OS.
5458 The optional argument TERMINAL specifies which display to ask about.
5459 TERMINAL should be a terminal object, a frame or a display name (a string).
5460 If omitted or nil, that stands for the selected frame's display. */)
5461 (Lisp_Object terminal)
5463 return build_string ("Microsoft Corp.");
5466 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
5467 doc: /* Return the version numbers of the GUI software on TERMINAL.
5468 The value is a list of three integers specifying the version of the GUI
5469 software in use.
5471 For GNU and Unix system, the first 2 numbers are the version of the X
5472 Protocol used on TERMINAL and the 3rd number is the distributor-specific
5473 release number. For MS-Windows, the 3 numbers report the version and
5474 the build number of the OS.
5476 See also the function `x-server-vendor'.
5478 The optional argument TERMINAL specifies which display to ask about.
5479 TERMINAL should be a terminal object, a frame or a display name (a string).
5480 If omitted or nil, that stands for the selected frame's display. */)
5481 (Lisp_Object terminal)
5483 return list3i (w32_major_version, w32_minor_version, w32_build_number);
5486 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
5487 doc: /* Return the number of screens on the server of DISPLAY.
5488 The optional argument DISPLAY specifies which display to ask about.
5489 DISPLAY should be either a frame or a display name (a string).
5490 If omitted or nil, that stands for the selected frame's display. */)
5491 (Lisp_Object display)
5493 return make_number (1);
5496 DEFUN ("x-display-mm-height", Fx_display_mm_height,
5497 Sx_display_mm_height, 0, 1, 0,
5498 doc: /* Return the height in millimeters of DISPLAY.
5499 The optional argument DISPLAY specifies which display to ask about.
5500 DISPLAY should be either a frame or a display name (a string).
5501 If omitted or nil, that stands for the selected frame's display.
5503 On \"multi-monitor\" setups this refers to the height in millimeters for
5504 all physical monitors associated with DISPLAY. To get information
5505 for each physical monitor, use `display-monitor-attributes-list'. */)
5506 (Lisp_Object display)
5508 struct w32_display_info *dpyinfo = check_x_display_info (display);
5509 HDC hdc;
5510 double mm_per_pixel;
5512 hdc = GetDC (NULL);
5513 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5514 / GetDeviceCaps (hdc, VERTRES));
5515 ReleaseDC (NULL, hdc);
5517 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5520 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5521 doc: /* Return the width in millimeters of DISPLAY.
5522 The optional argument DISPLAY specifies which display to ask about.
5523 DISPLAY should be either a frame or a display name (a string).
5524 If omitted or nil, that stands for the selected frame's display.
5526 On \"multi-monitor\" setups this refers to the width in millimeters for
5527 all physical monitors associated with TERMINAL. To get information
5528 for each physical monitor, use `display-monitor-attributes-list'. */)
5529 (Lisp_Object display)
5531 struct w32_display_info *dpyinfo = check_x_display_info (display);
5532 HDC hdc;
5533 double mm_per_pixel;
5535 hdc = GetDC (NULL);
5536 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5537 / GetDeviceCaps (hdc, HORZRES));
5538 ReleaseDC (NULL, hdc);
5540 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5543 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5544 Sx_display_backing_store, 0, 1, 0,
5545 doc: /* Return an indication of whether DISPLAY does backing store.
5546 The value may be `always', `when-mapped', or `not-useful'.
5547 The optional argument DISPLAY specifies which display to ask about.
5548 DISPLAY should be either a frame or a display name (a string).
5549 If omitted or nil, that stands for the selected frame's display. */)
5550 (Lisp_Object display)
5552 return intern ("not-useful");
5555 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5556 Sx_display_visual_class, 0, 1, 0,
5557 doc: /* Return the visual class of DISPLAY.
5558 The value is one of the symbols `static-gray', `gray-scale',
5559 `static-color', `pseudo-color', `true-color', or `direct-color'.
5561 The optional argument DISPLAY specifies which display to ask about.
5562 DISPLAY should be either a frame or a display name (a string).
5563 If omitted or nil, that stands for the selected frame's display. */)
5564 (Lisp_Object display)
5566 struct w32_display_info *dpyinfo = check_x_display_info (display);
5567 Lisp_Object result = Qnil;
5569 if (dpyinfo->has_palette)
5570 result = intern ("pseudo-color");
5571 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5572 result = intern ("static-grey");
5573 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5574 result = intern ("static-color");
5575 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5576 result = intern ("true-color");
5578 return result;
5581 DEFUN ("x-display-save-under", Fx_display_save_under,
5582 Sx_display_save_under, 0, 1, 0,
5583 doc: /* Return t if DISPLAY supports the save-under feature.
5584 The optional argument DISPLAY specifies which display to ask about.
5585 DISPLAY should be either a frame or a display name (a string).
5586 If omitted or nil, that stands for the selected frame's display. */)
5587 (Lisp_Object display)
5589 return Qnil;
5592 static BOOL CALLBACK ALIGN_STACK
5593 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5595 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5597 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5599 return TRUE;
5602 static Lisp_Object
5603 w32_display_monitor_attributes_list (void)
5605 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5606 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5607 int i, n_monitors;
5608 HMONITOR *monitors;
5610 if (!(enum_display_monitors_fn && get_monitor_info_fn
5611 && monitor_from_window_fn))
5612 return Qnil;
5614 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5615 (LPARAM) &monitor_list)
5616 || NILP (monitor_list))
5617 return Qnil;
5619 n_monitors = 0;
5620 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5621 n_monitors++;
5623 monitors = xmalloc (n_monitors * sizeof (*monitors));
5624 for (i = 0; i < n_monitors; i++)
5626 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5627 monitor_list = XCDR (monitor_list);
5630 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5631 FOR_EACH_FRAME (rest, frame)
5633 struct frame *f = XFRAME (frame);
5635 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5637 HMONITOR monitor =
5638 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5639 MONITOR_DEFAULT_TO_NEAREST);
5641 for (i = 0; i < n_monitors; i++)
5642 if (monitors[i] == monitor)
5643 break;
5645 if (i < n_monitors)
5646 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5650 for (i = 0; i < n_monitors; i++)
5652 Lisp_Object geometry, workarea, name, attributes = Qnil;
5653 HDC hdc;
5654 int width_mm, height_mm;
5655 struct MONITOR_INFO_EX mi;
5657 mi.cbSize = sizeof (mi);
5658 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5659 continue;
5661 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5662 if (hdc == NULL)
5663 continue;
5664 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5665 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5666 DeleteDC (hdc);
5668 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5669 attributes);
5671 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5673 attributes = Fcons (Fcons (Qname, name), attributes);
5675 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5676 attributes);
5678 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5679 mi.rcWork.right - mi.rcWork.left,
5680 mi.rcWork.bottom - mi.rcWork.top);
5681 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5683 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5684 mi.rcMonitor.right - mi.rcMonitor.left,
5685 mi.rcMonitor.bottom - mi.rcMonitor.top);
5686 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5688 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5689 primary_monitor_attributes = attributes;
5690 else
5691 attributes_list = Fcons (attributes, attributes_list);
5694 if (!NILP (primary_monitor_attributes))
5695 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5697 xfree (monitors);
5699 return attributes_list;
5702 static Lisp_Object
5703 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5705 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5706 HDC hdc;
5707 double mm_per_pixel;
5708 int pixel_width, pixel_height, width_mm, height_mm;
5709 RECT workarea_rect;
5711 /* Fallback: treat (possibly) multiple physical monitors as if they
5712 formed a single monitor as a whole. This should provide a
5713 consistent result at least on single monitor environments. */
5714 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5715 attributes);
5717 frames = Qnil;
5718 FOR_EACH_FRAME (rest, frame)
5720 struct frame *f = XFRAME (frame);
5722 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5723 frames = Fcons (frame, frames);
5725 attributes = Fcons (Fcons (Qframes, frames), attributes);
5727 pixel_width = x_display_pixel_width (dpyinfo);
5728 pixel_height = x_display_pixel_height (dpyinfo);
5730 hdc = GetDC (NULL);
5731 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5732 / GetDeviceCaps (hdc, HORZRES));
5733 width_mm = pixel_width * mm_per_pixel + 0.5;
5734 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5735 / GetDeviceCaps (hdc, VERTRES));
5736 height_mm = pixel_height * mm_per_pixel + 0.5;
5737 ReleaseDC (NULL, hdc);
5738 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5739 attributes);
5741 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5742 we don't care. */
5743 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5744 GetSystemMetrics (SM_YVIRTUALSCREEN),
5745 pixel_width, pixel_height);
5746 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5747 workarea = list4i (workarea_rect.left, workarea_rect.top,
5748 workarea_rect.right - workarea_rect.left,
5749 workarea_rect.bottom - workarea_rect.top);
5750 else
5751 workarea = geometry;
5752 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5754 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5756 return list1 (attributes);
5759 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5760 Sw32_display_monitor_attributes_list,
5761 0, 1, 0,
5762 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5764 The optional argument DISPLAY specifies which display to ask about.
5765 DISPLAY should be either a frame or a display name (a string).
5766 If omitted or nil, that stands for the selected frame's display.
5768 Internal use only, use `display-monitor-attributes-list' instead. */)
5769 (Lisp_Object display)
5771 struct w32_display_info *dpyinfo = check_x_display_info (display);
5772 Lisp_Object attributes_list;
5774 block_input ();
5775 attributes_list = w32_display_monitor_attributes_list ();
5776 if (NILP (attributes_list))
5777 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5778 unblock_input ();
5780 return attributes_list;
5783 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5784 doc: /* Set the sound generated when the bell is rung.
5785 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5786 to use the corresponding system sound for the bell. The 'silent sound
5787 prevents Emacs from making any sound at all.
5788 SOUND is nil to use the normal beep. */)
5789 (Lisp_Object sound)
5791 CHECK_SYMBOL (sound);
5793 if (NILP (sound))
5794 sound_type = 0xFFFFFFFF;
5795 else if (EQ (sound, intern ("asterisk")))
5796 sound_type = MB_ICONASTERISK;
5797 else if (EQ (sound, intern ("exclamation")))
5798 sound_type = MB_ICONEXCLAMATION;
5799 else if (EQ (sound, intern ("hand")))
5800 sound_type = MB_ICONHAND;
5801 else if (EQ (sound, intern ("question")))
5802 sound_type = MB_ICONQUESTION;
5803 else if (EQ (sound, intern ("ok")))
5804 sound_type = MB_OK;
5805 else if (EQ (sound, intern ("silent")))
5806 sound_type = MB_EMACS_SILENT;
5807 else
5808 sound_type = 0xFFFFFFFF;
5810 return sound;
5814 x_screen_planes (register struct frame *f)
5816 return FRAME_DISPLAY_INFO (f)->n_planes;
5819 /* Return the display structure for the display named NAME.
5820 Open a new connection if necessary. */
5822 struct w32_display_info *
5823 x_display_info_for_name (Lisp_Object name)
5825 struct w32_display_info *dpyinfo;
5827 CHECK_STRING (name);
5829 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5830 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5831 return dpyinfo;
5833 /* Use this general default value to start with. */
5834 Vx_resource_name = Vinvocation_name;
5836 validate_x_resource_name ();
5838 dpyinfo = w32_term_init (name, (unsigned char *)0,
5839 SSDATA (Vx_resource_name));
5841 if (dpyinfo == 0)
5842 error ("Cannot connect to server %s", SDATA (name));
5844 XSETFASTINT (Vwindow_system_version, w32_major_version);
5846 return dpyinfo;
5849 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5850 1, 3, 0, doc: /* Open a connection to a display server.
5851 DISPLAY is the name of the display to connect to.
5852 Optional second arg XRM-STRING is a string of resources in xrdb format.
5853 If the optional third arg MUST-SUCCEED is non-nil,
5854 terminate Emacs if we can't open the connection.
5855 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5856 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5858 unsigned char *xrm_option;
5859 struct w32_display_info *dpyinfo;
5861 CHECK_STRING (display);
5863 /* Signal an error in order to encourage correct use from callers.
5864 * If we ever support multiple window systems in the same Emacs,
5865 * we'll need callers to be precise about what window system they
5866 * want. */
5868 if (strcmp (SSDATA (display), "w32") != 0)
5869 error ("The name of the display in this Emacs must be \"w32\"");
5871 /* If initialization has already been done, return now to avoid
5872 overwriting critical parts of one_w32_display_info. */
5873 if (window_system_available (NULL))
5874 return Qnil;
5876 if (! NILP (xrm_string))
5877 CHECK_STRING (xrm_string);
5879 /* Allow color mapping to be defined externally; first look in user's
5880 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5882 Lisp_Object color_file;
5884 color_file = build_string ("~/rgb.txt");
5886 if (NILP (Ffile_readable_p (color_file)))
5887 color_file =
5888 Fexpand_file_name (build_string ("rgb.txt"),
5889 Fsymbol_value (intern ("data-directory")));
5891 Vw32_color_map = Fx_load_color_file (color_file);
5893 if (NILP (Vw32_color_map))
5894 Vw32_color_map = w32_default_color_map ();
5896 /* Merge in system logical colors. */
5897 add_system_logical_colors_to_map (&Vw32_color_map);
5899 if (! NILP (xrm_string))
5900 xrm_option = SDATA (xrm_string);
5901 else
5902 xrm_option = (unsigned char *) 0;
5904 /* Use this general default value to start with. */
5905 /* First remove .exe suffix from invocation-name - it looks ugly. */
5907 char basename[ MAX_PATH ], *str;
5909 lispstpcpy (basename, Vinvocation_name);
5910 str = strrchr (basename, '.');
5911 if (str) *str = 0;
5912 Vinvocation_name = build_string (basename);
5914 Vx_resource_name = Vinvocation_name;
5916 validate_x_resource_name ();
5918 /* This is what opens the connection and sets x_current_display.
5919 This also initializes many symbols, such as those used for input. */
5920 dpyinfo = w32_term_init (display, xrm_option,
5921 SSDATA (Vx_resource_name));
5923 if (dpyinfo == 0)
5925 if (!NILP (must_succeed))
5926 fatal ("Cannot connect to server %s.\n",
5927 SDATA (display));
5928 else
5929 error ("Cannot connect to server %s", SDATA (display));
5932 XSETFASTINT (Vwindow_system_version, w32_major_version);
5933 return Qnil;
5936 DEFUN ("x-close-connection", Fx_close_connection,
5937 Sx_close_connection, 1, 1, 0,
5938 doc: /* Close the connection to DISPLAY's server.
5939 For DISPLAY, specify either a frame or a display name (a string).
5940 If DISPLAY is nil, that stands for the selected frame's display. */)
5941 (Lisp_Object display)
5943 struct w32_display_info *dpyinfo = check_x_display_info (display);
5945 if (dpyinfo->reference_count > 0)
5946 error ("Display still has frames on it");
5948 block_input ();
5949 x_destroy_all_bitmaps (dpyinfo);
5951 x_delete_display (dpyinfo);
5952 unblock_input ();
5954 return Qnil;
5957 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5958 doc: /* Return the list of display names that Emacs has connections to. */)
5959 (void)
5961 Lisp_Object result = Qnil;
5962 struct w32_display_info *wdi;
5964 for (wdi = x_display_list; wdi; wdi = wdi->next)
5965 result = Fcons (XCAR (wdi->name_list_element), result);
5967 return result;
5970 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5971 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5972 This function only has an effect on X Windows. With MS Windows, it is
5973 defined but does nothing.
5975 If ON is nil, allow buffering of requests.
5976 Turning on synchronization prohibits the Xlib routines from buffering
5977 requests and seriously degrades performance, but makes debugging much
5978 easier.
5979 The optional second argument TERMINAL specifies which display to act on.
5980 TERMINAL should be a terminal object, a frame or a display name (a string).
5981 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5982 (Lisp_Object on, Lisp_Object display)
5984 return Qnil;
5989 /***********************************************************************
5990 Window properties
5991 ***********************************************************************/
5993 #if 0 /* TODO : port window properties to W32 */
5995 DEFUN ("x-change-window-property", Fx_change_window_property,
5996 Sx_change_window_property, 2, 6, 0,
5997 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5998 PROP must be a string. VALUE may be a string or a list of conses,
5999 numbers and/or strings. If an element in the list is a string, it is
6000 converted to an atom and the value of the Atom is used. If an element
6001 is a cons, it is converted to a 32 bit number where the car is the 16
6002 top bits and the cdr is the lower 16 bits.
6004 FRAME nil or omitted means use the selected frame.
6005 If TYPE is given and non-nil, it is the name of the type of VALUE.
6006 If TYPE is not given or nil, the type is STRING.
6007 FORMAT gives the size in bits of each element if VALUE is a list.
6008 It must be one of 8, 16 or 32.
6009 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6010 If OUTER-P is non-nil, the property is changed for the outer X window of
6011 FRAME. Default is to change on the edit X window. */)
6012 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6013 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6015 struct frame *f = decode_window_system_frame (frame);
6016 Atom prop_atom;
6018 CHECK_STRING (prop);
6019 CHECK_STRING (value);
6021 block_input ();
6022 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6023 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6024 prop_atom, XA_STRING, 8, PropModeReplace,
6025 SDATA (value), SCHARS (value));
6027 /* Make sure the property is set when we return. */
6028 XFlush (FRAME_W32_DISPLAY (f));
6029 unblock_input ();
6031 return value;
6035 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6036 Sx_delete_window_property, 1, 2, 0,
6037 doc: /* Remove window property PROP from X window of FRAME.
6038 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6039 (Lisp_Object prop, Lisp_Object frame)
6041 struct frame *f = decode_window_system_frame (frame);
6042 Atom prop_atom;
6044 CHECK_STRING (prop);
6045 block_input ();
6046 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6047 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6049 /* Make sure the property is removed when we return. */
6050 XFlush (FRAME_W32_DISPLAY (f));
6051 unblock_input ();
6053 return prop;
6057 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6058 1, 6, 0,
6059 doc: /* Value is the value of window property PROP on FRAME.
6060 If FRAME is nil or omitted, use the selected frame.
6062 On X Windows, the following optional arguments are also accepted:
6063 If TYPE is nil or omitted, get the property as a string.
6064 Otherwise TYPE is the name of the atom that denotes the type expected.
6065 If SOURCE is non-nil, get the property on that window instead of from
6066 FRAME. The number 0 denotes the root window.
6067 If DELETE-P is non-nil, delete the property after retrieving it.
6068 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6070 On MS Windows, this function accepts but ignores those optional arguments.
6072 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6073 no value of TYPE (always string in the MS Windows case). */)
6074 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6075 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6077 struct frame *f = decode_window_system_frame (frame);
6078 Atom prop_atom;
6079 int rc;
6080 Lisp_Object prop_value = Qnil;
6081 char *tmp_data = NULL;
6082 Atom actual_type;
6083 int actual_format;
6084 unsigned long actual_size, bytes_remaining;
6086 CHECK_STRING (prop);
6087 block_input ();
6088 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6089 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6090 prop_atom, 0, 0, False, XA_STRING,
6091 &actual_type, &actual_format, &actual_size,
6092 &bytes_remaining, (unsigned char **) &tmp_data);
6093 if (rc == Success)
6095 int size = bytes_remaining;
6097 XFree (tmp_data);
6098 tmp_data = NULL;
6100 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6101 prop_atom, 0, bytes_remaining,
6102 False, XA_STRING,
6103 &actual_type, &actual_format,
6104 &actual_size, &bytes_remaining,
6105 (unsigned char **) &tmp_data);
6106 if (rc == Success)
6107 prop_value = make_string (tmp_data, size);
6109 XFree (tmp_data);
6112 unblock_input ();
6114 return prop_value;
6116 return Qnil;
6119 #endif /* TODO */
6121 /***********************************************************************
6122 Tool tips
6123 ***********************************************************************/
6125 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
6126 Lisp_Object, Lisp_Object);
6127 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6128 Lisp_Object, int, int, int *, int *);
6130 /* The frame of a currently visible tooltip. */
6132 Lisp_Object tip_frame;
6134 /* If non-nil, a timer started that hides the last tooltip when it
6135 fires. */
6137 Lisp_Object tip_timer;
6138 Window tip_window;
6140 /* If non-nil, a vector of 3 elements containing the last args
6141 with which x-show-tip was called. See there. */
6143 Lisp_Object last_show_tip_args;
6146 static void
6147 unwind_create_tip_frame (Lisp_Object frame)
6149 Lisp_Object deleted;
6151 deleted = unwind_create_frame (frame);
6152 if (EQ (deleted, Qt))
6154 tip_window = NULL;
6155 tip_frame = Qnil;
6160 /* Create a frame for a tooltip on the display described by DPYINFO.
6161 PARMS is a list of frame parameters. TEXT is the string to
6162 display in the tip frame. Value is the frame.
6164 Note that functions called here, esp. x_default_parameter can
6165 signal errors, for instance when a specified color name is
6166 undefined. We have to make sure that we're in a consistent state
6167 when this happens. */
6169 static Lisp_Object
6170 x_create_tip_frame (struct w32_display_info *dpyinfo,
6171 Lisp_Object parms, Lisp_Object text)
6173 struct frame *f;
6174 Lisp_Object frame;
6175 Lisp_Object name;
6176 long window_prompting = 0;
6177 int width, height;
6178 ptrdiff_t count = SPECPDL_INDEX ();
6179 struct kboard *kb;
6180 bool face_change_before = face_change;
6181 Lisp_Object buffer;
6182 struct buffer *old_buffer;
6184 /* Use this general default value to start with until we know if
6185 this frame has a specified name. */
6186 Vx_resource_name = Vinvocation_name;
6188 kb = dpyinfo->terminal->kboard;
6190 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6191 avoid destructive changes behind our caller's back. */
6192 parms = Fcopy_alist (parms);
6194 /* Get the name of the frame to use for resource lookup. */
6195 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6196 if (!STRINGP (name)
6197 && !EQ (name, Qunbound)
6198 && !NILP (name))
6199 error ("Invalid frame name--not a string or nil");
6200 Vx_resource_name = name;
6202 frame = Qnil;
6203 /* Make a frame without minibuffer nor mode-line. */
6204 f = make_frame (false);
6205 f->wants_modeline = 0;
6206 XSETFRAME (frame, f);
6208 AUTO_STRING (tip, " *tip*");
6209 buffer = Fget_buffer_create (tip);
6210 /* Use set_window_buffer instead of Fset_window_buffer (see
6211 discussion of bug#11984, bug#12025, bug#12026). */
6212 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, false, false);
6213 old_buffer = current_buffer;
6214 set_buffer_internal_1 (XBUFFER (buffer));
6215 bset_truncate_lines (current_buffer, Qnil);
6216 specbind (Qinhibit_read_only, Qt);
6217 specbind (Qinhibit_modification_hooks, Qt);
6218 Ferase_buffer ();
6219 Finsert (1, &text);
6220 set_buffer_internal_1 (old_buffer);
6222 record_unwind_protect (unwind_create_tip_frame, frame);
6224 /* By setting the output method, we're essentially saying that
6225 the frame is live, as per FRAME_LIVE_P. If we get a signal
6226 from this point on, x_destroy_window might screw up reference
6227 counts etc. */
6228 f->terminal = dpyinfo->terminal;
6229 f->output_method = output_w32;
6230 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6232 FRAME_FONTSET (f) = -1;
6233 fset_icon_name (f, Qnil);
6235 #ifdef GLYPH_DEBUG
6236 image_cache_refcount =
6237 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6238 dpyinfo_refcount = dpyinfo->reference_count;
6239 #endif /* GLYPH_DEBUG */
6240 FRAME_KBOARD (f) = kb;
6241 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6242 f->output_data.w32->explicit_parent = false;
6244 /* Set the name; the functions to which we pass f expect the name to
6245 be set. */
6246 if (EQ (name, Qunbound) || NILP (name))
6248 fset_name (f, build_string (dpyinfo->w32_id_name));
6249 f->explicit_name = false;
6251 else
6253 fset_name (f, name);
6254 f->explicit_name = true;
6255 /* use the frame's title when getting resources for this frame. */
6256 specbind (Qx_resource_name, name);
6259 if (uniscribe_available)
6260 register_font_driver (&uniscribe_font_driver, f);
6261 register_font_driver (&w32font_driver, f);
6263 x_default_parameter (f, parms, Qfont_backend, Qnil,
6264 "fontBackend", "FontBackend", RES_TYPE_STRING);
6266 /* Extract the window parameters from the supplied values
6267 that are needed to determine window geometry. */
6268 x_default_font_parameter (f, parms);
6270 x_default_parameter (f, parms, Qborder_width, make_number (2),
6271 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6272 /* This defaults to 2 in order to match xterm. We recognize either
6273 internalBorderWidth or internalBorder (which is what xterm calls
6274 it). */
6275 if (NILP (Fassq (Qinternal_border_width, parms)))
6277 Lisp_Object value;
6279 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6280 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
6281 if (! EQ (value, Qunbound))
6282 parms = Fcons (Fcons (Qinternal_border_width, value),
6283 parms);
6285 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6286 "internalBorderWidth", "internalBorderWidth",
6287 RES_TYPE_NUMBER);
6288 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
6289 NULL, NULL, RES_TYPE_NUMBER);
6290 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
6291 NULL, NULL, RES_TYPE_NUMBER);
6293 /* Also do the stuff which must be set before the window exists. */
6294 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6295 "foreground", "Foreground", RES_TYPE_STRING);
6296 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6297 "background", "Background", RES_TYPE_STRING);
6298 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6299 "pointerColor", "Foreground", RES_TYPE_STRING);
6300 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6301 "cursorColor", "Foreground", RES_TYPE_STRING);
6302 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6303 "borderColor", "BorderColor", RES_TYPE_STRING);
6305 /* Init faces before x_default_parameter is called for the
6306 scroll-bar-width parameter because otherwise we end up in
6307 init_iterator with a null face cache, which should not happen. */
6308 init_frame_faces (f);
6310 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6311 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6313 window_prompting = x_figure_window_size (f, parms, false);
6315 /* No fringes on tip frame. */
6316 f->fringe_cols = 0;
6317 f->left_fringe_width = 0;
6318 f->right_fringe_width = 0;
6320 block_input ();
6321 my_create_tip_window (f);
6322 unblock_input ();
6324 x_make_gc (f);
6326 x_default_parameter (f, parms, Qauto_raise, Qnil,
6327 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6328 x_default_parameter (f, parms, Qauto_lower, Qnil,
6329 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6330 x_default_parameter (f, parms, Qcursor_type, Qbox,
6331 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6332 /* Process alpha here (Bug#17344). */
6333 x_default_parameter (f, parms, Qalpha, Qnil,
6334 "alpha", "Alpha", RES_TYPE_NUMBER);
6336 /* Dimensions, especially FRAME_LINES (f), must be done via
6337 change_frame_size. Change will not be effected unless different
6338 from the current FRAME_LINES (f). */
6339 width = FRAME_COLS (f);
6340 height = FRAME_LINES (f);
6341 SET_FRAME_COLS (f, 0);
6342 SET_FRAME_LINES (f, 0);
6343 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
6344 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
6346 /* Add `tooltip' frame parameter's default value. */
6347 if (NILP (Fframe_parameter (frame, Qtooltip)))
6348 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
6350 /* Set up faces after all frame parameters are known. This call
6351 also merges in face attributes specified for new frames.
6353 Frame parameters may be changed if .Xdefaults contains
6354 specifications for the default font. For example, if there is an
6355 `Emacs.default.attributeBackground: pink', the `background-color'
6356 attribute of the frame get's set, which let's the internal border
6357 of the tooltip frame appear in pink. Prevent this. */
6359 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
6360 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
6361 Lisp_Object colors = Qnil;
6363 /* Set tip_frame here, so that */
6364 tip_frame = frame;
6365 call2 (Qface_set_after_frame_default, frame, Qnil);
6367 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
6368 colors = Fcons (Fcons (Qbackground_color, bg), colors);
6369 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
6370 colors = Fcons (Fcons (Qforeground_color, fg), colors);
6372 if (!NILP (colors))
6373 Fmodify_frame_parameters (frame, colors);
6376 f->no_split = true;
6378 /* Now that the frame is official, it counts as a reference to
6379 its display. */
6380 FRAME_DISPLAY_INFO (f)->reference_count++;
6381 f->terminal->reference_count++;
6383 /* It is now ok to make the frame official even if we get an error
6384 below. And the frame needs to be on Vframe_list or making it
6385 visible won't work. */
6386 Vframe_list = Fcons (frame, Vframe_list);
6387 f->can_x_set_window_size = true;
6389 /* Setting attributes of faces of the tooltip frame from resources
6390 and similar will set face_change, which leads to the
6391 clearing of all current matrices. Since this isn't necessary
6392 here, avoid it by resetting face_change to the value it
6393 had before we created the tip frame. */
6394 face_change = face_change_before;
6396 /* Discard the unwind_protect. */
6397 return unbind_to (count, frame);
6401 /* Compute where to display tip frame F. PARMS is the list of frame
6402 parameters for F. DX and DY are specified offsets from the current
6403 location of the mouse. WIDTH and HEIGHT are the width and height
6404 of the tooltip. Return coordinates relative to the root window of
6405 the display in *ROOT_X and *ROOT_Y. */
6407 static void
6408 compute_tip_xy (struct frame *f,
6409 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
6410 int width, int height, int *root_x, int *root_y)
6412 Lisp_Object left, top, right, bottom;
6413 int min_x, min_y, max_x, max_y;
6415 /* User-specified position? */
6416 left = Fcdr (Fassq (Qleft, parms));
6417 top = Fcdr (Fassq (Qtop, parms));
6418 right = Fcdr (Fassq (Qright, parms));
6419 bottom = Fcdr (Fassq (Qbottom, parms));
6421 /* Move the tooltip window where the mouse pointer is. Resize and
6422 show it. */
6423 if ((!INTEGERP (left) && !INTEGERP (right))
6424 || (!INTEGERP (top) && !INTEGERP (bottom)))
6426 POINT pt;
6428 /* Default min and max values. */
6429 min_x = 0;
6430 min_y = 0;
6431 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
6432 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
6434 block_input ();
6435 GetCursorPos (&pt);
6436 *root_x = pt.x;
6437 *root_y = pt.y;
6438 unblock_input ();
6440 /* If multiple monitor support is available, constrain the tip onto
6441 the current monitor. This improves the above by allowing negative
6442 co-ordinates if monitor positions are such that they are valid, and
6443 snaps a tooltip onto a single monitor if we are close to the edge
6444 where it would otherwise flow onto the other monitor (or into
6445 nothingness if there is a gap in the overlap). */
6446 if (monitor_from_point_fn && get_monitor_info_fn)
6448 struct MONITOR_INFO info;
6449 HMONITOR monitor
6450 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
6451 info.cbSize = sizeof (info);
6453 if (get_monitor_info_fn (monitor, &info))
6455 min_x = info.rcWork.left;
6456 min_y = info.rcWork.top;
6457 max_x = info.rcWork.right;
6458 max_y = info.rcWork.bottom;
6463 if (INTEGERP (top))
6464 *root_y = XINT (top);
6465 else if (INTEGERP (bottom))
6466 *root_y = XINT (bottom) - height;
6467 else if (*root_y + XINT (dy) <= min_y)
6468 *root_y = min_y; /* Can happen for negative dy */
6469 else if (*root_y + XINT (dy) + height <= max_y)
6470 /* It fits below the pointer */
6471 *root_y += XINT (dy);
6472 else if (height + XINT (dy) + min_y <= *root_y)
6473 /* It fits above the pointer. */
6474 *root_y -= height + XINT (dy);
6475 else
6476 /* Put it on the top. */
6477 *root_y = min_y;
6479 if (INTEGERP (left))
6480 *root_x = XINT (left);
6481 else if (INTEGERP (right))
6482 *root_y = XINT (right) - width;
6483 else if (*root_x + XINT (dx) <= min_x)
6484 *root_x = 0; /* Can happen for negative dx */
6485 else if (*root_x + XINT (dx) + width <= max_x)
6486 /* It fits to the right of the pointer. */
6487 *root_x += XINT (dx);
6488 else if (width + XINT (dx) + min_x <= *root_x)
6489 /* It fits to the left of the pointer. */
6490 *root_x -= width + XINT (dx);
6491 else
6492 /* Put it left justified on the screen -- it ought to fit that way. */
6493 *root_x = min_x;
6497 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
6498 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
6499 A tooltip window is a small window displaying a string.
6501 This is an internal function; Lisp code should call `tooltip-show'.
6503 FRAME nil or omitted means use the selected frame.
6505 PARMS is an optional list of frame parameters which can be
6506 used to change the tooltip's appearance.
6508 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6509 means use the default timeout of 5 seconds.
6511 If the list of frame parameters PARMS contains a `left' parameter,
6512 display the tooltip at that x-position. If the list of frame parameters
6513 PARMS contains no `left' but a `right' parameter, display the tooltip
6514 right-adjusted at that x-position. Otherwise display it at the
6515 x-position of the mouse, with offset DX added (default is 5 if DX isn't
6516 specified).
6518 Likewise for the y-position: If a `top' frame parameter is specified, it
6519 determines the position of the upper edge of the tooltip window. If a
6520 `bottom' parameter but no `top' frame parameter is specified, it
6521 determines the position of the lower edge of the tooltip window.
6522 Otherwise display the tooltip window at the y-position of the mouse,
6523 with offset DY added (default is -10).
6525 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6526 Text larger than the specified size is clipped. */)
6527 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6529 struct frame *f;
6530 struct window *w;
6531 int root_x, root_y;
6532 struct buffer *old_buffer;
6533 struct text_pos pos;
6534 int i, width, height;
6535 bool seen_reversed_p;
6536 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6537 ptrdiff_t count = SPECPDL_INDEX ();
6539 specbind (Qinhibit_redisplay, Qt);
6541 CHECK_STRING (string);
6542 f = decode_window_system_frame (frame);
6543 if (NILP (timeout))
6544 timeout = make_number (5);
6545 else
6546 CHECK_NATNUM (timeout);
6548 if (NILP (dx))
6549 dx = make_number (5);
6550 else
6551 CHECK_NUMBER (dx);
6553 if (NILP (dy))
6554 dy = make_number (-10);
6555 else
6556 CHECK_NUMBER (dy);
6558 if (NILP (last_show_tip_args))
6559 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6561 if (!NILP (tip_frame))
6563 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6564 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6565 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6567 if (EQ (frame, last_frame)
6568 && !NILP (Fequal (last_string, string))
6569 && !NILP (Fequal (last_parms, parms)))
6571 struct frame *f = XFRAME (tip_frame);
6573 /* Only DX and DY have changed. */
6574 if (!NILP (tip_timer))
6576 Lisp_Object timer = tip_timer;
6577 tip_timer = Qnil;
6578 call1 (Qcancel_timer, timer);
6581 block_input ();
6582 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6583 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6585 /* Put tooltip in topmost group and in position. */
6586 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6587 root_x, root_y, 0, 0,
6588 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6590 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6591 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6592 0, 0, 0, 0,
6593 SWP_NOMOVE | SWP_NOSIZE
6594 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6596 unblock_input ();
6597 goto start_timer;
6601 /* Hide a previous tip, if any. */
6602 Fx_hide_tip ();
6604 ASET (last_show_tip_args, 0, string);
6605 ASET (last_show_tip_args, 1, frame);
6606 ASET (last_show_tip_args, 2, parms);
6608 /* Add default values to frame parameters. */
6609 if (NILP (Fassq (Qname, parms)))
6610 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6611 if (NILP (Fassq (Qinternal_border_width, parms)))
6612 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6613 if (NILP (Fassq (Qright_divider_width, parms)))
6614 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6615 if (NILP (Fassq (Qbottom_divider_width, parms)))
6616 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6617 if (NILP (Fassq (Qborder_width, parms)))
6618 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6619 if (NILP (Fassq (Qborder_color, parms)))
6620 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6621 if (NILP (Fassq (Qbackground_color, parms)))
6622 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6623 parms);
6625 /* Block input until the tip has been fully drawn, to avoid crashes
6626 when drawing tips in menus. */
6627 block_input ();
6629 /* Create a frame for the tooltip, and record it in the global
6630 variable tip_frame. */
6631 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6632 f = XFRAME (frame);
6634 /* Set up the frame's root window. */
6635 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6636 w->left_col = 0;
6637 w->top_line = 0;
6638 w->pixel_left = 0;
6639 w->pixel_top = 0;
6641 if (CONSP (Vx_max_tooltip_size)
6642 && INTEGERP (XCAR (Vx_max_tooltip_size))
6643 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6644 && INTEGERP (XCDR (Vx_max_tooltip_size))
6645 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6647 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6648 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6650 else
6652 w->total_cols = 80;
6653 w->total_lines = 40;
6656 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6657 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6659 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6660 adjust_frame_glyphs (f);
6661 w->pseudo_window_p = true;
6663 /* Display the tooltip text in a temporary buffer. */
6664 old_buffer = current_buffer;
6665 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6666 bset_truncate_lines (current_buffer, Qnil);
6667 clear_glyph_matrix (w->desired_matrix);
6668 clear_glyph_matrix (w->current_matrix);
6669 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6670 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6672 /* Compute width and height of the tooltip. */
6673 width = height = 0;
6674 seen_reversed_p = false;
6675 for (i = 0; i < w->desired_matrix->nrows; ++i)
6677 struct glyph_row *row = &w->desired_matrix->rows[i];
6678 struct glyph *last;
6679 int row_width;
6681 /* Stop at the first empty row at the end. */
6682 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6683 break;
6685 /* Let the row go over the full width of the frame. */
6686 row->full_width_p = true;
6688 row_width = row->pixel_width;
6689 if (row->used[TEXT_AREA])
6691 if (!row->reversed_p)
6693 /* There's a glyph at the end of rows that is used to
6694 place the cursor there. Don't include the width of
6695 this glyph. */
6696 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6697 if (NILP (last->object))
6698 row_width -= last->pixel_width;
6700 else
6702 /* There could be a stretch glyph at the beginning of R2L
6703 rows that is produced by extend_face_to_end_of_line.
6704 Don't count that glyph. */
6705 struct glyph *g = row->glyphs[TEXT_AREA];
6707 if (g->type == STRETCH_GLYPH && NILP (g->object))
6709 row_width -= g->pixel_width;
6710 seen_reversed_p = true;
6715 height += row->height;
6716 width = max (width, row_width);
6719 /* If we've seen partial-length R2L rows, we need to re-adjust the
6720 tool-tip frame width and redisplay it again, to avoid over-wide
6721 tips due to the stretch glyph that extends R2L lines to full
6722 width of the frame. */
6723 if (seen_reversed_p)
6725 /* PXW: Why do we do the pixel-to-cols conversion only if
6726 seen_reversed_p holds? Don't we have to set other fields of
6727 the window/frame structure?
6729 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6730 not in pixels. */
6731 w->pixel_width = width;
6732 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6733 w->total_cols = width;
6734 FRAME_TOTAL_COLS (f) = width;
6735 SET_FRAME_WIDTH (f, width);
6736 adjust_frame_glyphs (f);
6737 w->pseudo_window_p = 1;
6738 clear_glyph_matrix (w->desired_matrix);
6739 clear_glyph_matrix (w->current_matrix);
6740 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6741 width = height = 0;
6742 /* Recompute width and height of the tooltip. */
6743 for (i = 0; i < w->desired_matrix->nrows; ++i)
6745 struct glyph_row *row = &w->desired_matrix->rows[i];
6746 struct glyph *last;
6747 int row_width;
6749 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6750 break;
6751 row->full_width_p = true;
6752 row_width = row->pixel_width;
6753 if (row->used[TEXT_AREA] && !row->reversed_p)
6755 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6756 if (NILP (last->object))
6757 row_width -= last->pixel_width;
6760 height += row->height;
6761 width = max (width, row_width);
6765 /* Add the frame's internal border to the width and height the w32
6766 window should have. */
6767 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6768 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6770 /* Move the tooltip window where the mouse pointer is. Resize and
6771 show it.
6773 PXW: This should use the frame's pixel coordinates. */
6774 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6777 /* Adjust Window size to take border into account. */
6778 RECT rect;
6779 rect.left = rect.top = 0;
6780 rect.right = width;
6781 rect.bottom = height;
6782 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6783 FRAME_EXTERNAL_MENU_BAR (f));
6785 /* Position and size tooltip, and put it in the topmost group.
6786 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6787 peculiarity of w32 display: without it, some fonts cause the
6788 last character of the tip to be truncated or wrapped around to
6789 the next line. */
6790 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6791 root_x, root_y,
6792 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6793 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6795 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6796 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6797 0, 0, 0, 0,
6798 SWP_NOMOVE | SWP_NOSIZE
6799 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6801 /* Let redisplay know that we have made the frame visible already. */
6802 SET_FRAME_VISIBLE (f, 1);
6804 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6807 /* Draw into the window. */
6808 w->must_be_updated_p = true;
6809 update_single_window (w);
6811 unblock_input ();
6813 /* Restore original current buffer. */
6814 set_buffer_internal_1 (old_buffer);
6815 windows_or_buffers_changed = old_windows_or_buffers_changed;
6817 start_timer:
6818 /* Let the tip disappear after timeout seconds. */
6819 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6820 intern ("x-hide-tip"));
6822 return unbind_to (count, Qnil);
6826 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6827 doc: /* Hide the current tooltip window, if there is any.
6828 Value is t if tooltip was open, nil otherwise. */)
6829 (void)
6831 ptrdiff_t count;
6832 Lisp_Object deleted, frame, timer;
6834 /* Return quickly if nothing to do. */
6835 if (NILP (tip_timer) && NILP (tip_frame))
6836 return Qnil;
6838 frame = tip_frame;
6839 timer = tip_timer;
6840 tip_frame = tip_timer = deleted = Qnil;
6842 count = SPECPDL_INDEX ();
6843 specbind (Qinhibit_redisplay, Qt);
6844 specbind (Qinhibit_quit, Qt);
6846 if (!NILP (timer))
6847 call1 (Qcancel_timer, timer);
6849 if (FRAMEP (frame))
6851 delete_frame (frame, Qnil);
6852 deleted = Qt;
6855 return unbind_to (count, deleted);
6858 /***********************************************************************
6859 File selection dialog
6860 ***********************************************************************/
6862 #define FILE_NAME_TEXT_FIELD edt1
6863 #define FILE_NAME_COMBO_BOX cmb13
6864 #define FILE_NAME_LIST lst1
6866 /* Callback for altering the behavior of the Open File dialog.
6867 Makes the Filename text field contain "Current Directory" and be
6868 read-only when "Directories" is selected in the filter. This
6869 allows us to work around the fact that the standard Open File
6870 dialog does not support directories. */
6871 static UINT_PTR CALLBACK
6872 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6874 if (msg == WM_NOTIFY)
6876 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6877 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6878 int dropdown_changed;
6879 int dir_index;
6880 #ifdef NTGUI_UNICODE
6881 const int use_unicode = 1;
6882 #else /* !NTGUI_UNICODE */
6883 int use_unicode = w32_unicode_filenames;
6884 #endif /* NTGUI_UNICODE */
6886 /* Detect when the Filter dropdown is changed. */
6887 if (use_unicode)
6888 dropdown_changed =
6889 notify_w->hdr.code == CDN_TYPECHANGE
6890 || notify_w->hdr.code == CDN_INITDONE;
6891 else
6892 dropdown_changed =
6893 notify_a->hdr.code == CDN_TYPECHANGE
6894 || notify_a->hdr.code == CDN_INITDONE;
6895 if (dropdown_changed)
6897 HWND dialog = GetParent (hwnd);
6898 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6899 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6900 int hdr_code;
6902 /* At least on Windows 7, the above attempt to get the window handle
6903 to the File Name Text Field fails. The following code does the
6904 job though. Note that this code is based on my examination of the
6905 window hierarchy using Microsoft Spy++. bk */
6906 if (edit_control == NULL)
6908 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6909 if (tmp)
6911 tmp = GetWindow (tmp, GW_CHILD);
6912 if (tmp)
6913 edit_control = GetWindow (tmp, GW_CHILD);
6917 /* Directories is in index 2. */
6918 if (use_unicode)
6920 dir_index = notify_w->lpOFN->nFilterIndex;
6921 hdr_code = notify_w->hdr.code;
6923 else
6925 dir_index = notify_a->lpOFN->nFilterIndex;
6926 hdr_code = notify_a->hdr.code;
6928 if (dir_index == 2)
6930 if (use_unicode)
6931 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6932 (LPARAM)L"Current Directory");
6933 else
6934 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6935 (LPARAM)"Current Directory");
6936 EnableWindow (edit_control, FALSE);
6937 /* Note that at least on Windows 7, the above call to EnableWindow
6938 disables the window that would ordinarily have focus. If we
6939 do not set focus to some other window here, focus will land in
6940 no man's land and the user will be unable to tab through the
6941 dialog box (pressing tab will only result in a beep).
6942 Avoid that problem by setting focus to the list here. */
6943 if (hdr_code == CDN_INITDONE)
6944 SetFocus (list);
6946 else
6948 /* Don't override default filename on init done. */
6949 if (hdr_code == CDN_TYPECHANGE)
6951 if (use_unicode)
6952 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6953 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6954 else
6955 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6956 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6958 EnableWindow (edit_control, TRUE);
6962 return 0;
6965 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6966 doc: /* Read file name, prompting with PROMPT in directory DIR.
6967 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6968 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6969 or directory must exist.
6971 This function is only defined on NS, MS Windows, and X Windows with the
6972 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6973 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6974 On Windows 7 and later, the file selection dialog "remembers" the last
6975 directory where the user selected a file, and will open that directory
6976 instead of DIR on subsequent invocations of this function with the same
6977 value of DIR as in previous invocations; this is standard Windows behavior. */)
6978 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6980 /* Filter index: 1: All Files, 2: Directories only */
6981 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6982 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6984 Lisp_Object filename = default_filename;
6985 struct frame *f = SELECTED_FRAME ();
6986 BOOL file_opened = FALSE;
6987 Lisp_Object orig_dir = dir;
6988 Lisp_Object orig_prompt = prompt;
6990 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6991 compatibility) we end up with the old file dialogs. Define a big
6992 enough struct for the new dialog to trick GetOpenFileName into
6993 giving us the new dialogs on newer versions of Windows. */
6994 struct {
6995 OPENFILENAMEW details;
6996 #if _WIN32_WINNT < 0x500 /* < win2k */
6997 PVOID pvReserved;
6998 DWORD dwReserved;
6999 DWORD FlagsEx;
7000 #endif /* < win2k */
7001 } new_file_details_w;
7003 #ifdef NTGUI_UNICODE
7004 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
7005 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7006 const int use_unicode = 1;
7007 #else /* not NTGUI_UNICODE */
7008 struct {
7009 OPENFILENAMEA details;
7010 #if _WIN32_WINNT < 0x500 /* < win2k */
7011 PVOID pvReserved;
7012 DWORD dwReserved;
7013 DWORD FlagsEx;
7014 #endif /* < win2k */
7015 } new_file_details_a;
7016 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7017 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7018 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7019 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7020 int use_unicode = w32_unicode_filenames;
7021 wchar_t *prompt_w;
7022 char *prompt_a;
7023 int len;
7024 char fname_ret[MAX_UTF8_PATH];
7025 #endif /* NTGUI_UNICODE */
7028 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7029 system file encoding expected by the platform APIs (e.g. Cygwin's
7030 POSIX implementation) may not be the same as the encoding expected
7031 by the Windows "ANSI" APIs! */
7033 CHECK_STRING (prompt);
7034 CHECK_STRING (dir);
7036 dir = Fexpand_file_name (dir, Qnil);
7038 if (STRINGP (filename))
7039 filename = Ffile_name_nondirectory (filename);
7040 else
7041 filename = empty_unibyte_string;
7043 #ifdef CYGWIN
7044 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7045 if (SCHARS (filename) > 0)
7046 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7047 #endif
7049 CHECK_STRING (dir);
7050 CHECK_STRING (filename);
7052 /* The code in file_dialog_callback that attempts to set the text
7053 of the file name edit window when handling the CDN_INITDONE
7054 WM_NOTIFY message does not work. Setting filename to "Current
7055 Directory" in the only_dir_p case here does work however. */
7056 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7057 filename = build_string ("Current Directory");
7059 /* Convert the values we've computed so far to system form. */
7060 #ifdef NTGUI_UNICODE
7061 to_unicode (prompt, &prompt);
7062 to_unicode (dir, &dir);
7063 to_unicode (filename, &filename);
7064 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7065 report_file_error ("filename too long", default_filename);
7067 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7068 #else /* !NTGUI_UNICODE */
7069 prompt = ENCODE_FILE (prompt);
7070 dir = ENCODE_FILE (dir);
7071 filename = ENCODE_FILE (filename);
7073 /* We modify these in-place, so make copies for safety. */
7074 dir = Fcopy_sequence (dir);
7075 unixtodos_filename (SDATA (dir));
7076 filename = Fcopy_sequence (filename);
7077 unixtodos_filename (SDATA (filename));
7078 if (SBYTES (filename) >= MAX_UTF8_PATH)
7079 report_file_error ("filename too long", default_filename);
7080 if (w32_unicode_filenames)
7082 filename_to_utf16 (SSDATA (dir), dir_w);
7083 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7085 /* filename_to_utf16 sets errno to ENOENT when the file
7086 name is too long or cannot be converted to UTF-16. */
7087 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7088 report_file_error ("filename too long", default_filename);
7090 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7091 SSDATA (prompt), -1, NULL, 0);
7092 if (len > 32768)
7093 len = 32768;
7094 prompt_w = alloca (len * sizeof (wchar_t));
7095 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7096 SSDATA (prompt), -1, prompt_w, len);
7098 else
7100 filename_to_ansi (SSDATA (dir), dir_a);
7101 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7103 /* filename_to_ansi sets errno to ENOENT when the file
7104 name is too long or cannot be converted to UTF-16. */
7105 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7106 report_file_error ("filename too long", default_filename);
7108 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7109 SSDATA (prompt), -1, NULL, 0);
7110 if (len > 32768)
7111 len = 32768;
7112 prompt_w = alloca (len * sizeof (wchar_t));
7113 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7114 SSDATA (prompt), -1, prompt_w, len);
7115 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7116 if (len > 32768)
7117 len = 32768;
7118 prompt_a = alloca (len);
7119 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7121 #endif /* NTGUI_UNICODE */
7123 /* Fill in the structure for the call to GetOpenFileName below.
7124 For NTGUI_UNICODE builds (which run only on NT), we just use
7125 the actual size of the structure. For non-NTGUI_UNICODE
7126 builds, we tell the OS we're using an old version of the
7127 structure if the OS isn't new enough to support the newer
7128 version. */
7129 if (use_unicode)
7131 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7132 if (w32_major_version > 4 && w32_major_version < 95)
7133 file_details_w->lStructSize = sizeof (new_file_details_w);
7134 else
7135 file_details_w->lStructSize = sizeof (*file_details_w);
7136 /* Set up the inout parameter for the selected file name. */
7137 file_details_w->lpstrFile = filename_buf_w;
7138 file_details_w->nMaxFile =
7139 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7140 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7141 /* Undocumented Bug in Common File Dialog:
7142 If a filter is not specified, shell links are not resolved. */
7143 file_details_w->lpstrFilter = filter_w;
7144 #ifdef NTGUI_UNICODE
7145 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7146 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7147 #else
7148 file_details_w->lpstrInitialDir = dir_w;
7149 file_details_w->lpstrTitle = prompt_w;
7150 #endif
7151 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7152 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7153 | OFN_EXPLORER | OFN_ENABLEHOOK);
7154 if (!NILP (mustmatch))
7156 /* Require that the path to the parent directory exists. */
7157 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7158 /* If we are looking for a file, require that it exists. */
7159 if (NILP (only_dir_p))
7160 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7163 #ifndef NTGUI_UNICODE
7164 else
7166 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7167 if (w32_major_version > 4 && w32_major_version < 95)
7168 file_details_a->lStructSize = sizeof (new_file_details_a);
7169 else
7170 file_details_a->lStructSize = sizeof (*file_details_a);
7171 file_details_a->lpstrFile = filename_buf_a;
7172 file_details_a->nMaxFile =
7173 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7174 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7175 file_details_a->lpstrFilter = filter_a;
7176 file_details_a->lpstrInitialDir = dir_a;
7177 file_details_a->lpstrTitle = prompt_a;
7178 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7179 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7180 | OFN_EXPLORER | OFN_ENABLEHOOK);
7181 if (!NILP (mustmatch))
7183 /* Require that the path to the parent directory exists. */
7184 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7185 /* If we are looking for a file, require that it exists. */
7186 if (NILP (only_dir_p))
7187 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7190 #endif /* !NTGUI_UNICODE */
7193 int count = SPECPDL_INDEX ();
7194 /* Prevent redisplay. */
7195 specbind (Qinhibit_redisplay, Qt);
7196 block_input ();
7197 if (use_unicode)
7199 file_details_w->lpfnHook = file_dialog_callback;
7201 file_opened = GetOpenFileNameW (file_details_w);
7203 #ifndef NTGUI_UNICODE
7204 else
7206 file_details_a->lpfnHook = file_dialog_callback;
7208 file_opened = GetOpenFileNameA (file_details_a);
7210 #endif /* !NTGUI_UNICODE */
7211 unblock_input ();
7212 unbind_to (count, Qnil);
7215 if (file_opened)
7217 /* Get an Emacs string from the value Windows gave us. */
7218 #ifdef NTGUI_UNICODE
7219 filename = from_unicode_buffer (filename_buf_w);
7220 #else /* !NTGUI_UNICODE */
7221 if (use_unicode)
7222 filename_from_utf16 (filename_buf_w, fname_ret);
7223 else
7224 filename_from_ansi (filename_buf_a, fname_ret);
7225 dostounix_filename (fname_ret);
7226 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7227 #endif /* NTGUI_UNICODE */
7229 #ifdef CYGWIN
7230 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7231 #endif /* CYGWIN */
7233 /* Strip the dummy filename off the end of the string if we
7234 added it to select a directory. */
7235 if ((use_unicode && file_details_w->nFilterIndex == 2)
7236 #ifndef NTGUI_UNICODE
7237 || (!use_unicode && file_details_a->nFilterIndex == 2)
7238 #endif
7240 filename = Ffile_name_directory (filename);
7242 /* User canceled the dialog without making a selection. */
7243 else if (!CommDlgExtendedError ())
7244 filename = Qnil;
7245 /* An error occurred, fallback on reading from the mini-buffer. */
7246 else
7247 filename = Fcompleting_read (
7248 orig_prompt,
7249 intern ("read-file-name-internal"),
7250 orig_dir,
7251 mustmatch,
7252 orig_dir,
7253 Qfile_name_history,
7254 default_filename,
7255 Qnil);
7258 /* Make "Cancel" equivalent to C-g. */
7259 if (NILP (filename))
7260 Fsignal (Qquit, Qnil);
7262 return filename;
7266 #ifdef WINDOWSNT
7267 /* Moving files to the system recycle bin.
7268 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
7269 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
7270 Ssystem_move_file_to_trash, 1, 1, 0,
7271 doc: /* Move file or directory named FILENAME to the recycle bin. */)
7272 (Lisp_Object filename)
7274 Lisp_Object handler;
7275 Lisp_Object encoded_file;
7276 Lisp_Object operation;
7278 operation = Qdelete_file;
7279 if (!NILP (Ffile_directory_p (filename))
7280 && NILP (Ffile_symlink_p (filename)))
7282 operation = intern ("delete-directory");
7283 filename = Fdirectory_file_name (filename);
7286 /* Must have fully qualified file names for moving files to Recycle
7287 Bin. */
7288 filename = Fexpand_file_name (filename, Qnil);
7290 handler = Ffind_file_name_handler (filename, operation);
7291 if (!NILP (handler))
7292 return call2 (handler, operation, filename);
7293 else
7295 const char * path;
7296 int result;
7298 encoded_file = ENCODE_FILE (filename);
7300 path = map_w32_filename (SDATA (encoded_file), NULL);
7302 /* The Unicode version of SHFileOperation is not supported on
7303 Windows 9X. */
7304 if (w32_unicode_filenames && os_subtype != OS_9X)
7306 SHFILEOPSTRUCTW file_op_w;
7307 /* We need one more element beyond MAX_PATH because this is
7308 a list of file names, with the last element double-null
7309 terminated. */
7310 wchar_t tmp_path_w[MAX_PATH + 1];
7312 memset (tmp_path_w, 0, sizeof (tmp_path_w));
7313 filename_to_utf16 (path, tmp_path_w);
7315 /* On Windows, write permission is required to delete/move files. */
7316 _wchmod (tmp_path_w, 0666);
7318 memset (&file_op_w, 0, sizeof (file_op_w));
7319 file_op_w.hwnd = HWND_DESKTOP;
7320 file_op_w.wFunc = FO_DELETE;
7321 file_op_w.pFrom = tmp_path_w;
7322 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7323 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7324 file_op_w.fAnyOperationsAborted = FALSE;
7326 result = SHFileOperationW (&file_op_w);
7328 else
7330 SHFILEOPSTRUCTA file_op_a;
7331 char tmp_path_a[MAX_PATH + 1];
7333 memset (tmp_path_a, 0, sizeof (tmp_path_a));
7334 filename_to_ansi (path, tmp_path_a);
7336 /* If a file cannot be represented in ANSI codepage, don't
7337 let them inadvertently delete other files because some
7338 characters are interpreted as a wildcards. */
7339 if (_mbspbrk (tmp_path_a, "?*"))
7340 result = ERROR_FILE_NOT_FOUND;
7341 else
7343 _chmod (tmp_path_a, 0666);
7345 memset (&file_op_a, 0, sizeof (file_op_a));
7346 file_op_a.hwnd = HWND_DESKTOP;
7347 file_op_a.wFunc = FO_DELETE;
7348 file_op_a.pFrom = tmp_path_a;
7349 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7350 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7351 file_op_a.fAnyOperationsAborted = FALSE;
7353 result = SHFileOperationA (&file_op_a);
7356 if (result != 0)
7357 report_file_error ("Removing old name", list1 (filename));
7359 return Qnil;
7362 #endif /* WINDOWSNT */
7365 /***********************************************************************
7366 w32 specialized functions
7367 ***********************************************************************/
7369 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
7370 Sw32_send_sys_command, 1, 2, 0,
7371 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
7372 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
7373 to minimize), #xf120 to restore frame to original size, and #xf100
7374 to activate the menubar for keyboard access. #xf140 activates the
7375 screen saver if defined.
7377 If optional parameter FRAME is not specified, use selected frame. */)
7378 (Lisp_Object command, Lisp_Object frame)
7380 struct frame *f = decode_window_system_frame (frame);
7382 CHECK_NUMBER (command);
7384 if (FRAME_W32_P (f))
7385 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
7387 return Qnil;
7390 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
7391 doc: /* Get Windows to perform OPERATION on DOCUMENT.
7392 This is a wrapper around the ShellExecute system function, which
7393 invokes the application registered to handle OPERATION for DOCUMENT.
7395 OPERATION is either nil or a string that names a supported operation.
7396 What operations can be used depends on the particular DOCUMENT and its
7397 handler application, but typically it is one of the following common
7398 operations:
7400 \"open\" - open DOCUMENT, which could be a file, a directory, or an
7401 executable program (application). If it is an application,
7402 that application is launched in the current buffer's default
7403 directory. Otherwise, the application associated with
7404 DOCUMENT is launched in the buffer's default directory.
7405 \"opennew\" - like \"open\", but instruct the application to open
7406 DOCUMENT in a new window.
7407 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
7408 \"print\" - print DOCUMENT, which must be a file.
7409 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
7410 The printer should be provided in PARAMETERS, see below.
7411 \"explore\" - start the Windows Explorer on DOCUMENT.
7412 \"edit\" - launch an editor and open DOCUMENT for editing; which
7413 editor is launched depends on the association for the
7414 specified DOCUMENT.
7415 \"find\" - initiate search starting from DOCUMENT, which must specify
7416 a directory.
7417 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
7418 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
7419 the clipboard.
7420 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
7421 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
7422 which must be a directory.
7423 \"pastelink\"
7424 - create a shortcut in DOCUMENT (which must be a directory)
7425 the file or directory whose name is in the clipboard.
7426 \"runas\" - run DOCUMENT, which must be an excutable file, with
7427 elevated privileges (a.k.a. \"as Administrator\").
7428 \"properties\"
7429 - open the property sheet dialog for DOCUMENT.
7430 nil - invoke the default OPERATION, or \"open\" if default is
7431 not defined or unavailable.
7433 DOCUMENT is typically the name of a document file or a URL, but can
7434 also be an executable program to run, or a directory to open in the
7435 Windows Explorer. If it is a file or a directory, it must be a local
7436 one; this function does not support remote file names.
7438 If DOCUMENT is an executable program, the optional third arg PARAMETERS
7439 can be a string containing command line parameters, separated by blanks,
7440 that will be passed to the program. Some values of OPERATION also require
7441 parameters (e.g., \"printto\" requires the printer address). Otherwise,
7442 PARAMETERS should be nil or unspecified. Note that double quote characters
7443 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
7445 Optional fourth argument SHOW-FLAG can be used to control how the
7446 application will be displayed when it is invoked. If SHOW-FLAG is nil
7447 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
7448 specified, otherwise it is an integer between 0 and 11 representing
7449 a ShowWindow flag:
7451 0 - start hidden
7452 1 - start as normal-size window
7453 3 - start in a maximized window
7454 6 - start in a minimized window
7455 10 - start as the application itself specifies; this is the default. */)
7456 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
7458 char *errstr;
7459 Lisp_Object current_dir = BVAR (current_buffer, directory);;
7460 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
7461 #ifdef CYGWIN
7462 intptr_t result;
7463 #else
7464 int use_unicode = w32_unicode_filenames;
7465 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
7466 Lisp_Object absdoc, handler;
7467 BOOL success;
7468 #endif
7470 CHECK_STRING (document);
7472 #ifdef CYGWIN
7473 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
7474 document = Fcygwin_convert_file_name_to_windows (document, Qt);
7476 /* Encode filename, current directory and parameters. */
7477 current_dir = GUI_ENCODE_FILE (current_dir);
7478 document = GUI_ENCODE_FILE (document);
7479 doc_w = GUI_SDATA (document);
7480 if (STRINGP (parameters))
7482 parameters = GUI_ENCODE_SYSTEM (parameters);
7483 params_w = GUI_SDATA (parameters);
7485 if (STRINGP (operation))
7487 operation = GUI_ENCODE_SYSTEM (operation);
7488 ops_w = GUI_SDATA (operation);
7490 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7491 GUI_SDATA (current_dir),
7492 (INTEGERP (show_flag)
7493 ? XINT (show_flag) : SW_SHOWDEFAULT));
7495 if (result > 32)
7496 return Qt;
7498 switch (result)
7500 case SE_ERR_ACCESSDENIED:
7501 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7502 break;
7503 case SE_ERR_ASSOCINCOMPLETE:
7504 case SE_ERR_NOASSOC:
7505 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7506 break;
7507 case SE_ERR_DDEBUSY:
7508 case SE_ERR_DDEFAIL:
7509 errstr = w32_strerror (ERROR_DDE_FAIL);
7510 break;
7511 case SE_ERR_DDETIMEOUT:
7512 errstr = w32_strerror (ERROR_TIMEOUT);
7513 break;
7514 case SE_ERR_DLLNOTFOUND:
7515 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7516 break;
7517 case SE_ERR_FNF:
7518 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7519 break;
7520 case SE_ERR_OOM:
7521 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7522 break;
7523 case SE_ERR_PNF:
7524 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7525 break;
7526 case SE_ERR_SHARE:
7527 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7528 break;
7529 default:
7530 errstr = w32_strerror (0);
7531 break;
7534 #else /* !CYGWIN */
7536 const char file_url_str[] = "file:///";
7537 const int file_url_len = sizeof (file_url_str) - 1;
7538 int doclen;
7540 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
7542 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
7543 start a thread in some rare system configurations, for
7544 unknown reasons. That thread is started in the context of
7545 the Emacs process, but out of control of our code, and seems
7546 to never exit afterwards. Each such thread reserves 8MB of
7547 stack space (because that's the value recorded in the Emacs
7548 executable at link time: Emacs needs a large stack). So a
7549 large enough number of invocations of w32-shell-execute can
7550 potentially cause the Emacs process to run out of available
7551 address space, which is nasty. To work around this, we
7552 convert such URLs to local file names, which seems to prevent
7553 those threads from starting. See bug #20220. */
7554 char *p = SSDATA (document) + file_url_len;
7556 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
7557 document = Fsubstring_no_properties (document,
7558 make_number (file_url_len), Qnil);
7560 /* We have a situation here. If DOCUMENT is a relative file name,
7561 but its name includes leading directories, i.e. it lives not in
7562 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7563 will fail to find it. So we need to make the file name is
7564 absolute. But DOCUMENT does not have to be a file, it can be a
7565 URL, for example. So we make it absolute only if it is an
7566 existing file; if it is a file that does not exist, tough. */
7567 absdoc = Fexpand_file_name (document, Qnil);
7568 /* Don't call file handlers for file-exists-p, since they might
7569 attempt to access the file, which could fail or produce undesired
7570 consequences, see bug#16558 for an example. */
7571 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7572 if (NILP (handler))
7574 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7576 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7578 /* ShellExecute fails if DOCUMENT is a UNC with forward
7579 slashes (expand-file-name above converts all backslashes
7580 to forward slashes). Now that we know DOCUMENT is a
7581 file, we can mirror all forward slashes into backslashes. */
7582 unixtodos_filename (SSDATA (absdoc_encoded));
7583 document = absdoc_encoded;
7585 else
7586 document = ENCODE_FILE (document);
7588 else
7589 document = ENCODE_FILE (document);
7591 current_dir = ENCODE_FILE (current_dir);
7592 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
7593 be a URL that is not limited to MAX_PATH chararcters. */
7594 doclen = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7595 SSDATA (document), -1, NULL, 0);
7596 doc_w = xmalloc (doclen * sizeof (wchar_t));
7597 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
7598 SSDATA (document), -1, doc_w, doclen);
7599 if (use_unicode)
7601 wchar_t current_dir_w[MAX_PATH];
7602 SHELLEXECUTEINFOW shexinfo_w;
7604 /* Encode the current directory and parameters, and convert
7605 operation to UTF-16. */
7606 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7607 if (STRINGP (parameters))
7609 int len;
7611 parameters = ENCODE_SYSTEM (parameters);
7612 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7613 SSDATA (parameters), -1, NULL, 0);
7614 if (len > 32768)
7615 len = 32768;
7616 params_w = alloca (len * sizeof (wchar_t));
7617 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7618 SSDATA (parameters), -1, params_w, len);
7619 params_w[len - 1] = 0;
7621 if (STRINGP (operation))
7623 /* Assume OPERATION is pure ASCII. */
7624 const char *s = SSDATA (operation);
7625 wchar_t *d;
7626 int len = SBYTES (operation) + 1;
7628 if (len > 32768)
7629 len = 32768;
7630 d = ops_w = alloca (len * sizeof (wchar_t));
7631 while (d < ops_w + len - 1)
7632 *d++ = *s++;
7633 *d = 0;
7636 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7637 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7638 able to invoke verbs from shortcut menu extensions, not just
7639 static verbs listed in the Registry. */
7640 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7641 shexinfo_w.cbSize = sizeof (shexinfo_w);
7642 shexinfo_w.fMask =
7643 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7644 shexinfo_w.hwnd = NULL;
7645 shexinfo_w.lpVerb = ops_w;
7646 shexinfo_w.lpFile = doc_w;
7647 shexinfo_w.lpParameters = params_w;
7648 shexinfo_w.lpDirectory = current_dir_w;
7649 shexinfo_w.nShow =
7650 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7651 success = ShellExecuteExW (&shexinfo_w);
7652 xfree (doc_w);
7654 else
7656 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7657 SHELLEXECUTEINFOA shexinfo_a;
7658 int codepage = codepage_for_filenames (NULL);
7659 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
7660 NULL, NULL);
7662 doc_a = xmalloc (ldoc_a);
7663 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
7664 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7665 if (STRINGP (parameters))
7667 parameters = ENCODE_SYSTEM (parameters);
7668 params_a = SSDATA (parameters);
7670 if (STRINGP (operation))
7672 /* Assume OPERATION is pure ASCII. */
7673 ops_a = SSDATA (operation);
7675 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7676 shexinfo_a.cbSize = sizeof (shexinfo_a);
7677 shexinfo_a.fMask =
7678 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7679 shexinfo_a.hwnd = NULL;
7680 shexinfo_a.lpVerb = ops_a;
7681 shexinfo_a.lpFile = doc_a;
7682 shexinfo_a.lpParameters = params_a;
7683 shexinfo_a.lpDirectory = current_dir_a;
7684 shexinfo_a.nShow =
7685 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7686 success = ShellExecuteExA (&shexinfo_a);
7687 xfree (doc_w);
7688 xfree (doc_a);
7691 if (success)
7692 return Qt;
7694 errstr = w32_strerror (0);
7696 #endif /* !CYGWIN */
7698 /* The error string might be encoded in the locale's encoding. */
7699 if (!NILP (Vlocale_coding_system))
7701 Lisp_Object decoded =
7702 code_convert_string_norecord (build_unibyte_string (errstr),
7703 Vlocale_coding_system, 0);
7704 errstr = SSDATA (decoded);
7706 error ("ShellExecute failed: %s", errstr);
7709 /* Lookup virtual keycode from string representing the name of a
7710 non-ascii keystroke into the corresponding virtual key, using
7711 lispy_function_keys. */
7712 static int
7713 lookup_vk_code (char *key)
7715 int i;
7717 for (i = 0; i < 256; i++)
7718 if (lispy_function_keys[i]
7719 && strcmp (lispy_function_keys[i], key) == 0)
7720 return i;
7722 return -1;
7725 /* Convert a one-element vector style key sequence to a hot key
7726 definition. */
7727 static Lisp_Object
7728 w32_parse_hot_key (Lisp_Object key)
7730 /* Copied from Fdefine_key and store_in_keymap. */
7731 register Lisp_Object c;
7732 int vk_code;
7733 int lisp_modifiers;
7734 int w32_modifiers;
7736 CHECK_VECTOR (key);
7738 if (ASIZE (key) != 1)
7739 return Qnil;
7741 c = AREF (key, 0);
7743 if (CONSP (c) && lucid_event_type_list_p (c))
7744 c = Fevent_convert_list (c);
7746 if (! INTEGERP (c) && ! SYMBOLP (c))
7747 error ("Key definition is invalid");
7749 /* Work out the base key and the modifiers. */
7750 if (SYMBOLP (c))
7752 c = parse_modifiers (c);
7753 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7754 c = Fcar (c);
7755 if (!SYMBOLP (c))
7756 emacs_abort ();
7757 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7759 else if (INTEGERP (c))
7761 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7762 /* Many ascii characters are their own virtual key code. */
7763 vk_code = XINT (c) & CHARACTERBITS;
7766 if (vk_code < 0 || vk_code > 255)
7767 return Qnil;
7769 if ((lisp_modifiers & meta_modifier) != 0
7770 && !NILP (Vw32_alt_is_meta))
7771 lisp_modifiers |= alt_modifier;
7773 /* Supply defs missing from mingw32. */
7774 #ifndef MOD_ALT
7775 #define MOD_ALT 0x0001
7776 #define MOD_CONTROL 0x0002
7777 #define MOD_SHIFT 0x0004
7778 #define MOD_WIN 0x0008
7779 #endif
7781 /* Convert lisp modifiers to Windows hot-key form. */
7782 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7783 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7784 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7785 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7787 return HOTKEY (vk_code, w32_modifiers);
7790 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7791 Sw32_register_hot_key, 1, 1, 0,
7792 doc: /* Register KEY as a hot-key combination.
7793 Certain key combinations like Alt-Tab are reserved for system use on
7794 Windows, and therefore are normally intercepted by the system. However,
7795 most of these key combinations can be received by registering them as
7796 hot-keys, overriding their special meaning.
7798 KEY must be a one element key definition in vector form that would be
7799 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7800 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7801 is always interpreted as the Windows modifier keys.
7803 The return value is the hotkey-id if registered, otherwise nil. */)
7804 (Lisp_Object key)
7806 key = w32_parse_hot_key (key);
7808 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7810 /* Reuse an empty slot if possible. */
7811 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7813 /* Safe to add new key to list, even if we have focus. */
7814 if (NILP (item))
7815 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7816 else
7817 XSETCAR (item, key);
7819 /* Notify input thread about new hot-key definition, so that it
7820 takes effect without needing to switch focus. */
7821 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7822 (WPARAM) XINT (key), 0);
7825 return key;
7828 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7829 Sw32_unregister_hot_key, 1, 1, 0,
7830 doc: /* Unregister KEY as a hot-key combination. */)
7831 (Lisp_Object key)
7833 Lisp_Object item;
7835 if (!INTEGERP (key))
7836 key = w32_parse_hot_key (key);
7838 item = Fmemq (key, w32_grabbed_keys);
7840 if (!NILP (item))
7842 LPARAM lparam;
7844 eassert (CONSP (item));
7845 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
7846 so that it works in a --with-wide-int build as well. */
7847 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
7849 /* Notify input thread about hot-key definition being removed, so
7850 that it takes effect without needing focus switch. */
7851 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7852 (WPARAM) XINT (XCAR (item)), lparam))
7854 MSG msg;
7855 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7857 return Qt;
7859 return Qnil;
7862 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7863 Sw32_registered_hot_keys, 0, 0, 0,
7864 doc: /* Return list of registered hot-key IDs. */)
7865 (void)
7867 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7870 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7871 Sw32_reconstruct_hot_key, 1, 1, 0,
7872 doc: /* Convert hot-key ID to a lisp key combination.
7873 usage: (w32-reconstruct-hot-key ID) */)
7874 (Lisp_Object hotkeyid)
7876 int vk_code, w32_modifiers;
7877 Lisp_Object key;
7879 CHECK_NUMBER (hotkeyid);
7881 vk_code = HOTKEY_VK_CODE (hotkeyid);
7882 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7884 if (vk_code < 256 && lispy_function_keys[vk_code])
7885 key = intern (lispy_function_keys[vk_code]);
7886 else
7887 key = make_number (vk_code);
7889 key = Fcons (key, Qnil);
7890 if (w32_modifiers & MOD_SHIFT)
7891 key = Fcons (Qshift, key);
7892 if (w32_modifiers & MOD_CONTROL)
7893 key = Fcons (Qctrl, key);
7894 if (w32_modifiers & MOD_ALT)
7895 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7896 if (w32_modifiers & MOD_WIN)
7897 key = Fcons (Qhyper, key);
7899 return key;
7902 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7903 Sw32_toggle_lock_key, 1, 2, 0,
7904 doc: /* Toggle the state of the lock key KEY.
7905 KEY can be `capslock', `kp-numlock', or `scroll'.
7906 If the optional parameter NEW-STATE is a number, then the state of KEY
7907 is set to off if the low bit of NEW-STATE is zero, otherwise on.
7908 If NEW-STATE is omitted or nil, the function toggles the state,
7910 Value is the new state of the key, or nil if the function failed
7911 to change the state. */)
7912 (Lisp_Object key, Lisp_Object new_state)
7914 int vk_code;
7915 LPARAM lparam;
7917 if (EQ (key, intern ("capslock")))
7918 vk_code = VK_CAPITAL;
7919 else if (EQ (key, intern ("kp-numlock")))
7920 vk_code = VK_NUMLOCK;
7921 else if (EQ (key, intern ("scroll")))
7922 vk_code = VK_SCROLL;
7923 else
7924 return Qnil;
7926 if (!dwWindowsThreadId)
7927 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7929 if (NILP (new_state))
7930 lparam = -1;
7931 else
7932 lparam = (XUINT (new_state)) & 1;
7933 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7934 (WPARAM) vk_code, lparam))
7936 MSG msg;
7937 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7938 return make_number (msg.wParam);
7940 return Qnil;
7943 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7944 2, 2, 0,
7945 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7947 This is a direct interface to the Windows API FindWindow function. */)
7948 (Lisp_Object class, Lisp_Object name)
7950 HWND hnd;
7952 if (!NILP (class))
7953 CHECK_STRING (class);
7954 if (!NILP (name))
7955 CHECK_STRING (name);
7957 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7958 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7959 if (!hnd)
7960 return Qnil;
7961 return Qt;
7964 DEFUN ("w32-frame-geometry", Fw32_frame_geometry, Sw32_frame_geometry, 0, 1, 0,
7965 doc: /* Return geometric attributes of FRAME.
7966 FRAME must be a live frame and defaults to the selected one. The return
7967 value is an association list of the attributes listed below. All height
7968 and width values are in pixels.
7970 `outer-position' is a cons of the outer left and top edges of FRAME
7971 relative to the origin - the position (0, 0) - of FRAME's display.
7973 `outer-size' is a cons of the outer width and height of FRAME. The
7974 outer size includes the title bar and the external borders as well as
7975 any menu and/or tool bar of frame.
7977 `external-border-size' is a cons of the horizontal and vertical width of
7978 FRAME's external borders as supplied by the window manager.
7980 `title-bar-size' is a cons of the width and height of the title bar of
7981 FRAME as supplied by the window manager. If both of them are zero,
7982 FRAME has no title bar. If only the width is zero, Emacs was not
7983 able to retrieve the width information.
7985 `menu-bar-external', if non-nil, means the menu bar is external (never
7986 included in the inner edges of FRAME).
7988 `menu-bar-size' is a cons of the width and height of the menu bar of
7989 FRAME.
7991 `tool-bar-external', if non-nil, means the tool bar is external (never
7992 included in the inner edges of FRAME).
7994 `tool-bar-position' tells on which side the tool bar on FRAME is and can
7995 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
7996 has no tool bar.
7998 `tool-bar-size' is a cons of the width and height of the tool bar of
7999 FRAME.
8001 `internal-border-width' is the width of the internal border of
8002 FRAME. */)
8003 (Lisp_Object frame)
8005 struct frame *f = decode_live_frame (frame);
8007 MENUBARINFO menu_bar;
8008 WINDOWINFO window;
8009 int left, top, right, bottom;
8010 unsigned int external_border_width, external_border_height;
8011 int title_bar_width = 0, title_bar_height = 0;
8012 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8013 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8014 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8015 bool fullboth = EQ (get_frame_param (f, Qfullscreen), Qfullboth);
8017 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8018 return Qnil;
8020 block_input ();
8021 /* Outer rectangle and borders. */
8022 window.cbSize = sizeof (window);
8023 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8024 external_border_width = window.cxWindowBorders;
8025 external_border_height = window.cyWindowBorders;
8026 /* Title bar. */
8027 if (get_title_bar_info_fn)
8029 TITLEBAR_INFO title_bar;
8031 title_bar.cbSize = sizeof (title_bar);
8032 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8033 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8034 for (int i = 0; i < 6; i++)
8035 title_bar.rgstate[i] = 0;
8036 if (get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar)
8037 && !(title_bar.rgstate[0] & 0x00008001))
8039 title_bar_width
8040 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8041 title_bar_height
8042 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8045 else if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8046 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8047 /* Menu bar. */
8048 menu_bar.cbSize = sizeof (menu_bar);
8049 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8050 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8051 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8052 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8053 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8054 unblock_input ();
8056 left = window.rcWindow.left;
8057 top = window.rcWindow.top;
8058 right = window.rcWindow.right;
8059 bottom = window.rcWindow.bottom;
8061 /* Menu bar. */
8062 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8063 /* Fix menu bar height reported by GetMenuBarInfo. */
8064 if (menu_bar_height > single_menu_bar_height)
8065 /* A wrapped menu bar. */
8066 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8067 else if (menu_bar_height > 0)
8068 /* A single line menu bar. */
8069 menu_bar_height = single_menu_bar_height;
8071 return listn (CONSTYPE_HEAP, 10,
8072 Fcons (Qouter_position,
8073 Fcons (make_number (left), make_number (top))),
8074 Fcons (Qouter_size,
8075 Fcons (make_number (right - left),
8076 make_number (bottom - top))),
8077 Fcons (Qexternal_border_size,
8078 Fcons (make_number (external_border_width),
8079 make_number (external_border_height))),
8080 Fcons (Qtitle_bar_size,
8081 Fcons (make_number (title_bar_width),
8082 make_number (title_bar_height))),
8083 Fcons (Qmenu_bar_external, Qt),
8084 Fcons (Qmenu_bar_size,
8085 Fcons (make_number
8086 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8087 make_number (menu_bar_height))),
8088 Fcons (Qtool_bar_external, Qnil),
8089 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8090 Fcons (Qtool_bar_size,
8091 Fcons (make_number
8092 (tool_bar_height
8093 ? right - left - 2 * internal_border_width
8094 : 0),
8095 make_number (tool_bar_height))),
8096 Fcons (Qinternal_border_width,
8097 make_number (internal_border_width)));
8100 DEFUN ("w32-frame-edges", Fw32_frame_edges, Sw32_frame_edges, 0, 2, 0,
8101 doc: /* Return edge coordinates of FRAME.
8102 FRAME must be a live frame and defaults to the selected one. The return
8103 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8104 in pixels relative to the origin - the position (0, 0) - of FRAME's
8105 display.
8107 If optional argument TYPE is the symbol `outer-edges', return the outer
8108 edges of FRAME. The outer edges comprise the decorations of the window
8109 manager (like the title bar or external borders) as well as any external
8110 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8111 `native-edges' or nil, return the native edges of FRAME. The native
8112 edges exclude the decorations of the window manager and any external
8113 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8114 the inner edges of FRAME. These edges exclude title bar, any borders,
8115 menu bar or tool bar of FRAME. */)
8116 (Lisp_Object frame, Lisp_Object type)
8118 struct frame *f = decode_live_frame (frame);
8120 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8121 return Qnil;
8123 if (EQ (type, Qouter_edges))
8125 RECT rectangle;
8127 block_input ();
8128 /* Outer frame rectangle, including outer borders and title bar. */
8129 GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8130 unblock_input ();
8132 return list4 (make_number (rectangle.left),
8133 make_number (rectangle.top),
8134 make_number (rectangle.right),
8135 make_number (rectangle.bottom));
8137 else
8139 RECT rectangle;
8140 POINT pt;
8141 int left, top, right, bottom;
8143 block_input ();
8144 /* Inner frame rectangle, excluding borders and title bar. */
8145 GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
8146 /* Get top-left corner of native rectangle in screen
8147 coordinates. */
8148 pt.x = 0;
8149 pt.y = 0;
8150 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
8151 unblock_input ();
8153 left = pt.x;
8154 top = pt.y;
8155 right = left + rectangle.right;
8156 bottom = top + rectangle.bottom;
8158 if (EQ (type, Qinner_edges))
8160 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8162 return list4 (make_number (left + internal_border_width),
8163 make_number (top
8164 + FRAME_TOOL_BAR_HEIGHT (f)
8165 + internal_border_width),
8166 make_number (right - internal_border_width),
8167 make_number (bottom - internal_border_width));
8169 else
8170 return list4 (make_number (left), make_number (top),
8171 make_number (right), make_number (bottom));
8175 DEFUN ("w32-mouse-absolute-pixel-position", Fw32_mouse_absolute_pixel_position,
8176 Sw32_mouse_absolute_pixel_position, 0, 0, 0,
8177 doc: /* Return absolute position of mouse cursor in pixels.
8178 The position is returned as a cons cell (X . Y) of the coordinates of
8179 the mouse cursor position in pixels relative to a position (0, 0) of the
8180 selected frame's display. */)
8181 (void)
8183 POINT pt;
8185 block_input ();
8186 GetCursorPos (&pt);
8187 unblock_input ();
8189 return Fcons (make_number (pt.x), make_number (pt.y));
8192 DEFUN ("w32-set-mouse-absolute-pixel-position", Fw32_set_mouse_absolute_pixel_position,
8193 Sw32_set_mouse_absolute_pixel_position, 2, 2, 0,
8194 doc: /* Move mouse pointer to absolute pixel position (X, Y).
8195 The coordinates X and Y are interpreted in pixels relative to a position
8196 (0, 0) of the selected frame's display. */)
8197 (Lisp_Object x, Lisp_Object y)
8199 CHECK_TYPE_RANGED_INTEGER (int, x);
8200 CHECK_TYPE_RANGED_INTEGER (int, y);
8202 block_input ();
8203 SetCursorPos (XINT (x), XINT (y));
8204 unblock_input ();
8206 return Qnil;
8209 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
8210 doc: /* Get power status information from Windows system.
8212 The following %-sequences are provided:
8213 %L AC line status (verbose)
8214 %B Battery status (verbose)
8215 %b Battery status, empty means high, `-' means low,
8216 `!' means critical, and `+' means charging
8217 %p Battery load percentage
8218 %s Remaining time (to charge or discharge) in seconds
8219 %m Remaining time (to charge or discharge) in minutes
8220 %h Remaining time (to charge or discharge) in hours
8221 %t Remaining time (to charge or discharge) in the form `h:min' */)
8222 (void)
8224 Lisp_Object status = Qnil;
8226 SYSTEM_POWER_STATUS system_status;
8227 if (GetSystemPowerStatus (&system_status))
8229 Lisp_Object line_status, battery_status, battery_status_symbol;
8230 Lisp_Object load_percentage, seconds, minutes, hours, remain;
8232 long seconds_left = (long) system_status.BatteryLifeTime;
8234 if (system_status.ACLineStatus == 0)
8235 line_status = build_string ("off-line");
8236 else if (system_status.ACLineStatus == 1)
8237 line_status = build_string ("on-line");
8238 else
8239 line_status = build_string ("N/A");
8241 if (system_status.BatteryFlag & 128)
8243 battery_status = build_string ("N/A");
8244 battery_status_symbol = empty_unibyte_string;
8246 else if (system_status.BatteryFlag & 8)
8248 battery_status = build_string ("charging");
8249 battery_status_symbol = build_string ("+");
8250 if (system_status.BatteryFullLifeTime != -1L)
8251 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
8253 else if (system_status.BatteryFlag & 4)
8255 battery_status = build_string ("critical");
8256 battery_status_symbol = build_string ("!");
8258 else if (system_status.BatteryFlag & 2)
8260 battery_status = build_string ("low");
8261 battery_status_symbol = build_string ("-");
8263 else if (system_status.BatteryFlag & 1)
8265 battery_status = build_string ("high");
8266 battery_status_symbol = empty_unibyte_string;
8268 else
8270 battery_status = build_string ("medium");
8271 battery_status_symbol = empty_unibyte_string;
8274 if (system_status.BatteryLifePercent > 100)
8275 load_percentage = build_string ("N/A");
8276 else
8278 char buffer[16];
8279 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
8280 load_percentage = build_string (buffer);
8283 if (seconds_left < 0)
8284 seconds = minutes = hours = remain = build_string ("N/A");
8285 else
8287 long m;
8288 float h;
8289 char buffer[16];
8290 snprintf (buffer, 16, "%ld", seconds_left);
8291 seconds = build_string (buffer);
8293 m = seconds_left / 60;
8294 snprintf (buffer, 16, "%ld", m);
8295 minutes = build_string (buffer);
8297 h = seconds_left / 3600.0;
8298 snprintf (buffer, 16, "%3.1f", h);
8299 hours = build_string (buffer);
8301 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
8302 remain = build_string (buffer);
8305 status = listn (CONSTYPE_HEAP, 8,
8306 Fcons (make_number ('L'), line_status),
8307 Fcons (make_number ('B'), battery_status),
8308 Fcons (make_number ('b'), battery_status_symbol),
8309 Fcons (make_number ('p'), load_percentage),
8310 Fcons (make_number ('s'), seconds),
8311 Fcons (make_number ('m'), minutes),
8312 Fcons (make_number ('h'), hours),
8313 Fcons (make_number ('t'), remain));
8315 return status;
8319 #ifdef WINDOWSNT
8320 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
8321 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8322 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
8323 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8325 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8326 doc: /* Return storage information about the file system FILENAME is on.
8327 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8328 storage of the file system, FREE is the free storage, and AVAIL is the
8329 storage available to a non-superuser. All 3 numbers are in bytes.
8330 If the underlying system call fails, value is nil. */)
8331 (Lisp_Object filename)
8333 Lisp_Object encoded, value;
8335 CHECK_STRING (filename);
8336 filename = Fexpand_file_name (filename, Qnil);
8337 encoded = ENCODE_FILE (filename);
8339 value = Qnil;
8341 /* Determining the required information on Windows turns out, sadly,
8342 to be more involved than one would hope. The original Windows API
8343 call for this will return bogus information on some systems, but we
8344 must dynamically probe for the replacement api, since that was
8345 added rather late on. */
8347 HMODULE hKernel = GetModuleHandle ("kernel32");
8348 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
8349 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
8350 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
8351 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
8352 bool have_pfn_GetDiskFreeSpaceEx =
8353 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
8354 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
8356 /* On Windows, we may need to specify the root directory of the
8357 volume holding FILENAME. */
8358 char rootname[MAX_UTF8_PATH];
8359 wchar_t rootname_w[MAX_PATH];
8360 char rootname_a[MAX_PATH];
8361 char *name = SDATA (encoded);
8362 BOOL result;
8364 /* find the root name of the volume if given */
8365 if (isalpha (name[0]) && name[1] == ':')
8367 rootname[0] = name[0];
8368 rootname[1] = name[1];
8369 rootname[2] = '\\';
8370 rootname[3] = 0;
8372 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8374 char *str = rootname;
8375 int slashes = 4;
8378 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8379 break;
8380 *str++ = *name++;
8382 while ( *name );
8384 *str++ = '\\';
8385 *str = 0;
8388 if (w32_unicode_filenames)
8389 filename_to_utf16 (rootname, rootname_w);
8390 else
8391 filename_to_ansi (rootname, rootname_a);
8393 if (have_pfn_GetDiskFreeSpaceEx)
8395 /* Unsigned large integers cannot be cast to double, so
8396 use signed ones instead. */
8397 LARGE_INTEGER availbytes;
8398 LARGE_INTEGER freebytes;
8399 LARGE_INTEGER totalbytes;
8401 if (w32_unicode_filenames)
8402 result = pfn_GetDiskFreeSpaceExW (rootname_w,
8403 (ULARGE_INTEGER *)&availbytes,
8404 (ULARGE_INTEGER *)&totalbytes,
8405 (ULARGE_INTEGER *)&freebytes);
8406 else
8407 result = pfn_GetDiskFreeSpaceExA (rootname_a,
8408 (ULARGE_INTEGER *)&availbytes,
8409 (ULARGE_INTEGER *)&totalbytes,
8410 (ULARGE_INTEGER *)&freebytes);
8411 if (result)
8412 value = list3 (make_float ((double) totalbytes.QuadPart),
8413 make_float ((double) freebytes.QuadPart),
8414 make_float ((double) availbytes.QuadPart));
8416 else
8418 DWORD sectors_per_cluster;
8419 DWORD bytes_per_sector;
8420 DWORD free_clusters;
8421 DWORD total_clusters;
8423 if (w32_unicode_filenames)
8424 result = GetDiskFreeSpaceW (rootname_w,
8425 &sectors_per_cluster,
8426 &bytes_per_sector,
8427 &free_clusters,
8428 &total_clusters);
8429 else
8430 result = GetDiskFreeSpaceA (rootname_a,
8431 &sectors_per_cluster,
8432 &bytes_per_sector,
8433 &free_clusters,
8434 &total_clusters);
8435 if (result)
8436 value = list3 (make_float ((double) total_clusters
8437 * sectors_per_cluster * bytes_per_sector),
8438 make_float ((double) free_clusters
8439 * sectors_per_cluster * bytes_per_sector),
8440 make_float ((double) free_clusters
8441 * sectors_per_cluster * bytes_per_sector));
8445 return value;
8447 #endif /* WINDOWSNT */
8450 #ifdef WINDOWSNT
8451 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8452 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8453 (void)
8455 static char pname_buf[256];
8456 int err;
8457 HANDLE hPrn;
8458 PRINTER_INFO_2W *ppi2w = NULL;
8459 PRINTER_INFO_2A *ppi2a = NULL;
8460 DWORD dwNeeded = 0, dwReturned = 0;
8461 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
8462 char port_name[MAX_UTF8_PATH];
8464 /* Retrieve the default string from Win.ini (the registry).
8465 * String will be in form "printername,drivername,portname".
8466 * This is the most portable way to get the default printer. */
8467 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8468 return Qnil;
8469 /* printername precedes first "," character */
8470 strtok (pname_buf, ",");
8471 /* We want to know more than the printer name */
8472 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8473 return Qnil;
8474 /* GetPrinterW is not supported by unicows.dll. */
8475 if (w32_unicode_filenames && os_subtype != OS_9X)
8476 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
8477 else
8478 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
8479 if (dwNeeded == 0)
8481 ClosePrinter (hPrn);
8482 return Qnil;
8484 /* Call GetPrinter again with big enough memory block. */
8485 if (w32_unicode_filenames && os_subtype != OS_9X)
8487 /* Allocate memory for the PRINTER_INFO_2 struct. */
8488 ppi2w = xmalloc (dwNeeded);
8489 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
8490 ClosePrinter (hPrn);
8491 if (!err)
8493 xfree (ppi2w);
8494 return Qnil;
8497 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
8498 && ppi2w->pServerName)
8500 filename_from_utf16 (ppi2w->pServerName, server_name);
8501 filename_from_utf16 (ppi2w->pShareName, share_name);
8503 else
8505 server_name[0] = '\0';
8506 filename_from_utf16 (ppi2w->pPortName, port_name);
8509 else
8511 ppi2a = xmalloc (dwNeeded);
8512 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
8513 ClosePrinter (hPrn);
8514 if (!err)
8516 xfree (ppi2a);
8517 return Qnil;
8520 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
8521 && ppi2a->pServerName)
8523 filename_from_ansi (ppi2a->pServerName, server_name);
8524 filename_from_ansi (ppi2a->pShareName, share_name);
8526 else
8528 server_name[0] = '\0';
8529 filename_from_ansi (ppi2a->pPortName, port_name);
8533 if (server_name[0])
8535 /* a remote printer */
8536 if (server_name[0] == '\\')
8537 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
8538 share_name);
8539 else
8540 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
8541 share_name);
8542 pname_buf[sizeof (pname_buf) - 1] = '\0';
8544 else
8546 /* a local printer */
8547 strncpy (pname_buf, port_name, sizeof (pname_buf));
8548 pname_buf[sizeof (pname_buf) - 1] = '\0';
8549 /* `pPortName' can include several ports, delimited by ','.
8550 * we only use the first one. */
8551 strtok (pname_buf, ",");
8554 return DECODE_FILE (build_unibyte_string (pname_buf));
8556 #endif /* WINDOWSNT */
8559 /* Equivalent of strerror for W32 error codes. */
8560 char *
8561 w32_strerror (int error_no)
8563 static char buf[500];
8564 DWORD ret;
8566 if (error_no == 0)
8567 error_no = GetLastError ();
8569 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
8570 FORMAT_MESSAGE_IGNORE_INSERTS,
8571 NULL,
8572 error_no,
8573 0, /* choose most suitable language */
8574 buf, sizeof (buf), NULL);
8576 while (ret > 0 && (buf[ret - 1] == '\n' ||
8577 buf[ret - 1] == '\r' ))
8578 --ret;
8579 buf[ret] = '\0';
8580 if (!ret)
8581 sprintf (buf, "w32 error %u", error_no);
8583 return buf;
8586 /* For convenience when debugging. (You cannot call GetLastError
8587 directly from GDB: it will crash, because it uses the __stdcall
8588 calling convention, not the _cdecl convention assumed by GDB.) */
8589 DWORD
8590 w32_last_error (void)
8592 return GetLastError ();
8595 /* Cache information describing the NT system for later use. */
8596 void
8597 cache_system_info (void)
8599 union
8601 struct info
8603 char major;
8604 char minor;
8605 short platform;
8606 } info;
8607 DWORD data;
8608 } version;
8610 /* Cache the module handle of Emacs itself. */
8611 hinst = GetModuleHandle (NULL);
8613 /* Cache the version of the operating system. */
8614 version.data = GetVersion ();
8615 w32_major_version = version.info.major;
8616 w32_minor_version = version.info.minor;
8618 if (version.info.platform & 0x8000)
8619 os_subtype = OS_9X;
8620 else
8621 os_subtype = OS_NT;
8623 /* Cache page size, allocation unit, processor type, etc. */
8624 GetSystemInfo (&sysinfo_cache);
8625 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
8627 /* Cache os info. */
8628 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
8629 GetVersionEx (&osinfo_cache);
8631 w32_build_number = osinfo_cache.dwBuildNumber;
8632 if (os_subtype == OS_9X)
8633 w32_build_number &= 0xffff;
8635 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
8638 #ifdef EMACSDEBUG
8639 void
8640 _DebPrint (const char *fmt, ...)
8642 char buf[1024];
8643 va_list args;
8645 va_start (args, fmt);
8646 vsprintf (buf, fmt, args);
8647 va_end (args);
8648 #if CYGWIN
8649 fprintf (stderr, "%s", buf);
8650 #endif
8651 OutputDebugString (buf);
8653 #endif
8656 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
8658 int cur_state = (GetKeyState (vk_code) & 1);
8660 if (NILP (new_state)
8661 || (NUMBERP (new_state)
8662 && ((XUINT (new_state)) & 1) != cur_state))
8664 #ifdef WINDOWSNT
8665 faked_key = vk_code;
8666 #endif /* WINDOWSNT */
8668 keybd_event ((BYTE) vk_code,
8669 (BYTE) MapVirtualKey (vk_code, 0),
8670 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8671 keybd_event ((BYTE) vk_code,
8672 (BYTE) MapVirtualKey (vk_code, 0),
8673 KEYEVENTF_EXTENDEDKEY | 0, 0);
8674 keybd_event ((BYTE) vk_code,
8675 (BYTE) MapVirtualKey (vk_code, 0),
8676 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8677 cur_state = !cur_state;
8680 return cur_state;
8683 /* Translate console modifiers to emacs modifiers.
8684 German keyboard support (Kai Morgan Zeise 2/18/95). */
8686 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
8688 int retval = 0;
8690 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
8691 pressed, first remove those modifiers. */
8692 if (!NILP (Vw32_recognize_altgr)
8693 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8694 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8695 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
8697 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
8698 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
8700 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8702 retval |= ctrl_modifier;
8703 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8704 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8705 retval |= meta_modifier;
8708 if (mods & LEFT_WIN_PRESSED)
8709 retval |= w32_key_to_modifier (VK_LWIN);
8710 if (mods & RIGHT_WIN_PRESSED)
8711 retval |= w32_key_to_modifier (VK_RWIN);
8712 if (mods & APPS_PRESSED)
8713 retval |= w32_key_to_modifier (VK_APPS);
8714 if (mods & SCROLLLOCK_ON)
8715 retval |= w32_key_to_modifier (VK_SCROLL);
8717 /* Just in case someone wanted the original behavior, make it
8718 optional by setting w32-capslock-is-shiftlock to t. */
8719 if (NILP (Vw32_capslock_is_shiftlock)
8720 /* Keys that should _not_ be affected by CapsLock. */
8721 && ( (key == VK_BACK)
8722 || (key == VK_TAB)
8723 || (key == VK_CLEAR)
8724 || (key == VK_RETURN)
8725 || (key == VK_ESCAPE)
8726 || ((key >= VK_SPACE) && (key <= VK_HELP))
8727 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
8728 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
8731 /* Only consider shift state. */
8732 if ((mods & SHIFT_PRESSED) != 0)
8733 retval |= shift_modifier;
8735 else
8737 /* Ignore CapsLock state if not enabled. */
8738 if (NILP (Vw32_enable_caps_lock))
8739 mods &= ~CAPSLOCK_ON;
8740 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
8741 retval |= shift_modifier;
8744 return retval;
8747 /* The return code indicates key code size. cpID is the codepage to
8748 use for translation to Unicode; -1 means use the current console
8749 input codepage. */
8751 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
8753 unsigned int key_code = event->wVirtualKeyCode;
8754 unsigned int mods = event->dwControlKeyState;
8755 BYTE keystate[256];
8756 static BYTE ansi_code[4];
8757 static int isdead = 0;
8759 if (isdead == 2)
8761 event->uChar.AsciiChar = ansi_code[2];
8762 isdead = 0;
8763 return 1;
8765 if (event->uChar.AsciiChar != 0)
8766 return 1;
8768 memset (keystate, 0, sizeof (keystate));
8769 keystate[key_code] = 0x80;
8770 if (mods & SHIFT_PRESSED)
8771 keystate[VK_SHIFT] = 0x80;
8772 if (mods & CAPSLOCK_ON)
8773 keystate[VK_CAPITAL] = 1;
8774 /* If we recognize right-alt and left-ctrl as AltGr, set the key
8775 states accordingly before invoking ToAscii. */
8776 if (!NILP (Vw32_recognize_altgr)
8777 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
8779 keystate[VK_CONTROL] = 0x80;
8780 keystate[VK_LCONTROL] = 0x80;
8781 keystate[VK_MENU] = 0x80;
8782 keystate[VK_RMENU] = 0x80;
8785 #if 0
8786 /* Because of an OS bug, ToAscii corrupts the stack when called to
8787 convert a dead key in console mode on NT4. Unfortunately, trying
8788 to check for dead keys using MapVirtualKey doesn't work either -
8789 these functions apparently use internal information about keyboard
8790 layout which doesn't get properly updated in console programs when
8791 changing layout (though apparently it gets partly updated,
8792 otherwise ToAscii wouldn't crash). */
8793 if (is_dead_key (event->wVirtualKeyCode))
8794 return 0;
8795 #endif
8797 /* On NT, call ToUnicode instead and then convert to the current
8798 console input codepage. */
8799 if (os_subtype == OS_NT)
8801 WCHAR buf[128];
8803 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
8804 keystate, buf, 128, 0);
8805 if (isdead > 0)
8807 /* When we are called from the GUI message processing code,
8808 we are passed the current keyboard codepage, a positive
8809 number, to use below. */
8810 if (cpId == -1)
8811 cpId = GetConsoleCP ();
8813 event->uChar.UnicodeChar = buf[isdead - 1];
8814 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8815 ansi_code, 4, NULL, NULL);
8817 else
8818 isdead = 0;
8820 else
8822 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8823 keystate, (LPWORD) ansi_code, 0);
8826 if (isdead == 0)
8827 return 0;
8828 event->uChar.AsciiChar = ansi_code[0];
8829 return isdead;
8833 void
8834 w32_sys_ring_bell (struct frame *f)
8836 if (sound_type == 0xFFFFFFFF)
8838 Beep (666, 100);
8840 else if (sound_type == MB_EMACS_SILENT)
8842 /* Do nothing. */
8844 else
8845 MessageBeep (sound_type);
8848 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
8849 0, 0, 0,
8850 doc: /* Return non-nil when a menu-bar menu is being used.
8851 Internal use only. */)
8852 (void)
8854 return menubar_in_use ? Qt : Qnil;
8858 /***********************************************************************
8859 Initialization
8860 ***********************************************************************/
8862 /* Keep this list in the same order as frame_parms in frame.c.
8863 Use 0 for unsupported frame parameters. */
8865 frame_parm_handler w32_frame_parm_handlers[] =
8867 x_set_autoraise,
8868 x_set_autolower,
8869 x_set_background_color,
8870 x_set_border_color,
8871 x_set_border_width,
8872 x_set_cursor_color,
8873 x_set_cursor_type,
8874 x_set_font,
8875 x_set_foreground_color,
8876 x_set_icon_name,
8877 x_set_icon_type,
8878 x_set_internal_border_width,
8879 x_set_right_divider_width,
8880 x_set_bottom_divider_width,
8881 x_set_menu_bar_lines,
8882 x_set_mouse_color,
8883 x_explicitly_set_name,
8884 x_set_scroll_bar_width,
8885 x_set_scroll_bar_height,
8886 x_set_title,
8887 x_set_unsplittable,
8888 x_set_vertical_scroll_bars,
8889 x_set_horizontal_scroll_bars,
8890 x_set_visibility,
8891 x_set_tool_bar_lines,
8892 0, /* x_set_scroll_bar_foreground, */
8893 0, /* x_set_scroll_bar_background, */
8894 x_set_screen_gamma,
8895 x_set_line_spacing,
8896 x_set_left_fringe,
8897 x_set_right_fringe,
8898 0, /* x_set_wait_for_wm, */
8899 x_set_fullscreen,
8900 x_set_font_backend,
8901 x_set_alpha,
8902 0, /* x_set_sticky */
8903 0, /* x_set_tool_bar_position */
8906 void
8907 syms_of_w32fns (void)
8909 globals_of_w32fns ();
8910 track_mouse_window = NULL;
8912 w32_visible_system_caret_hwnd = NULL;
8914 DEFSYM (Qundefined_color, "undefined-color");
8915 DEFSYM (Qcancel_timer, "cancel-timer");
8916 DEFSYM (Qhyper, "hyper");
8917 DEFSYM (Qsuper, "super");
8918 DEFSYM (Qmeta, "meta");
8919 DEFSYM (Qalt, "alt");
8920 DEFSYM (Qctrl, "ctrl");
8921 DEFSYM (Qcontrol, "control");
8922 DEFSYM (Qshift, "shift");
8923 DEFSYM (Qfont_param, "font-parameter");
8924 DEFSYM (Qgeometry, "geometry");
8925 DEFSYM (Qworkarea, "workarea");
8926 DEFSYM (Qmm_size, "mm-size");
8927 DEFSYM (Qframes, "frames");
8928 DEFSYM (Qtip_frame, "tip-frame");
8929 DEFSYM (Qunicode_sip, "unicode-sip");
8931 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
8932 DEFSYM (Qgnutls_dll, "gnutls");
8933 DEFSYM (Qlibxml2_dll, "libxml2");
8934 DEFSYM (Qserif, "serif");
8935 DEFSYM (Qzlib_dll, "zlib");
8937 Fput (Qundefined_color, Qerror_conditions,
8938 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8939 Fput (Qundefined_color, Qerror_message,
8940 build_pure_c_string ("Undefined color"));
8942 staticpro (&w32_grabbed_keys);
8943 w32_grabbed_keys = Qnil;
8945 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8946 doc: /* An array of color name mappings for Windows. */);
8947 Vw32_color_map = Qnil;
8949 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8950 doc: /* Non-nil if Alt key presses are passed on to Windows.
8951 When non-nil, for example, Alt pressed and released and then space will
8952 open the System menu. When nil, Emacs processes the Alt key events, and
8953 then silently swallows them. */);
8954 Vw32_pass_alt_to_system = Qnil;
8956 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8957 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8958 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8959 Vw32_alt_is_meta = Qt;
8961 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8962 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8963 w32_quit_key = 0;
8965 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8966 Vw32_pass_lwindow_to_system,
8967 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8969 When non-nil, the Start menu is opened by tapping the key.
8970 If you set this to nil, the left \"Windows\" key is processed by Emacs
8971 according to the value of `w32-lwindow-modifier', which see.
8973 Note that some combinations of the left \"Windows\" key with other keys are
8974 caught by Windows at low level, and so binding them in Emacs will have no
8975 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8976 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8977 the doc string of `w32-phantom-key-code'. */);
8978 Vw32_pass_lwindow_to_system = Qt;
8980 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8981 Vw32_pass_rwindow_to_system,
8982 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8984 When non-nil, the Start menu is opened by tapping the key.
8985 If you set this to nil, the right \"Windows\" key is processed by Emacs
8986 according to the value of `w32-rwindow-modifier', which see.
8988 Note that some combinations of the right \"Windows\" key with other keys are
8989 caught by Windows at low level, and so binding them in Emacs will have no
8990 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8991 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8992 the doc string of `w32-phantom-key-code'. */);
8993 Vw32_pass_rwindow_to_system = Qt;
8995 DEFVAR_LISP ("w32-phantom-key-code",
8996 Vw32_phantom_key_code,
8997 doc: /* Virtual key code used to generate \"phantom\" key presses.
8998 Value is a number between 0 and 255.
9000 Phantom key presses are generated in order to stop the system from
9001 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
9002 `w32-pass-rwindow-to-system' is nil. */);
9003 /* Although 255 is technically not a valid key code, it works and
9004 means that this hack won't interfere with any real key code. */
9005 XSETINT (Vw32_phantom_key_code, 255);
9007 DEFVAR_LISP ("w32-enable-num-lock",
9008 Vw32_enable_num_lock,
9009 doc: /* If non-nil, the Num Lock key acts normally.
9010 Set to nil to handle Num Lock as the `kp-numlock' key. */);
9011 Vw32_enable_num_lock = Qt;
9013 DEFVAR_LISP ("w32-enable-caps-lock",
9014 Vw32_enable_caps_lock,
9015 doc: /* If non-nil, the Caps Lock key acts normally.
9016 Set to nil to handle Caps Lock as the `capslock' key. */);
9017 Vw32_enable_caps_lock = Qt;
9019 DEFVAR_LISP ("w32-scroll-lock-modifier",
9020 Vw32_scroll_lock_modifier,
9021 doc: /* Modifier to use for the Scroll Lock ON state.
9022 The value can be hyper, super, meta, alt, control or shift for the
9023 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
9024 Any other value will cause the Scroll Lock key to be ignored. */);
9025 Vw32_scroll_lock_modifier = Qnil;
9027 DEFVAR_LISP ("w32-lwindow-modifier",
9028 Vw32_lwindow_modifier,
9029 doc: /* Modifier to use for the left \"Windows\" key.
9030 The value can be hyper, super, meta, alt, control or shift for the
9031 respective modifier, or nil to appear as the `lwindow' key.
9032 Any other value will cause the key to be ignored. */);
9033 Vw32_lwindow_modifier = Qnil;
9035 DEFVAR_LISP ("w32-rwindow-modifier",
9036 Vw32_rwindow_modifier,
9037 doc: /* Modifier to use for the right \"Windows\" key.
9038 The value can be hyper, super, meta, alt, control or shift for the
9039 respective modifier, or nil to appear as the `rwindow' key.
9040 Any other value will cause the key to be ignored. */);
9041 Vw32_rwindow_modifier = Qnil;
9043 DEFVAR_LISP ("w32-apps-modifier",
9044 Vw32_apps_modifier,
9045 doc: /* Modifier to use for the \"Apps\" key.
9046 The value can be hyper, super, meta, alt, control or shift for the
9047 respective modifier, or nil to appear as the `apps' key.
9048 Any other value will cause the key to be ignored. */);
9049 Vw32_apps_modifier = Qnil;
9051 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
9052 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
9053 w32_enable_synthesized_fonts = 0;
9055 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
9056 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
9057 Vw32_enable_palette = Qt;
9059 DEFVAR_INT ("w32-mouse-button-tolerance",
9060 w32_mouse_button_tolerance,
9061 doc: /* Analogue of double click interval for faking middle mouse events.
9062 The value is the minimum time in milliseconds that must elapse between
9063 left and right button down events before they are considered distinct events.
9064 If both mouse buttons are depressed within this interval, a middle mouse
9065 button down event is generated instead. */);
9066 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
9068 DEFVAR_INT ("w32-mouse-move-interval",
9069 w32_mouse_move_interval,
9070 doc: /* Minimum interval between mouse move events.
9071 The value is the minimum time in milliseconds that must elapse between
9072 successive mouse move (or scroll bar drag) events before they are
9073 reported as lisp events. */);
9074 w32_mouse_move_interval = 0;
9076 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
9077 w32_pass_extra_mouse_buttons_to_system,
9078 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
9079 Recent versions of Windows support mice with up to five buttons.
9080 Since most applications don't support these extra buttons, most mouse
9081 drivers will allow you to map them to functions at the system level.
9082 If this variable is non-nil, Emacs will pass them on, allowing the
9083 system to handle them. */);
9084 w32_pass_extra_mouse_buttons_to_system = 0;
9086 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
9087 w32_pass_multimedia_buttons_to_system,
9088 doc: /* If non-nil, media buttons are passed to Windows.
9089 Some modern keyboards contain buttons for controlling media players, web
9090 browsers and other applications. Generally these buttons are handled on a
9091 system wide basis, but by setting this to nil they are made available
9092 to Emacs for binding. Depending on your keyboard, additional keys that
9093 may be available are:
9095 browser-back, browser-forward, browser-refresh, browser-stop,
9096 browser-search, browser-favorites, browser-home,
9097 mail, mail-reply, mail-forward, mail-send,
9098 app-1, app-2,
9099 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
9100 spell-check, correction-list, toggle-dictate-command,
9101 media-next, media-previous, media-stop, media-play-pause, media-select,
9102 media-play, media-pause, media-record, media-fast-forward, media-rewind,
9103 media-channel-up, media-channel-down,
9104 volume-mute, volume-up, volume-down,
9105 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
9106 bass-down, bass-boost, bass-up, treble-down, treble-up */);
9107 w32_pass_multimedia_buttons_to_system = 1;
9109 #if 0 /* TODO: Mouse cursor customization. */
9110 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
9111 doc: /* The shape of the pointer when over text.
9112 Changing the value does not affect existing frames
9113 unless you set the mouse color. */);
9114 Vx_pointer_shape = Qnil;
9116 Vx_nontext_pointer_shape = Qnil;
9118 Vx_mode_pointer_shape = Qnil;
9120 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
9121 doc: /* The shape of the pointer when Emacs is busy.
9122 This variable takes effect when you create a new frame
9123 or when you set the mouse color. */);
9124 Vx_hourglass_pointer_shape = Qnil;
9126 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
9127 Vx_sensitive_text_pointer_shape,
9128 doc: /* The shape of the pointer when over mouse-sensitive text.
9129 This variable takes effect when you create a new frame
9130 or when you set the mouse color. */);
9131 Vx_sensitive_text_pointer_shape = Qnil;
9133 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
9134 Vx_window_horizontal_drag_shape,
9135 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
9136 This variable takes effect when you create a new frame
9137 or when you set the mouse color. */);
9138 Vx_window_horizontal_drag_shape = Qnil;
9140 DEFVAR_LISP ("x-window-vertical-drag-cursor",
9141 Vx_window_vertical_drag_shape,
9142 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
9143 This variable takes effect when you create a new frame
9144 or when you set the mouse color. */);
9145 Vx_window_vertical_drag_shape = Qnil;
9146 #endif
9148 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
9149 doc: /* A string indicating the foreground color of the cursor box. */);
9150 Vx_cursor_fore_pixel = Qnil;
9152 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
9153 doc: /* Maximum size for tooltips.
9154 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
9155 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
9157 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
9158 doc: /* Non-nil if no window manager is in use.
9159 Emacs doesn't try to figure this out; this is always nil
9160 unless you set it to something else. */);
9161 /* We don't have any way to find this out, so set it to nil
9162 and maybe the user would like to set it to t. */
9163 Vx_no_window_manager = Qnil;
9165 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
9166 Vx_pixel_size_width_font_regexp,
9167 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
9169 Since Emacs gets width of a font matching with this regexp from
9170 PIXEL_SIZE field of the name, font finding mechanism gets faster for
9171 such a font. This is especially effective for such large fonts as
9172 Chinese, Japanese, and Korean. */);
9173 Vx_pixel_size_width_font_regexp = Qnil;
9175 DEFVAR_LISP ("w32-bdf-filename-alist",
9176 Vw32_bdf_filename_alist,
9177 doc: /* List of bdf fonts and their corresponding filenames. */);
9178 Vw32_bdf_filename_alist = Qnil;
9180 DEFVAR_BOOL ("w32-strict-fontnames",
9181 w32_strict_fontnames,
9182 doc: /* Non-nil means only use fonts that are exact matches for those requested.
9183 Default is nil, which allows old fontnames that are not XLFD compliant,
9184 and allows third-party CJK display to work by specifying false charset
9185 fields to trick Emacs into translating to Big5, SJIS etc.
9186 Setting this to t will prevent wrong fonts being selected when
9187 fontsets are automatically created. */);
9188 w32_strict_fontnames = 0;
9190 DEFVAR_BOOL ("w32-strict-painting",
9191 w32_strict_painting,
9192 doc: /* Non-nil means use strict rules for repainting frames.
9193 Set this to nil to get the old behavior for repainting; this should
9194 only be necessary if the default setting causes problems. */);
9195 w32_strict_painting = 1;
9197 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
9198 w32_use_fallback_wm_chars_method,
9199 doc: /* Non-nil means use old method of processing character keys.
9200 This is intended only for debugging of the new processing method.
9201 Default is nil.
9203 This variable has effect only on NT family of systems, not on Windows 9X. */);
9204 w32_use_fallback_wm_chars_method = 0;
9206 DEFVAR_BOOL ("w32-disable-new-uniscribe-apis",
9207 w32_disable_new_uniscribe_apis,
9208 doc: /* Non-nil means don't use new Uniscribe APIs.
9209 The new APIs are used to access OTF features supported by fonts.
9210 This is intended only for debugging of the new Uniscribe-related code.
9211 Default is nil.
9213 This variable has effect only on Windows Vista and later. */);
9214 w32_disable_new_uniscribe_apis = 0;
9216 #if 0 /* TODO: Port to W32 */
9217 defsubr (&Sx_change_window_property);
9218 defsubr (&Sx_delete_window_property);
9219 defsubr (&Sx_window_property);
9220 #endif
9221 defsubr (&Sxw_display_color_p);
9222 defsubr (&Sx_display_grayscale_p);
9223 defsubr (&Sxw_color_defined_p);
9224 defsubr (&Sxw_color_values);
9225 defsubr (&Sx_server_max_request_size);
9226 defsubr (&Sx_server_vendor);
9227 defsubr (&Sx_server_version);
9228 defsubr (&Sx_display_pixel_width);
9229 defsubr (&Sx_display_pixel_height);
9230 defsubr (&Sx_display_mm_width);
9231 defsubr (&Sx_display_mm_height);
9232 defsubr (&Sx_display_screens);
9233 defsubr (&Sx_display_planes);
9234 defsubr (&Sx_display_color_cells);
9235 defsubr (&Sx_display_visual_class);
9236 defsubr (&Sx_display_backing_store);
9237 defsubr (&Sx_display_save_under);
9238 defsubr (&Sx_create_frame);
9239 defsubr (&Sx_open_connection);
9240 defsubr (&Sx_close_connection);
9241 defsubr (&Sx_display_list);
9242 defsubr (&Sw32_frame_geometry);
9243 defsubr (&Sw32_frame_edges);
9244 defsubr (&Sw32_mouse_absolute_pixel_position);
9245 defsubr (&Sw32_set_mouse_absolute_pixel_position);
9246 defsubr (&Sx_synchronize);
9248 /* W32 specific functions */
9250 defsubr (&Sw32_define_rgb_color);
9251 defsubr (&Sw32_default_color_map);
9252 defsubr (&Sw32_display_monitor_attributes_list);
9253 defsubr (&Sw32_send_sys_command);
9254 defsubr (&Sw32_shell_execute);
9255 defsubr (&Sw32_register_hot_key);
9256 defsubr (&Sw32_unregister_hot_key);
9257 defsubr (&Sw32_registered_hot_keys);
9258 defsubr (&Sw32_reconstruct_hot_key);
9259 defsubr (&Sw32_toggle_lock_key);
9260 defsubr (&Sw32_window_exists_p);
9261 defsubr (&Sw32_battery_status);
9262 defsubr (&Sw32__menu_bar_in_use);
9264 #ifdef WINDOWSNT
9265 defsubr (&Sfile_system_info);
9266 defsubr (&Sdefault_printer_name);
9267 #endif
9269 defsubr (&Sset_message_beep);
9270 defsubr (&Sx_show_tip);
9271 defsubr (&Sx_hide_tip);
9272 tip_timer = Qnil;
9273 staticpro (&tip_timer);
9274 tip_frame = Qnil;
9275 staticpro (&tip_frame);
9277 last_show_tip_args = Qnil;
9278 staticpro (&last_show_tip_args);
9280 defsubr (&Sx_file_dialog);
9281 #ifdef WINDOWSNT
9282 defsubr (&Ssystem_move_file_to_trash);
9283 #endif
9288 /* Crashing and reporting backtrace. */
9290 #ifndef CYGWIN
9291 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
9292 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
9293 #endif
9294 static DWORD except_code;
9295 static PVOID except_addr;
9297 #ifndef CYGWIN
9299 /* Stack overflow recovery. */
9301 /* Re-establish the guard page at stack limit. This is needed because
9302 when a stack overflow is detected, Windows removes the guard bit
9303 from the guard page, so if we don't re-establish that protection,
9304 the next stack overflow will cause a crash. */
9305 void
9306 w32_reset_stack_overflow_guard (void)
9308 /* MinGW headers don't declare this (should be in malloc.h). */
9309 _CRTIMP int __cdecl _resetstkoflw (void);
9311 /* We ignore the return value. If _resetstkoflw fails, the next
9312 stack overflow will crash the program. */
9313 (void)_resetstkoflw ();
9316 static void
9317 stack_overflow_handler (void)
9319 /* Hard GC error may lead to stack overflow caused by
9320 too nested calls to mark_object. No way to survive. */
9321 if (gc_in_progress)
9322 terminate_due_to_signal (SIGSEGV, 40);
9323 #ifdef _WIN64
9324 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
9325 __builtin_longjmp (return_to_command_loop, 1);
9326 #else
9327 sys_longjmp (return_to_command_loop, 1);
9328 #endif
9331 /* This handler records the exception code and the address where it
9332 was triggered so that this info could be included in the backtrace.
9333 Without that, the backtrace in some cases has no information
9334 whatsoever about the offending code, and looks as if the top-level
9335 exception handler in the MinGW startup code was the one that
9336 crashed. We also recover from stack overflow, by calling our stack
9337 overflow handler that jumps back to top level. */
9338 static LONG CALLBACK
9339 my_exception_handler (EXCEPTION_POINTERS * exception_data)
9341 except_code = exception_data->ExceptionRecord->ExceptionCode;
9342 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
9344 /* If this is a stack overflow exception, attempt to recover. */
9345 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
9346 && exception_data->ExceptionRecord->NumberParameters == 2
9347 /* We can only longjmp to top level from the main thread. */
9348 && GetCurrentThreadId () == dwMainThreadId)
9350 /* Call stack_overflow_handler (). */
9351 #ifdef _WIN64
9352 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
9353 #else
9354 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
9355 #endif
9356 /* Zero this out, so the stale address of the stack overflow
9357 exception we handled is not displayed in some future
9358 unrelated crash. */
9359 except_addr = 0;
9360 return EXCEPTION_CONTINUE_EXECUTION;
9363 if (prev_exception_handler)
9364 return prev_exception_handler (exception_data);
9365 return EXCEPTION_EXECUTE_HANDLER;
9367 #endif
9369 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
9370 PULONG);
9372 #define BACKTRACE_LIMIT_MAX 62
9375 w32_backtrace (void **buffer, int limit)
9377 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
9378 HMODULE hm_kernel32 = NULL;
9380 if (!s_pfn_CaptureStackBackTrace)
9382 hm_kernel32 = LoadLibrary ("Kernel32.dll");
9383 s_pfn_CaptureStackBackTrace =
9384 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
9385 "RtlCaptureStackBackTrace");
9387 if (s_pfn_CaptureStackBackTrace)
9388 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
9389 buffer, NULL);
9390 return 0;
9393 void
9394 emacs_abort (void)
9396 int button;
9397 button = MessageBox (NULL,
9398 "A fatal error has occurred!\n\n"
9399 "Would you like to attach a debugger?\n\n"
9400 "Select:\n"
9401 "YES -- to debug Emacs, or\n"
9402 "NO -- to abort Emacs and produce a backtrace\n"
9403 " (emacs_backtrace.txt in current directory)."
9404 #if __GNUC__
9405 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
9406 "\"continue\" inside GDB before clicking YES.)"
9407 #endif
9408 , "Emacs Abort Dialog",
9409 MB_ICONEXCLAMATION | MB_TASKMODAL
9410 | MB_SETFOREGROUND | MB_YESNO);
9411 switch (button)
9413 case IDYES:
9414 DebugBreak ();
9415 exit (2); /* tell the compiler we will never return */
9416 case IDNO:
9417 default:
9419 void *stack[BACKTRACE_LIMIT_MAX + 1];
9420 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
9422 if (i)
9424 int errfile_fd = -1;
9425 int j;
9426 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
9427 /* The type below should really be 'void *', but
9428 INT_BUFSIZE_BOUND cannot handle that without
9429 triggering compiler warnings (under certain
9430 pedantic warning switches), it wants an
9431 integer type. */
9432 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
9433 #ifdef CYGWIN
9434 int stderr_fd = 2;
9435 #else
9436 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
9437 int stderr_fd = -1;
9439 if (errout && errout != INVALID_HANDLE_VALUE)
9440 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
9441 #endif
9443 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
9444 but not on Windows 7. addr2line doesn't mind a missing
9445 "0x", but will be confused by an extra one. */
9446 if (except_addr)
9447 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
9448 except_code, except_addr);
9449 if (stderr_fd >= 0)
9451 if (except_addr)
9452 write (stderr_fd, buf, strlen (buf));
9453 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
9455 #ifdef CYGWIN
9456 #define _open open
9457 #endif
9458 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
9459 if (errfile_fd >= 0)
9461 lseek (errfile_fd, 0L, SEEK_END);
9462 if (except_addr)
9463 write (errfile_fd, buf, strlen (buf));
9464 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
9467 for (j = 0; j < i; j++)
9469 /* stack[] gives the return addresses, whereas we want
9470 the address of the call, so decrease each address
9471 by approximate size of 1 CALL instruction. */
9472 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
9473 if (stderr_fd >= 0)
9474 write (stderr_fd, buf, strlen (buf));
9475 if (errfile_fd >= 0)
9476 write (errfile_fd, buf, strlen (buf));
9478 if (i == BACKTRACE_LIMIT_MAX)
9480 if (stderr_fd >= 0)
9481 write (stderr_fd, "...\r\n", 5);
9482 if (errfile_fd >= 0)
9483 write (errfile_fd, "...\r\n", 5);
9485 if (errfile_fd >= 0)
9486 close (errfile_fd);
9488 abort ();
9489 break;
9496 /* Initialization. */
9499 globals_of_w32fns is used to initialize those global variables that
9500 must always be initialized on startup even when the global variable
9501 initialized is non zero (see the function main in emacs.c).
9502 globals_of_w32fns is called from syms_of_w32fns when the global
9503 variable initialized is 0 and directly from main when initialized
9504 is non zero.
9506 void
9507 globals_of_w32fns (void)
9509 HMODULE user32_lib = GetModuleHandle ("user32.dll");
9511 TrackMouseEvent not available in all versions of Windows, so must load
9512 it dynamically. Do it once, here, instead of every time it is used.
9514 track_mouse_event_fn = (TrackMouseEvent_Proc)
9515 GetProcAddress (user32_lib, "TrackMouseEvent");
9517 monitor_from_point_fn = (MonitorFromPoint_Proc)
9518 GetProcAddress (user32_lib, "MonitorFromPoint");
9519 get_monitor_info_fn = (GetMonitorInfo_Proc)
9520 GetProcAddress (user32_lib, "GetMonitorInfoA");
9521 monitor_from_window_fn = (MonitorFromWindow_Proc)
9522 GetProcAddress (user32_lib, "MonitorFromWindow");
9523 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
9524 GetProcAddress (user32_lib, "EnumDisplayMonitors");
9525 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
9526 GetProcAddress (user32_lib, "GetTitleBarInfo");
9529 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
9530 get_composition_string_fn = (ImmGetCompositionString_Proc)
9531 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
9532 get_ime_context_fn = (ImmGetContext_Proc)
9533 GetProcAddress (imm32_lib, "ImmGetContext");
9534 release_ime_context_fn = (ImmReleaseContext_Proc)
9535 GetProcAddress (imm32_lib, "ImmReleaseContext");
9536 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
9537 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
9540 except_code = 0;
9541 except_addr = 0;
9542 #ifndef CYGWIN
9543 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
9544 #endif
9546 DEFVAR_INT ("w32-ansi-code-page",
9547 w32_ansi_code_page,
9548 doc: /* The ANSI code page used by the system. */);
9549 w32_ansi_code_page = GetACP ();
9551 if (os_subtype == OS_NT)
9552 w32_unicode_gui = 1;
9553 else
9554 w32_unicode_gui = 0;
9556 after_deadkey = -1;
9558 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
9559 InitCommonControls ();
9561 syms_of_w32uniscribe ();
9563 /* Needed for recovery from C stack overflows in batch mode. */
9564 if (noninteractive)
9565 dwMainThreadId = GetCurrentThreadId ();
9568 #ifdef NTGUI_UNICODE
9570 Lisp_Object
9571 ntgui_encode_system (Lisp_Object str)
9573 Lisp_Object encoded;
9574 to_unicode (str, &encoded);
9575 return encoded;
9578 #endif /* NTGUI_UNICODE */