Do not use switch-to-buffer for working in a temp buffer
[emacs.git] / src / w32fns.c
blob1b628b0b42eb9c137f23d7fd9b93cc5a191ffeef
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2017 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 (at
10 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>
23 /* Override API version to get the latest functionality. */
24 #undef _WIN32_WINNT
25 #define _WIN32_WINNT 0x0600
27 #include <signal.h>
28 #include <stdio.h>
29 #include <limits.h>
30 #include <errno.h>
31 #include <math.h>
32 #include <fcntl.h>
33 #include <unistd.h>
35 #include <c-ctype.h>
37 #include "lisp.h"
38 #include "w32term.h"
39 #include "frame.h"
40 #include "window.h"
41 #include "buffer.h"
42 #include "keyboard.h"
43 #include "blockinput.h"
44 #include "coding.h"
46 #include "w32common.h"
47 #include "w32inevt.h"
49 #ifdef WINDOWSNT
50 #include <mbstring.h>
51 #endif /* WINDOWSNT */
53 #if CYGWIN
54 #include "cygw32.h"
55 #else
56 #include "w32.h"
57 #endif
59 #include <basetyps.h>
60 #include <unknwn.h>
61 #include <commctrl.h>
62 #include <commdlg.h>
63 #include <shellapi.h>
64 #include <shlwapi.h>
65 #include <ctype.h>
66 #include <winspool.h>
67 #include <objbase.h>
69 #include <dlgs.h>
70 #include <imm.h>
71 #include <windowsx.h>
73 #ifndef FOF_NO_CONNECTED_ELEMENTS
74 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
75 #endif
77 extern int w32_console_toggle_lock_key (int, Lisp_Object);
78 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
79 extern void w32_free_menu_strings (HWND);
80 extern const char *map_w32_filename (const char *, const char **);
82 #ifndef IDC_HAND
83 #define IDC_HAND MAKEINTRESOURCE(32649)
84 #endif
86 /* Prefix for system colors. */
87 #define SYSTEM_COLOR_PREFIX "System"
88 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
90 /* State variables for emulating a three button mouse. */
91 #define LMOUSE 1
92 #define MMOUSE 2
93 #define RMOUSE 4
95 static int button_state = 0;
96 static W32Msg saved_mouse_button_msg;
97 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
98 static W32Msg saved_mouse_move_msg;
99 static unsigned mouse_move_timer = 0;
101 /* Window that is tracking the mouse. */
102 static HWND track_mouse_window;
104 /* Multi-monitor API definitions that are not pulled from the headers
105 since we are compiling for NT 4. */
106 #ifndef MONITOR_DEFAULT_TO_NEAREST
107 #define MONITOR_DEFAULT_TO_NEAREST 2
108 #endif
109 #ifndef MONITORINFOF_PRIMARY
110 #define MONITORINFOF_PRIMARY 1
111 #endif
112 #ifndef SM_XVIRTUALSCREEN
113 #define SM_XVIRTUALSCREEN 76
114 #endif
115 #ifndef SM_YVIRTUALSCREEN
116 #define SM_YVIRTUALSCREEN 77
117 #endif
118 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
119 To avoid a compile error on one or the other, redefine with a new name. */
120 struct MONITOR_INFO
122 DWORD cbSize;
123 RECT rcMonitor;
124 RECT rcWork;
125 DWORD dwFlags;
128 #if _WIN32_WINDOWS >= 0x0410
129 #define C_CHILDREN_TITLEBAR CCHILDREN_TITLEBAR
130 typedef TITLEBARINFO TITLEBAR_INFO;
131 #else
132 #define C_CHILDREN_TITLEBAR 5
133 typedef struct
135 DWORD cbSize;
136 RECT rcTitleBar;
137 DWORD rgstate[C_CHILDREN_TITLEBAR+1];
138 } TITLEBAR_INFO, *PTITLEBAR_INFO;
139 #endif
141 #ifndef CCHDEVICENAME
142 #define CCHDEVICENAME 32
143 #endif
144 struct MONITOR_INFO_EX
146 DWORD cbSize;
147 RECT rcMonitor;
148 RECT rcWork;
149 DWORD dwFlags;
150 char szDevice[CCHDEVICENAME];
153 /* Reportedly, MSVC does not have this in its headers. */
154 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
155 DECLARE_HANDLE(HMONITOR);
156 #endif
158 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
159 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
160 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
161 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
162 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
163 typedef BOOL (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
164 typedef BOOL (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
165 IN COMPOSITIONFORM *form);
166 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
167 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
168 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
169 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
170 (IN HWND hwnd, IN DWORD dwFlags);
171 typedef BOOL CALLBACK (* MonitorEnum_Proc)
172 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
173 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
174 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
175 typedef BOOL (WINAPI * GetTitleBarInfo_Proc)
176 (IN HWND hwnd, OUT TITLEBAR_INFO* info);
178 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
179 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
180 ImmGetContext_Proc get_ime_context_fn = NULL;
181 ImmReleaseContext_Proc release_ime_context_fn = NULL;
182 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
183 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
184 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
185 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
186 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
187 GetTitleBarInfo_Proc get_title_bar_info_fn = NULL;
189 extern AppendMenuW_Proc unicode_append_menu;
191 /* Flag to selectively ignore WM_IME_CHAR messages. */
192 static int ignore_ime_char = 0;
194 /* W95 mousewheel handler */
195 unsigned int msh_mousewheel = 0;
197 /* Timers */
198 #define MOUSE_BUTTON_ID 1
199 #define MOUSE_MOVE_ID 2
200 #define MENU_FREE_ID 3
201 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
202 is received. */
203 #define MENU_FREE_DELAY 1000
204 static unsigned menu_free_timer = 0;
206 #ifdef GLYPH_DEBUG
207 static ptrdiff_t image_cache_refcount;
208 static int dpyinfo_refcount;
209 #endif
211 static HWND w32_visible_system_caret_hwnd;
213 static int w32_unicode_gui;
215 /* From w32menu.c */
216 int menubar_in_use = 0;
218 /* From w32uniscribe.c */
219 extern void syms_of_w32uniscribe (void);
220 extern int uniscribe_available;
222 #ifdef WINDOWSNT
223 /* From w32inevt.c */
224 extern int faked_key;
225 #endif /* WINDOWSNT */
227 /* This gives us the page size and the size of the allocation unit on NT. */
228 SYSTEM_INFO sysinfo_cache;
230 /* This gives us version, build, and platform identification. */
231 OSVERSIONINFO osinfo_cache;
233 DWORD_PTR syspage_mask = 0;
235 /* The major and minor versions of NT. */
236 int w32_major_version;
237 int w32_minor_version;
238 int w32_build_number;
240 /* Distinguish between Windows NT and Windows 95. */
241 int os_subtype;
243 #ifdef HAVE_NTGUI
244 HINSTANCE hinst = NULL;
245 #endif
247 static unsigned int sound_type = 0xFFFFFFFF;
248 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
250 /* Special virtual key code for indicating "any" key. */
251 #define VK_ANY 0xFF
253 #ifndef WM_WTSSESSION_CHANGE
254 /* 32-bit MinGW does not define these constants. */
255 # define WM_WTSSESSION_CHANGE 0x02B1
256 # define WTS_SESSION_LOCK 0x7
257 #endif
259 /* Keyboard hook state data. */
260 static struct
262 int hook_count; /* counter, if several windows are created */
263 HHOOK hook; /* hook handle */
264 HWND console; /* console window handle */
266 int lwindown; /* Left Windows key currently pressed (and hooked) */
267 int rwindown; /* Right Windows key currently pressed (and hooked) */
268 int winsdown; /* Number of handled keys currently pressed */
269 int send_win_up; /* Pass through the keyup for this Windows key press? */
270 int suppress_lone; /* Suppress simulated Windows keydown-keyup for this press? */
271 int winseen; /* Windows keys seen during this press? */
273 char alt_hooked[256]; /* hook Alt+[this key]? */
274 char lwin_hooked[256]; /* hook left Win+[this key]? */
275 char rwin_hooked[256]; /* hook right Win+[this key]? */
276 } kbdhook;
277 typedef HWND (WINAPI *GetConsoleWindow_Proc) (void);
279 typedef BOOL (WINAPI *IsDebuggerPresent_Proc) (void);
281 /* stdin, from w32console.c */
282 extern HANDLE keyboard_handle;
284 /* Let the user specify a display with a frame.
285 nil stands for the selected frame--or, if that is not a w32 frame,
286 the first display on the list. */
288 struct w32_display_info *
289 check_x_display_info (Lisp_Object object)
291 if (NILP (object))
293 struct frame *sf = XFRAME (selected_frame);
295 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
296 return FRAME_DISPLAY_INFO (sf);
297 else
298 return &one_w32_display_info;
300 else if (TERMINALP (object))
302 struct terminal *t = decode_live_terminal (object);
304 if (t->type != output_w32)
305 error ("Terminal %d is not a W32 display", t->id);
307 return t->display_info.w32;
309 else if (STRINGP (object))
310 return x_display_info_for_name (object);
311 else
313 struct frame *f;
315 CHECK_LIVE_FRAME (object);
316 f = XFRAME (object);
317 if (! FRAME_W32_P (f))
318 error ("Non-W32 frame used");
319 return FRAME_DISPLAY_INFO (f);
323 /* Return the Emacs frame-object corresponding to an w32 window.
324 It could be the frame's main window or an icon window. */
326 struct frame *
327 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
329 Lisp_Object tail, frame;
330 struct frame *f;
332 FOR_EACH_FRAME (tail, frame)
334 f = XFRAME (frame);
335 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
336 continue;
338 if (FRAME_W32_WINDOW (f) == wdesc)
339 return f;
341 return 0;
345 static Lisp_Object unwind_create_frame (Lisp_Object);
346 static void unwind_create_tip_frame (Lisp_Object);
347 static void my_create_window (struct frame *);
348 static void my_create_tip_window (struct frame *);
350 /* TODO: Native Input Method support; see x_create_im. */
351 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
352 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
353 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
354 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
355 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
356 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
357 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
358 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
359 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
360 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
363 /* Store the screen positions of frame F into XPTR and YPTR.
364 These are the positions of the containing window manager window,
365 not Emacs's own window. */
367 void
368 x_real_positions (struct frame *f, int *xptr, int *yptr)
370 POINT pt;
371 RECT rect;
373 /* Get the bounds of the WM window. */
374 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
376 pt.x = 0;
377 pt.y = 0;
379 /* Convert (0, 0) in the client area to screen co-ordinates. */
380 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
382 *xptr = rect.left;
383 *yptr = rect.top;
386 /* Returns the window rectangle appropriate for the given fullscreen mode.
387 The normal rect parameter was the window's rectangle prior to entering
388 fullscreen mode. If multiple monitor support is available, the nearest
389 monitor to the window is chosen. */
391 void
392 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
394 struct MONITOR_INFO mi = { sizeof(mi) };
395 if (monitor_from_window_fn && get_monitor_info_fn)
397 HMONITOR monitor =
398 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
399 get_monitor_info_fn (monitor, &mi);
401 else
403 mi.rcMonitor.left = 0;
404 mi.rcMonitor.top = 0;
405 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
406 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
407 mi.rcWork.left = 0;
408 mi.rcWork.top = 0;
409 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
410 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
413 switch (fsmode)
415 case FULLSCREEN_BOTH:
416 rect->left = mi.rcMonitor.left;
417 rect->top = mi.rcMonitor.top;
418 rect->right = mi.rcMonitor.right;
419 rect->bottom = mi.rcMonitor.bottom;
420 break;
421 case FULLSCREEN_WIDTH:
422 rect->left = mi.rcWork.left;
423 rect->top = normal.top;
424 rect->right = mi.rcWork.right;
425 rect->bottom = normal.bottom;
426 break;
427 case FULLSCREEN_HEIGHT:
428 rect->left = normal.left;
429 rect->top = mi.rcWork.top;
430 rect->right = normal.right;
431 rect->bottom = mi.rcWork.bottom;
432 break;
433 default:
434 *rect = normal;
435 break;
441 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
442 Sw32_define_rgb_color, 4, 4, 0,
443 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
444 This adds or updates a named color to `w32-color-map', making it
445 available for use. The original entry's RGB ref is returned, or nil
446 if the entry is new. */)
447 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
449 Lisp_Object rgb;
450 Lisp_Object oldrgb = Qnil;
451 Lisp_Object entry;
453 CHECK_NUMBER (red);
454 CHECK_NUMBER (green);
455 CHECK_NUMBER (blue);
456 CHECK_STRING (name);
458 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
460 block_input ();
462 /* replace existing entry in w32-color-map or add new entry. */
463 entry = Fassoc (name, Vw32_color_map);
464 if (NILP (entry))
466 entry = Fcons (name, rgb);
467 Vw32_color_map = Fcons (entry, Vw32_color_map);
469 else
471 oldrgb = Fcdr (entry);
472 Fsetcdr (entry, rgb);
475 unblock_input ();
477 return (oldrgb);
480 /* The default colors for the w32 color map */
481 typedef struct colormap_t
483 const char *name;
484 COLORREF colorref;
485 } colormap_t;
487 colormap_t w32_color_map[] =
489 {"snow" , PALETTERGB (255,250,250)},
490 {"ghost white" , PALETTERGB (248,248,255)},
491 {"GhostWhite" , PALETTERGB (248,248,255)},
492 {"white smoke" , PALETTERGB (245,245,245)},
493 {"WhiteSmoke" , PALETTERGB (245,245,245)},
494 {"gainsboro" , PALETTERGB (220,220,220)},
495 {"floral white" , PALETTERGB (255,250,240)},
496 {"FloralWhite" , PALETTERGB (255,250,240)},
497 {"old lace" , PALETTERGB (253,245,230)},
498 {"OldLace" , PALETTERGB (253,245,230)},
499 {"linen" , PALETTERGB (250,240,230)},
500 {"antique white" , PALETTERGB (250,235,215)},
501 {"AntiqueWhite" , PALETTERGB (250,235,215)},
502 {"papaya whip" , PALETTERGB (255,239,213)},
503 {"PapayaWhip" , PALETTERGB (255,239,213)},
504 {"blanched almond" , PALETTERGB (255,235,205)},
505 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
506 {"bisque" , PALETTERGB (255,228,196)},
507 {"peach puff" , PALETTERGB (255,218,185)},
508 {"PeachPuff" , PALETTERGB (255,218,185)},
509 {"navajo white" , PALETTERGB (255,222,173)},
510 {"NavajoWhite" , PALETTERGB (255,222,173)},
511 {"moccasin" , PALETTERGB (255,228,181)},
512 {"cornsilk" , PALETTERGB (255,248,220)},
513 {"ivory" , PALETTERGB (255,255,240)},
514 {"lemon chiffon" , PALETTERGB (255,250,205)},
515 {"LemonChiffon" , PALETTERGB (255,250,205)},
516 {"seashell" , PALETTERGB (255,245,238)},
517 {"honeydew" , PALETTERGB (240,255,240)},
518 {"mint cream" , PALETTERGB (245,255,250)},
519 {"MintCream" , PALETTERGB (245,255,250)},
520 {"azure" , PALETTERGB (240,255,255)},
521 {"alice blue" , PALETTERGB (240,248,255)},
522 {"AliceBlue" , PALETTERGB (240,248,255)},
523 {"lavender" , PALETTERGB (230,230,250)},
524 {"lavender blush" , PALETTERGB (255,240,245)},
525 {"LavenderBlush" , PALETTERGB (255,240,245)},
526 {"misty rose" , PALETTERGB (255,228,225)},
527 {"MistyRose" , PALETTERGB (255,228,225)},
528 {"white" , PALETTERGB (255,255,255)},
529 {"black" , PALETTERGB ( 0, 0, 0)},
530 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
531 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
532 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
533 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
534 {"dim gray" , PALETTERGB (105,105,105)},
535 {"DimGray" , PALETTERGB (105,105,105)},
536 {"dim grey" , PALETTERGB (105,105,105)},
537 {"DimGrey" , PALETTERGB (105,105,105)},
538 {"slate gray" , PALETTERGB (112,128,144)},
539 {"SlateGray" , PALETTERGB (112,128,144)},
540 {"slate grey" , PALETTERGB (112,128,144)},
541 {"SlateGrey" , PALETTERGB (112,128,144)},
542 {"light slate gray" , PALETTERGB (119,136,153)},
543 {"LightSlateGray" , PALETTERGB (119,136,153)},
544 {"light slate grey" , PALETTERGB (119,136,153)},
545 {"LightSlateGrey" , PALETTERGB (119,136,153)},
546 {"gray" , PALETTERGB (190,190,190)},
547 {"grey" , PALETTERGB (190,190,190)},
548 {"light grey" , PALETTERGB (211,211,211)},
549 {"LightGrey" , PALETTERGB (211,211,211)},
550 {"light gray" , PALETTERGB (211,211,211)},
551 {"LightGray" , PALETTERGB (211,211,211)},
552 {"midnight blue" , PALETTERGB ( 25, 25,112)},
553 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
554 {"navy" , PALETTERGB ( 0, 0,128)},
555 {"navy blue" , PALETTERGB ( 0, 0,128)},
556 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
557 {"cornflower blue" , PALETTERGB (100,149,237)},
558 {"CornflowerBlue" , PALETTERGB (100,149,237)},
559 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
560 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
561 {"slate blue" , PALETTERGB (106, 90,205)},
562 {"SlateBlue" , PALETTERGB (106, 90,205)},
563 {"medium slate blue" , PALETTERGB (123,104,238)},
564 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
565 {"light slate blue" , PALETTERGB (132,112,255)},
566 {"LightSlateBlue" , PALETTERGB (132,112,255)},
567 {"medium blue" , PALETTERGB ( 0, 0,205)},
568 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
569 {"royal blue" , PALETTERGB ( 65,105,225)},
570 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
571 {"blue" , PALETTERGB ( 0, 0,255)},
572 {"dodger blue" , PALETTERGB ( 30,144,255)},
573 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
574 {"deep sky blue" , PALETTERGB ( 0,191,255)},
575 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
576 {"sky blue" , PALETTERGB (135,206,235)},
577 {"SkyBlue" , PALETTERGB (135,206,235)},
578 {"light sky blue" , PALETTERGB (135,206,250)},
579 {"LightSkyBlue" , PALETTERGB (135,206,250)},
580 {"steel blue" , PALETTERGB ( 70,130,180)},
581 {"SteelBlue" , PALETTERGB ( 70,130,180)},
582 {"light steel blue" , PALETTERGB (176,196,222)},
583 {"LightSteelBlue" , PALETTERGB (176,196,222)},
584 {"light blue" , PALETTERGB (173,216,230)},
585 {"LightBlue" , PALETTERGB (173,216,230)},
586 {"powder blue" , PALETTERGB (176,224,230)},
587 {"PowderBlue" , PALETTERGB (176,224,230)},
588 {"pale turquoise" , PALETTERGB (175,238,238)},
589 {"PaleTurquoise" , PALETTERGB (175,238,238)},
590 {"dark turquoise" , PALETTERGB ( 0,206,209)},
591 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
592 {"medium turquoise" , PALETTERGB ( 72,209,204)},
593 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
594 {"turquoise" , PALETTERGB ( 64,224,208)},
595 {"cyan" , PALETTERGB ( 0,255,255)},
596 {"light cyan" , PALETTERGB (224,255,255)},
597 {"LightCyan" , PALETTERGB (224,255,255)},
598 {"cadet blue" , PALETTERGB ( 95,158,160)},
599 {"CadetBlue" , PALETTERGB ( 95,158,160)},
600 {"medium aquamarine" , PALETTERGB (102,205,170)},
601 {"MediumAquamarine" , PALETTERGB (102,205,170)},
602 {"aquamarine" , PALETTERGB (127,255,212)},
603 {"dark green" , PALETTERGB ( 0,100, 0)},
604 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
605 {"dark olive green" , PALETTERGB ( 85,107, 47)},
606 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
607 {"dark sea green" , PALETTERGB (143,188,143)},
608 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
609 {"sea green" , PALETTERGB ( 46,139, 87)},
610 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
611 {"medium sea green" , PALETTERGB ( 60,179,113)},
612 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
613 {"light sea green" , PALETTERGB ( 32,178,170)},
614 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
615 {"pale green" , PALETTERGB (152,251,152)},
616 {"PaleGreen" , PALETTERGB (152,251,152)},
617 {"spring green" , PALETTERGB ( 0,255,127)},
618 {"SpringGreen" , PALETTERGB ( 0,255,127)},
619 {"lawn green" , PALETTERGB (124,252, 0)},
620 {"LawnGreen" , PALETTERGB (124,252, 0)},
621 {"green" , PALETTERGB ( 0,255, 0)},
622 {"chartreuse" , PALETTERGB (127,255, 0)},
623 {"medium spring green" , PALETTERGB ( 0,250,154)},
624 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
625 {"green yellow" , PALETTERGB (173,255, 47)},
626 {"GreenYellow" , PALETTERGB (173,255, 47)},
627 {"lime green" , PALETTERGB ( 50,205, 50)},
628 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
629 {"yellow green" , PALETTERGB (154,205, 50)},
630 {"YellowGreen" , PALETTERGB (154,205, 50)},
631 {"forest green" , PALETTERGB ( 34,139, 34)},
632 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
633 {"olive drab" , PALETTERGB (107,142, 35)},
634 {"OliveDrab" , PALETTERGB (107,142, 35)},
635 {"dark khaki" , PALETTERGB (189,183,107)},
636 {"DarkKhaki" , PALETTERGB (189,183,107)},
637 {"khaki" , PALETTERGB (240,230,140)},
638 {"pale goldenrod" , PALETTERGB (238,232,170)},
639 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
640 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
641 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
642 {"light yellow" , PALETTERGB (255,255,224)},
643 {"LightYellow" , PALETTERGB (255,255,224)},
644 {"yellow" , PALETTERGB (255,255, 0)},
645 {"gold" , PALETTERGB (255,215, 0)},
646 {"light goldenrod" , PALETTERGB (238,221,130)},
647 {"LightGoldenrod" , PALETTERGB (238,221,130)},
648 {"goldenrod" , PALETTERGB (218,165, 32)},
649 {"dark goldenrod" , PALETTERGB (184,134, 11)},
650 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
651 {"rosy brown" , PALETTERGB (188,143,143)},
652 {"RosyBrown" , PALETTERGB (188,143,143)},
653 {"indian red" , PALETTERGB (205, 92, 92)},
654 {"IndianRed" , PALETTERGB (205, 92, 92)},
655 {"saddle brown" , PALETTERGB (139, 69, 19)},
656 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
657 {"sienna" , PALETTERGB (160, 82, 45)},
658 {"peru" , PALETTERGB (205,133, 63)},
659 {"burlywood" , PALETTERGB (222,184,135)},
660 {"beige" , PALETTERGB (245,245,220)},
661 {"wheat" , PALETTERGB (245,222,179)},
662 {"sandy brown" , PALETTERGB (244,164, 96)},
663 {"SandyBrown" , PALETTERGB (244,164, 96)},
664 {"tan" , PALETTERGB (210,180,140)},
665 {"chocolate" , PALETTERGB (210,105, 30)},
666 {"firebrick" , PALETTERGB (178,34, 34)},
667 {"brown" , PALETTERGB (165,42, 42)},
668 {"dark salmon" , PALETTERGB (233,150,122)},
669 {"DarkSalmon" , PALETTERGB (233,150,122)},
670 {"salmon" , PALETTERGB (250,128,114)},
671 {"light salmon" , PALETTERGB (255,160,122)},
672 {"LightSalmon" , PALETTERGB (255,160,122)},
673 {"orange" , PALETTERGB (255,165, 0)},
674 {"dark orange" , PALETTERGB (255,140, 0)},
675 {"DarkOrange" , PALETTERGB (255,140, 0)},
676 {"coral" , PALETTERGB (255,127, 80)},
677 {"light coral" , PALETTERGB (240,128,128)},
678 {"LightCoral" , PALETTERGB (240,128,128)},
679 {"tomato" , PALETTERGB (255, 99, 71)},
680 {"orange red" , PALETTERGB (255, 69, 0)},
681 {"OrangeRed" , PALETTERGB (255, 69, 0)},
682 {"red" , PALETTERGB (255, 0, 0)},
683 {"hot pink" , PALETTERGB (255,105,180)},
684 {"HotPink" , PALETTERGB (255,105,180)},
685 {"deep pink" , PALETTERGB (255, 20,147)},
686 {"DeepPink" , PALETTERGB (255, 20,147)},
687 {"pink" , PALETTERGB (255,192,203)},
688 {"light pink" , PALETTERGB (255,182,193)},
689 {"LightPink" , PALETTERGB (255,182,193)},
690 {"pale violet red" , PALETTERGB (219,112,147)},
691 {"PaleVioletRed" , PALETTERGB (219,112,147)},
692 {"maroon" , PALETTERGB (176, 48, 96)},
693 {"medium violet red" , PALETTERGB (199, 21,133)},
694 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
695 {"violet red" , PALETTERGB (208, 32,144)},
696 {"VioletRed" , PALETTERGB (208, 32,144)},
697 {"magenta" , PALETTERGB (255, 0,255)},
698 {"violet" , PALETTERGB (238,130,238)},
699 {"plum" , PALETTERGB (221,160,221)},
700 {"orchid" , PALETTERGB (218,112,214)},
701 {"medium orchid" , PALETTERGB (186, 85,211)},
702 {"MediumOrchid" , PALETTERGB (186, 85,211)},
703 {"dark orchid" , PALETTERGB (153, 50,204)},
704 {"DarkOrchid" , PALETTERGB (153, 50,204)},
705 {"dark violet" , PALETTERGB (148, 0,211)},
706 {"DarkViolet" , PALETTERGB (148, 0,211)},
707 {"blue violet" , PALETTERGB (138, 43,226)},
708 {"BlueViolet" , PALETTERGB (138, 43,226)},
709 {"purple" , PALETTERGB (160, 32,240)},
710 {"medium purple" , PALETTERGB (147,112,219)},
711 {"MediumPurple" , PALETTERGB (147,112,219)},
712 {"thistle" , PALETTERGB (216,191,216)},
713 {"gray0" , PALETTERGB ( 0, 0, 0)},
714 {"grey0" , PALETTERGB ( 0, 0, 0)},
715 {"dark grey" , PALETTERGB (169,169,169)},
716 {"DarkGrey" , PALETTERGB (169,169,169)},
717 {"dark gray" , PALETTERGB (169,169,169)},
718 {"DarkGray" , PALETTERGB (169,169,169)},
719 {"dark blue" , PALETTERGB ( 0, 0,139)},
720 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
721 {"dark cyan" , PALETTERGB ( 0,139,139)},
722 {"DarkCyan" , PALETTERGB ( 0,139,139)},
723 {"dark magenta" , PALETTERGB (139, 0,139)},
724 {"DarkMagenta" , PALETTERGB (139, 0,139)},
725 {"dark red" , PALETTERGB (139, 0, 0)},
726 {"DarkRed" , PALETTERGB (139, 0, 0)},
727 {"light green" , PALETTERGB (144,238,144)},
728 {"LightGreen" , PALETTERGB (144,238,144)},
731 static Lisp_Object
732 w32_default_color_map (void)
734 int i;
735 colormap_t *pc = w32_color_map;
736 Lisp_Object cmap;
738 block_input ();
740 cmap = Qnil;
742 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
743 cmap = Fcons (Fcons (build_string (pc->name),
744 make_number (pc->colorref)),
745 cmap);
747 unblock_input ();
749 return (cmap);
752 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
753 0, 0, 0, doc: /* Return the default color map. */)
754 (void)
756 return w32_default_color_map ();
759 static Lisp_Object
760 w32_color_map_lookup (const char *colorname)
762 Lisp_Object tail, ret = Qnil;
764 block_input ();
766 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
768 register Lisp_Object elt, tem;
770 elt = XCAR (tail);
771 if (!CONSP (elt)) continue;
773 tem = XCAR (elt);
775 if (lstrcmpi (SSDATA (tem), colorname) == 0)
777 ret = Fcdr (elt);
778 break;
781 maybe_quit ();
784 unblock_input ();
786 return ret;
790 static void
791 add_system_logical_colors_to_map (Lisp_Object *system_colors)
793 HKEY colors_key;
795 /* Other registry operations are done with input blocked. */
796 block_input ();
798 /* Look for "Control Panel/Colors" under User and Machine registry
799 settings. */
800 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
801 KEY_READ, &colors_key) == ERROR_SUCCESS
802 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
803 KEY_READ, &colors_key) == ERROR_SUCCESS)
805 /* List all keys. */
806 char color_buffer[64];
807 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
808 int index = 0;
809 DWORD name_size, color_size;
810 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
812 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
813 color_size = sizeof (color_buffer);
815 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
817 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
818 NULL, NULL, (LPBYTE)color_buffer, &color_size)
819 == ERROR_SUCCESS)
821 unsigned r, g, b;
822 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
823 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
824 make_number (RGB (r, g, b))),
825 *system_colors);
827 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
828 color_size = sizeof (color_buffer);
829 index++;
831 RegCloseKey (colors_key);
834 unblock_input ();
838 static Lisp_Object
839 x_to_w32_color (const char * colorname)
841 register Lisp_Object ret = Qnil;
843 block_input ();
845 if (colorname[0] == '#')
847 /* Could be an old-style RGB Device specification. */
848 int size = strlen (colorname + 1);
849 char *color = alloca (size + 1);
851 strcpy (color, colorname + 1);
852 if (size == 3 || size == 6 || size == 9 || size == 12)
854 UINT colorval;
855 int i, pos;
856 pos = 0;
857 size /= 3;
858 colorval = 0;
860 for (i = 0; i < 3; i++)
862 char *end;
863 char t;
864 unsigned long value;
866 /* The check for 'x' in the following conditional takes into
867 account the fact that strtol allows a "0x" in front of
868 our numbers, and we don't. */
869 if (!isxdigit (color[0]) || color[1] == 'x')
870 break;
871 t = color[size];
872 color[size] = '\0';
873 value = strtoul (color, &end, 16);
874 color[size] = t;
875 if (errno == ERANGE || end - color != size)
876 break;
877 switch (size)
879 case 1:
880 value = value * 0x10;
881 break;
882 case 2:
883 break;
884 case 3:
885 value /= 0x10;
886 break;
887 case 4:
888 value /= 0x100;
889 break;
891 colorval |= (value << pos);
892 pos += 0x8;
893 if (i == 2)
895 unblock_input ();
896 XSETINT (ret, colorval);
897 return ret;
899 color = end;
903 else if (strnicmp (colorname, "rgb:", 4) == 0)
905 const char *color;
906 UINT colorval;
907 int i, pos;
908 pos = 0;
910 colorval = 0;
911 color = colorname + 4;
912 for (i = 0; i < 3; i++)
914 char *end;
915 unsigned long value;
917 /* The check for 'x' in the following conditional takes into
918 account the fact that strtol allows a "0x" in front of
919 our numbers, and we don't. */
920 if (!isxdigit (color[0]) || color[1] == 'x')
921 break;
922 value = strtoul (color, &end, 16);
923 if (errno == ERANGE)
924 break;
925 switch (end - color)
927 case 1:
928 value = value * 0x10 + value;
929 break;
930 case 2:
931 break;
932 case 3:
933 value /= 0x10;
934 break;
935 case 4:
936 value /= 0x100;
937 break;
938 default:
939 value = ULONG_MAX;
941 if (value == ULONG_MAX)
942 break;
943 colorval |= (value << pos);
944 pos += 0x8;
945 if (i == 2)
947 if (*end != '\0')
948 break;
949 unblock_input ();
950 XSETINT (ret, colorval);
951 return ret;
953 if (*end != '/')
954 break;
955 color = end + 1;
958 else if (strnicmp (colorname, "rgbi:", 5) == 0)
960 /* This is an RGB Intensity specification. */
961 const char *color;
962 UINT colorval;
963 int i, pos;
964 pos = 0;
966 colorval = 0;
967 color = colorname + 5;
968 for (i = 0; i < 3; i++)
970 char *end;
971 double value;
972 UINT val;
974 value = strtod (color, &end);
975 if (errno == ERANGE)
976 break;
977 if (value < 0.0 || value > 1.0)
978 break;
979 val = (UINT)(0x100 * value);
980 /* We used 0x100 instead of 0xFF to give a continuous
981 range between 0.0 and 1.0 inclusive. The next statement
982 fixes the 1.0 case. */
983 if (val == 0x100)
984 val = 0xFF;
985 colorval |= (val << pos);
986 pos += 0x8;
987 if (i == 2)
989 if (*end != '\0')
990 break;
991 unblock_input ();
992 XSETINT (ret, colorval);
993 return ret;
995 if (*end != '/')
996 break;
997 color = end + 1;
1000 /* I am not going to attempt to handle any of the CIE color schemes
1001 or TekHVC, since I don't know the algorithms for conversion to
1002 RGB. */
1004 /* If we fail to lookup the color name in w32_color_map, then check the
1005 colorname to see if it can be crudely approximated: If the X color
1006 ends in a number (e.g., "darkseagreen2"), strip the number and
1007 return the result of looking up the base color name. */
1008 ret = w32_color_map_lookup (colorname);
1009 if (NILP (ret))
1011 int len = strlen (colorname);
1013 if (isdigit (colorname[len - 1]))
1015 char *ptr, *approx = alloca (len + 1);
1017 strcpy (approx, colorname);
1018 ptr = &approx[len - 1];
1019 while (ptr > approx && isdigit (*ptr))
1020 *ptr-- = '\0';
1022 ret = w32_color_map_lookup (approx);
1026 unblock_input ();
1027 return ret;
1030 void
1031 w32_regenerate_palette (struct frame *f)
1033 struct w32_palette_entry * list;
1034 LOGPALETTE * log_palette;
1035 HPALETTE new_palette;
1036 int i;
1038 /* don't bother trying to create palette if not supported */
1039 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1040 return;
1042 log_palette = (LOGPALETTE *)
1043 alloca (sizeof (LOGPALETTE) +
1044 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1045 log_palette->palVersion = 0x300;
1046 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1048 list = FRAME_DISPLAY_INFO (f)->color_list;
1049 for (i = 0;
1050 i < FRAME_DISPLAY_INFO (f)->num_colors;
1051 i++, list = list->next)
1052 log_palette->palPalEntry[i] = list->entry;
1054 new_palette = CreatePalette (log_palette);
1056 enter_crit ();
1058 if (FRAME_DISPLAY_INFO (f)->palette)
1059 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1060 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1062 /* Realize display palette and garbage all frames. */
1063 release_frame_dc (f, get_frame_dc (f));
1065 leave_crit ();
1068 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1069 #define SET_W32_COLOR(pe, color) \
1070 do \
1072 pe.peRed = GetRValue (color); \
1073 pe.peGreen = GetGValue (color); \
1074 pe.peBlue = GetBValue (color); \
1075 pe.peFlags = 0; \
1076 } while (0)
1078 #if 0
1079 /* Keep these around in case we ever want to track color usage. */
1080 void
1081 w32_map_color (struct frame *f, COLORREF color)
1083 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1085 if (NILP (Vw32_enable_palette))
1086 return;
1088 /* check if color is already mapped */
1089 while (list)
1091 if (W32_COLOR (list->entry) == color)
1093 ++list->refcount;
1094 return;
1096 list = list->next;
1099 /* not already mapped, so add to list and recreate Windows palette */
1100 list = xmalloc (sizeof (struct w32_palette_entry));
1101 SET_W32_COLOR (list->entry, color);
1102 list->refcount = 1;
1103 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1104 FRAME_DISPLAY_INFO (f)->color_list = list;
1105 FRAME_DISPLAY_INFO (f)->num_colors++;
1107 /* set flag that palette must be regenerated */
1108 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1111 void
1112 w32_unmap_color (struct frame *f, COLORREF color)
1114 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1115 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1117 if (NILP (Vw32_enable_palette))
1118 return;
1120 /* check if color is already mapped */
1121 while (list)
1123 if (W32_COLOR (list->entry) == color)
1125 if (--list->refcount == 0)
1127 *prev = list->next;
1128 xfree (list);
1129 FRAME_DISPLAY_INFO (f)->num_colors--;
1130 break;
1132 else
1133 return;
1135 prev = &list->next;
1136 list = list->next;
1139 /* set flag that palette must be regenerated */
1140 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1142 #endif
1145 /* Gamma-correct COLOR on frame F. */
1147 void
1148 gamma_correct (struct frame *f, COLORREF *color)
1150 if (f->gamma)
1152 *color = PALETTERGB (
1153 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1154 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1155 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1160 /* Decide if color named COLOR is valid for the display associated with
1161 the selected frame; if so, return the rgb values in COLOR_DEF.
1162 If ALLOC is nonzero, allocate a new colormap cell. */
1165 w32_defined_color (struct frame *f, const char *color, XColor *color_def,
1166 bool alloc_p)
1168 register Lisp_Object tem;
1169 COLORREF w32_color_ref;
1171 tem = x_to_w32_color (color);
1173 if (!NILP (tem))
1175 if (f)
1177 /* Apply gamma correction. */
1178 w32_color_ref = XUINT (tem);
1179 gamma_correct (f, &w32_color_ref);
1180 XSETINT (tem, w32_color_ref);
1183 /* Map this color to the palette if it is enabled. */
1184 if (!NILP (Vw32_enable_palette))
1186 struct w32_palette_entry * entry =
1187 one_w32_display_info.color_list;
1188 struct w32_palette_entry ** prev =
1189 &one_w32_display_info.color_list;
1191 /* check if color is already mapped */
1192 while (entry)
1194 if (W32_COLOR (entry->entry) == XUINT (tem))
1195 break;
1196 prev = &entry->next;
1197 entry = entry->next;
1200 if (entry == NULL && alloc_p)
1202 /* not already mapped, so add to list */
1203 entry = xmalloc (sizeof (struct w32_palette_entry));
1204 SET_W32_COLOR (entry->entry, XUINT (tem));
1205 entry->next = NULL;
1206 *prev = entry;
1207 one_w32_display_info.num_colors++;
1209 /* set flag that palette must be regenerated */
1210 one_w32_display_info.regen_palette = TRUE;
1213 /* Ensure COLORREF value is snapped to nearest color in (default)
1214 palette by simulating the PALETTERGB macro. This works whether
1215 or not the display device has a palette. */
1216 w32_color_ref = XUINT (tem) | 0x2000000;
1218 color_def->pixel = w32_color_ref;
1219 color_def->red = GetRValue (w32_color_ref) * 256;
1220 color_def->green = GetGValue (w32_color_ref) * 256;
1221 color_def->blue = GetBValue (w32_color_ref) * 256;
1223 return 1;
1225 else
1227 return 0;
1231 /* Given a string ARG naming a color, compute a pixel value from it
1232 suitable for screen F.
1233 If F is not a color screen, return DEF (default) regardless of what
1234 ARG says. */
1236 static int
1237 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1239 XColor cdef;
1241 CHECK_STRING (arg);
1243 if (strcmp (SSDATA (arg), "black") == 0)
1244 return BLACK_PIX_DEFAULT (f);
1245 else if (strcmp (SSDATA (arg), "white") == 0)
1246 return WHITE_PIX_DEFAULT (f);
1248 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1249 return def;
1251 /* w32_defined_color is responsible for coping with failures
1252 by looking for a near-miss. */
1253 if (w32_defined_color (f, SSDATA (arg), &cdef, true))
1254 return cdef.pixel;
1256 /* defined_color failed; return an ultimate default. */
1257 return def;
1262 /* Functions called only from `x_set_frame_param'
1263 to set individual parameters.
1265 If FRAME_W32_WINDOW (f) is 0,
1266 the frame is being created and its window does not exist yet.
1267 In that case, just record the parameter's new value
1268 in the standard place; do not attempt to change the window. */
1270 void
1271 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1273 struct w32_output *x = f->output_data.w32;
1274 PIX_TYPE fg, old_fg;
1276 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1277 old_fg = FRAME_FOREGROUND_PIXEL (f);
1278 FRAME_FOREGROUND_PIXEL (f) = fg;
1280 if (FRAME_W32_WINDOW (f) != 0)
1282 if (x->cursor_pixel == old_fg)
1284 x->cursor_pixel = fg;
1285 x->cursor_gc->background = fg;
1288 update_face_from_frame_parameter (f, Qforeground_color, arg);
1289 if (FRAME_VISIBLE_P (f))
1290 redraw_frame (f);
1294 void
1295 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1297 FRAME_BACKGROUND_PIXEL (f)
1298 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1300 if (FRAME_W32_WINDOW (f) != 0)
1302 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1303 FRAME_BACKGROUND_PIXEL (f));
1305 update_face_from_frame_parameter (f, Qbackground_color, arg);
1307 if (FRAME_VISIBLE_P (f))
1308 redraw_frame (f);
1312 void
1313 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1315 #if 0
1316 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1317 int count;
1318 #endif
1319 int mask_color;
1321 if (!EQ (Qnil, arg))
1322 f->output_data.w32->mouse_pixel
1323 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1324 mask_color = FRAME_BACKGROUND_PIXEL (f);
1326 /* Don't let pointers be invisible. */
1327 if (mask_color == f->output_data.w32->mouse_pixel
1328 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1329 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1331 #if 0 /* TODO : Mouse cursor customization. */
1332 block_input ();
1334 /* It's not okay to crash if the user selects a screwy cursor. */
1335 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1337 if (!EQ (Qnil, Vx_pointer_shape))
1339 CHECK_NUMBER (Vx_pointer_shape);
1340 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1342 else
1343 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1344 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1346 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1348 CHECK_NUMBER (Vx_nontext_pointer_shape);
1349 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1350 XINT (Vx_nontext_pointer_shape));
1352 else
1353 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1354 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1356 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1358 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1359 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1360 XINT (Vx_hourglass_pointer_shape));
1362 else
1363 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1364 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1366 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1367 if (!EQ (Qnil, Vx_mode_pointer_shape))
1369 CHECK_NUMBER (Vx_mode_pointer_shape);
1370 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1371 XINT (Vx_mode_pointer_shape));
1373 else
1374 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1375 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1377 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1379 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1380 hand_cursor
1381 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1382 XINT (Vx_sensitive_text_pointer_shape));
1384 else
1385 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1387 if (!NILP (Vx_window_horizontal_drag_shape))
1389 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1390 horizontal_drag_cursor
1391 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1392 XINT (Vx_window_horizontal_drag_shape));
1394 else
1395 horizontal_drag_cursor
1396 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1398 if (!NILP (Vx_window_vertical_drag_shape))
1400 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1401 vertical_drag_cursor
1402 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1403 XINT (Vx_window_vertical_drag_shape));
1405 else
1406 vertical_drag_cursor
1407 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1409 /* Check and report errors with the above calls. */
1410 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1411 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1414 XColor fore_color, back_color;
1416 fore_color.pixel = f->output_data.w32->mouse_pixel;
1417 back_color.pixel = mask_color;
1418 XQueryColor (FRAME_W32_DISPLAY (f),
1419 DefaultColormap (FRAME_W32_DISPLAY (f),
1420 DefaultScreen (FRAME_W32_DISPLAY (f))),
1421 &fore_color);
1422 XQueryColor (FRAME_W32_DISPLAY (f),
1423 DefaultColormap (FRAME_W32_DISPLAY (f),
1424 DefaultScreen (FRAME_W32_DISPLAY (f))),
1425 &back_color);
1426 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1427 &fore_color, &back_color);
1428 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1429 &fore_color, &back_color);
1430 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1431 &fore_color, &back_color);
1432 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1433 &fore_color, &back_color);
1434 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1435 &fore_color, &back_color);
1438 if (FRAME_W32_WINDOW (f) != 0)
1439 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1441 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1442 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1443 f->output_data.w32->text_cursor = cursor;
1445 if (nontext_cursor != f->output_data.w32->nontext_cursor
1446 && f->output_data.w32->nontext_cursor != 0)
1447 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1448 f->output_data.w32->nontext_cursor = nontext_cursor;
1450 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1451 && f->output_data.w32->hourglass_cursor != 0)
1452 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1453 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1455 if (mode_cursor != f->output_data.w32->modeline_cursor
1456 && f->output_data.w32->modeline_cursor != 0)
1457 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1458 f->output_data.w32->modeline_cursor = mode_cursor;
1460 if (hand_cursor != f->output_data.w32->hand_cursor
1461 && f->output_data.w32->hand_cursor != 0)
1462 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1463 f->output_data.w32->hand_cursor = hand_cursor;
1465 XFlush (FRAME_W32_DISPLAY (f));
1466 unblock_input ();
1468 update_face_from_frame_parameter (f, Qmouse_color, arg);
1469 #endif /* TODO */
1472 void
1473 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1475 unsigned long fore_pixel, pixel;
1477 if (!NILP (Vx_cursor_fore_pixel))
1478 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1479 WHITE_PIX_DEFAULT (f));
1480 else
1481 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1483 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1485 /* Make sure that the cursor color differs from the background color. */
1486 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1488 pixel = f->output_data.w32->mouse_pixel;
1489 if (pixel == fore_pixel)
1490 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1493 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1494 f->output_data.w32->cursor_pixel = pixel;
1496 if (FRAME_W32_WINDOW (f) != 0)
1498 block_input ();
1499 /* Update frame's cursor_gc. */
1500 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1501 f->output_data.w32->cursor_gc->background = pixel;
1503 unblock_input ();
1505 if (FRAME_VISIBLE_P (f))
1507 x_update_cursor (f, 0);
1508 x_update_cursor (f, 1);
1512 update_face_from_frame_parameter (f, Qcursor_color, arg);
1515 /* Set the border-color of frame F to pixel value PIX.
1516 Note that this does not fully take effect if done before
1517 F has a window. */
1519 static void
1520 x_set_border_pixel (struct frame *f, int pix)
1523 f->output_data.w32->border_pixel = pix;
1525 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1527 if (FRAME_VISIBLE_P (f))
1528 redraw_frame (f);
1532 /* Set the border-color of frame F to value described by ARG.
1533 ARG can be a string naming a color.
1534 The border-color is used for the border that is drawn by the server.
1535 Note that this does not fully take effect if done before
1536 F has a window; it must be redone when the window is created. */
1538 void
1539 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1541 int pix;
1543 CHECK_STRING (arg);
1544 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1545 x_set_border_pixel (f, pix);
1546 update_face_from_frame_parameter (f, Qborder_color, arg);
1550 void
1551 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1553 set_frame_cursor_types (f, arg);
1556 void
1557 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1559 bool result;
1561 if (NILP (arg) && NILP (oldval))
1562 return;
1564 if (STRINGP (arg) && STRINGP (oldval)
1565 && EQ (Fstring_equal (oldval, arg), Qt))
1566 return;
1568 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1569 return;
1571 block_input ();
1573 result = x_bitmap_icon (f, arg);
1574 if (result)
1576 unblock_input ();
1577 error ("No icon window available");
1580 unblock_input ();
1583 void
1584 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1586 if (STRINGP (arg))
1588 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1589 return;
1591 else if (!NILP (arg) || NILP (oldval))
1592 return;
1594 fset_icon_name (f, arg);
1596 #if 0
1597 if (f->output_data.w32->icon_bitmap != 0)
1598 return;
1600 block_input ();
1602 result = x_text_icon (f,
1603 SSDATA ((!NILP (f->icon_name)
1604 ? f->icon_name
1605 : !NILP (f->title)
1606 ? f->title
1607 : f->name)));
1609 if (result)
1611 unblock_input ();
1612 error ("No icon window available");
1615 /* If the window was unmapped (and its icon was mapped),
1616 the new icon is not mapped, so map the window in its stead. */
1617 if (FRAME_VISIBLE_P (f))
1619 #ifdef USE_X_TOOLKIT
1620 XtPopup (f->output_data.w32->widget, XtGrabNone);
1621 #endif
1622 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1625 XFlush (FRAME_W32_DISPLAY (f));
1626 unblock_input ();
1627 #endif
1630 static void
1631 x_clear_under_internal_border (struct frame *f)
1633 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1635 /* Clear border if it's larger than before. */
1636 if (border != 0)
1638 HDC hdc = get_frame_dc (f);
1639 int width = FRAME_PIXEL_WIDTH (f);
1640 int height = FRAME_PIXEL_HEIGHT (f);
1642 block_input ();
1643 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1644 w32_clear_area (f, hdc, 0, 0, border, height);
1645 w32_clear_area (f, hdc, width - border, 0, border, height);
1646 w32_clear_area (f, hdc, 0, height - border, width, border);
1647 release_frame_dc (f, hdc);
1648 unblock_input ();
1653 void
1654 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1656 int border;
1658 CHECK_TYPE_RANGED_INTEGER (int, arg);
1659 border = max (XINT (arg), 0);
1661 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1663 f->internal_border_width = border;
1665 if (FRAME_X_WINDOW (f) != 0)
1667 adjust_frame_size (f, -1, -1, 3, false, Qinternal_border_width);
1669 if (FRAME_VISIBLE_P (f))
1670 x_clear_under_internal_border (f);
1676 void
1677 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1679 int nlines;
1681 /* Right now, menu bars don't work properly in minibuf-only frames;
1682 most of the commands try to apply themselves to the minibuffer
1683 frame itself, and get an error because you can't switch buffers
1684 in or split the minibuffer window. */
1685 if (FRAME_MINIBUF_ONLY_P (f))
1686 return;
1688 if (INTEGERP (value))
1689 nlines = XINT (value);
1690 else
1691 nlines = 0;
1693 FRAME_MENU_BAR_LINES (f) = 0;
1694 FRAME_MENU_BAR_HEIGHT (f) = 0;
1695 if (nlines)
1696 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1697 else
1699 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1700 free_frame_menubar (f);
1701 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1703 /* Adjust the frame size so that the client (text) dimensions
1704 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1705 set correctly. Note that we resize twice: The first time upon
1706 a request from the window manager who wants to keep the height
1707 of the outer rectangle (including decorations) unchanged, and a
1708 second time because we want to keep the height of the inner
1709 rectangle (without the decorations unchanged). */
1710 adjust_frame_size (f, -1, -1, 2, true, Qmenu_bar_lines);
1712 /* Not sure whether this is needed. */
1713 x_clear_under_internal_border (f);
1718 /* Set the number of lines used for the tool bar of frame F to VALUE.
1719 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1720 the old number of tool bar lines (and is unused). This function may
1721 change the height of all windows on frame F to match the new tool bar
1722 height. By design, the frame's height doesn't change (but maybe it
1723 should if we don't get enough space otherwise). */
1725 void
1726 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1728 int nlines;
1730 /* Treat tool bars like menu bars. */
1731 if (FRAME_MINIBUF_ONLY_P (f))
1732 return;
1734 /* Use VALUE only if an integer >= 0. */
1735 if (INTEGERP (value) && XINT (value) >= 0)
1736 nlines = XFASTINT (value);
1737 else
1738 nlines = 0;
1740 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1744 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1745 void
1746 x_change_tool_bar_height (struct frame *f, int height)
1748 int unit = FRAME_LINE_HEIGHT (f);
1749 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1750 int lines = (height + unit - 1) / unit;
1751 Lisp_Object fullscreen;
1753 /* Make sure we redisplay all windows in this frame. */
1754 windows_or_buffers_changed = 23;
1756 /* Recalculate tool bar and frame text sizes. */
1757 FRAME_TOOL_BAR_HEIGHT (f) = height;
1758 FRAME_TOOL_BAR_LINES (f) = lines;
1759 /* Store `tool-bar-lines' and `height' frame parameters. */
1760 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1761 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1763 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1765 clear_frame (f);
1766 clear_current_matrices (f);
1769 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1770 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1772 /* Recalculate toolbar height. */
1773 f->n_tool_bar_rows = 0;
1774 if (old_height == 0
1775 && (!f->after_make_frame
1776 || NILP (frame_inhibit_implied_resize)
1777 || (CONSP (frame_inhibit_implied_resize)
1778 && NILP (Fmemq (Qtool_bar_lines, frame_inhibit_implied_resize)))))
1779 f->tool_bar_redisplayed = f->tool_bar_resized = false;
1781 adjust_frame_size (f, -1, -1,
1782 ((!f->tool_bar_resized
1783 && (NILP (fullscreen =
1784 get_frame_param (f, Qfullscreen))
1785 || EQ (fullscreen, Qfullwidth))) ? 1
1786 : (old_height == 0 || height == 0) ? 2
1787 : 4),
1788 false, Qtool_bar_lines);
1790 f->tool_bar_resized = f->tool_bar_redisplayed;
1792 /* adjust_frame_size might not have done anything, garbage frame
1793 here. */
1794 adjust_frame_glyphs (f);
1795 SET_FRAME_GARBAGED (f);
1796 if (FRAME_X_WINDOW (f))
1797 x_clear_under_internal_border (f);
1800 static void
1801 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1803 if (FRAME_W32_WINDOW (f))
1805 block_input ();
1806 #ifdef __CYGWIN__
1807 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1808 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1809 #else
1810 /* The frame's title many times shows the name of the file
1811 visited in the selected window's buffer, so it makes sense to
1812 support non-ASCII characters outside of the current system
1813 codepage in the title. */
1814 if (w32_unicode_filenames)
1816 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1817 wchar_t *title_w;
1818 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1819 -1, NULL, 0);
1821 if (tlen > 0)
1823 /* Windows truncates the title text beyond what fits on
1824 a single line, so we can limit the length to some
1825 reasonably large value, and use alloca. */
1826 if (tlen > 10000)
1827 tlen = 10000;
1828 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1829 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1830 title_w, tlen);
1831 title_w[tlen] = L'\0';
1832 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1834 else /* Conversion to UTF-16 failed, so we punt. */
1835 SetWindowTextA (FRAME_W32_WINDOW (f),
1836 SSDATA (ENCODE_SYSTEM (name)));
1838 else
1839 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1840 #endif
1841 unblock_input ();
1845 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1846 w32_id_name.
1848 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1849 name; if NAME is a string, set F's name to NAME and set
1850 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1852 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1853 suggesting a new name, which lisp code should override; if
1854 F->explicit_name is set, ignore the new name; otherwise, set it. */
1856 static void
1857 x_set_name (struct frame *f, Lisp_Object name, bool explicit)
1859 /* Make sure that requests from lisp code override requests from
1860 Emacs redisplay code. */
1861 if (explicit)
1863 /* If we're switching from explicit to implicit, we had better
1864 update the mode lines and thereby update the title. */
1865 if (f->explicit_name && NILP (name))
1866 update_mode_lines = 25;
1868 f->explicit_name = ! NILP (name);
1870 else if (f->explicit_name)
1871 return;
1873 /* If NAME is nil, set the name to the w32_id_name. */
1874 if (NILP (name))
1876 /* Check for no change needed in this very common case
1877 before we do any consing. */
1878 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1879 SSDATA (f->name)))
1880 return;
1881 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1883 else
1884 CHECK_STRING (name);
1886 /* Don't change the name if it's already NAME. */
1887 if (! NILP (Fstring_equal (name, f->name)))
1888 return;
1890 fset_name (f, name);
1892 /* For setting the frame title, the title parameter should override
1893 the name parameter. */
1894 if (! NILP (f->title))
1895 name = f->title;
1897 w32_set_title_bar_text (f, name);
1900 /* This function should be called when the user's lisp code has
1901 specified a name for the frame; the name will override any set by the
1902 redisplay code. */
1903 void
1904 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1906 x_set_name (f, arg, true);
1909 /* This function should be called by Emacs redisplay code to set the
1910 name; names set this way will never override names set by the user's
1911 lisp code. */
1912 void
1913 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1915 x_set_name (f, arg, false);
1918 /* Change the title of frame F to NAME.
1919 If NAME is nil, use the frame name as the title. */
1921 void
1922 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1924 /* Don't change the title if it's already NAME. */
1925 if (EQ (name, f->title))
1926 return;
1928 update_mode_lines = 26;
1930 fset_title (f, name);
1932 if (NILP (name))
1933 name = f->name;
1935 w32_set_title_bar_text (f, name);
1938 void
1939 x_set_scroll_bar_default_width (struct frame *f)
1941 int unit = FRAME_COLUMN_WIDTH (f);
1943 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1944 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1945 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1949 void
1950 x_set_scroll_bar_default_height (struct frame *f)
1952 int unit = FRAME_LINE_HEIGHT (f);
1954 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
1955 FRAME_CONFIG_SCROLL_BAR_LINES (f)
1956 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
1959 /* Subroutines for creating a frame. */
1961 Cursor w32_load_cursor (LPCTSTR);
1963 Cursor
1964 w32_load_cursor (LPCTSTR name)
1966 /* Try first to load cursor from application resource. */
1967 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1968 name, IMAGE_CURSOR, 0, 0,
1969 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1970 if (!cursor)
1972 /* Then try to load a shared predefined cursor. */
1973 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1974 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1976 return cursor;
1979 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1981 #define INIT_WINDOW_CLASS(WC) \
1982 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1983 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1984 (WC).cbClsExtra = 0; \
1985 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1986 (WC).hInstance = hinst; \
1987 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1988 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1989 (WC).hbrBackground = NULL; \
1990 (WC).lpszMenuName = NULL; \
1992 static BOOL
1993 w32_init_class (HINSTANCE hinst)
1995 if (w32_unicode_gui)
1997 WNDCLASSW uwc;
1998 INIT_WINDOW_CLASS(uwc);
1999 uwc.lpszClassName = L"Emacs";
2001 return RegisterClassW (&uwc);
2003 else
2005 WNDCLASS wc;
2006 INIT_WINDOW_CLASS(wc);
2007 wc.lpszClassName = EMACS_CLASS;
2009 return RegisterClassA (&wc);
2013 static HWND
2014 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
2016 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
2017 /* Position and size of scroll bar. */
2018 bar->left, bar->top, bar->width, bar->height,
2019 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2022 static HWND
2023 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
2025 return CreateWindow ("SCROLLBAR", "", SBS_HORZ | WS_CHILD | WS_VISIBLE,
2026 /* Position and size of scroll bar. */
2027 bar->left, bar->top, bar->width, bar->height,
2028 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
2031 static void
2032 w32_createwindow (struct frame *f, int *coords)
2034 HWND hwnd;
2035 RECT rect;
2036 int top;
2037 int left;
2039 rect.left = rect.top = 0;
2040 rect.right = FRAME_PIXEL_WIDTH (f);
2041 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2043 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2044 FRAME_EXTERNAL_MENU_BAR (f));
2046 /* Do first time app init */
2048 w32_init_class (hinst);
2050 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2052 left = f->left_pos;
2053 top = f->top_pos;
2055 else
2057 left = coords[0];
2058 top = coords[1];
2061 FRAME_W32_WINDOW (f) = hwnd
2062 = CreateWindow (EMACS_CLASS,
2063 f->namebuf,
2064 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2065 left, top,
2066 rect.right - rect.left, rect.bottom - rect.top,
2067 NULL,
2068 NULL,
2069 hinst,
2070 NULL);
2072 if (hwnd)
2074 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2075 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2076 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2077 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2078 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2079 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2081 /* Enable drag-n-drop. */
2082 DragAcceptFiles (hwnd, TRUE);
2084 /* Do this to discard the default setting specified by our parent. */
2085 ShowWindow (hwnd, SW_HIDE);
2087 /* Update frame positions. */
2088 GetWindowRect (hwnd, &rect);
2089 f->left_pos = rect.left;
2090 f->top_pos = rect.top;
2094 static void
2095 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2097 wmsg->msg.hwnd = hwnd;
2098 wmsg->msg.message = msg;
2099 wmsg->msg.wParam = wParam;
2100 wmsg->msg.lParam = lParam;
2101 wmsg->msg.time = GetMessageTime ();
2103 post_msg (wmsg);
2106 #ifdef WINDOWSNT
2107 /* The Windows keyboard hook callback. */
2108 static LRESULT CALLBACK
2109 funhook (int code, WPARAM w, LPARAM l)
2111 INPUT inputs[2];
2112 HWND focus = GetFocus ();
2113 int console = 0;
2114 KBDLLHOOKSTRUCT const *hs = (KBDLLHOOKSTRUCT*)l;
2116 if (code < 0 || (hs->flags & LLKHF_INJECTED))
2117 return CallNextHookEx (0, code, w, l);
2119 /* The keyboard hook sees keyboard input on all processes (except
2120 elevated ones, when Emacs itself is not elevated). As such,
2121 care must be taken to only filter out keyboard input when Emacs
2122 itself is on the foreground.
2124 GetFocus returns a non-NULL window if another application is active,
2125 and always for a console Emacs process. For a console Emacs, determine
2126 focus by checking if the current foreground window is the process's
2127 console window. */
2128 if (focus == NULL && kbdhook.console != NULL)
2130 if (GetForegroundWindow () == kbdhook.console)
2132 focus = kbdhook.console;
2133 console = 1;
2137 /* First, check hooks for the left and right Windows keys. */
2138 if (hs->vkCode == VK_LWIN || hs->vkCode == VK_RWIN)
2140 if (focus != NULL && (w == WM_KEYDOWN || w == WM_SYSKEYDOWN))
2142 /* The key is being pressed in an Emacs window. */
2143 if (hs->vkCode == VK_LWIN && !kbdhook.lwindown)
2145 kbdhook.lwindown = 1;
2146 kbdhook.winseen = 1;
2147 kbdhook.winsdown++;
2149 else if (hs->vkCode == VK_RWIN && !kbdhook.rwindown)
2151 kbdhook.rwindown = 1;
2152 kbdhook.winseen = 1;
2153 kbdhook.winsdown++;
2155 /* Returning 1 here drops the keypress without further processing.
2156 If the keypress was allowed to go through, the normal Windows
2157 hotkeys would take over. */
2158 return 1;
2160 else if (kbdhook.winsdown > 0 && (w == WM_KEYUP || w == WM_SYSKEYUP))
2162 /* A key that has been captured earlier is being released now. */
2163 if (hs->vkCode == VK_LWIN && kbdhook.lwindown)
2165 kbdhook.lwindown = 0;
2166 kbdhook.winsdown--;
2168 else if (hs->vkCode == VK_RWIN && kbdhook.rwindown)
2170 kbdhook.rwindown = 0;
2171 kbdhook.winsdown--;
2173 if (kbdhook.winsdown == 0 && kbdhook.winseen)
2175 if (!kbdhook.suppress_lone)
2177 /* The Windows key was pressed, then released,
2178 without any other key pressed simultaneously.
2179 Normally, this opens the Start menu, but the user
2180 can prevent this by setting the
2181 w32-pass-[lr]window-to-system variable to
2182 NIL. */
2183 if ((hs->vkCode == VK_LWIN && !NILP (Vw32_pass_lwindow_to_system)) ||
2184 (hs->vkCode == VK_RWIN && !NILP (Vw32_pass_rwindow_to_system)))
2186 /* Not prevented - Simulate the keypress to the system. */
2187 memset (inputs, 0, sizeof (inputs));
2188 inputs[0].type = INPUT_KEYBOARD;
2189 inputs[0].ki.wVk = hs->vkCode;
2190 inputs[0].ki.wScan = hs->vkCode;
2191 inputs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
2192 inputs[0].ki.time = 0;
2193 inputs[1].type = INPUT_KEYBOARD;
2194 inputs[1].ki.wVk = hs->vkCode;
2195 inputs[1].ki.wScan = hs->vkCode;
2196 inputs[1].ki.dwFlags
2197 = KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP;
2198 inputs[1].ki.time = 0;
2199 SendInput (2, inputs, sizeof (INPUT));
2201 else if (focus != NULL)
2203 /* When not passed to system, must simulate privately to Emacs. */
2204 PostMessage (focus, WM_SYSKEYDOWN, hs->vkCode, 0);
2205 PostMessage (focus, WM_SYSKEYUP, hs->vkCode, 0);
2209 if (kbdhook.winsdown == 0)
2211 /* No Windows keys pressed anymore - clear the state flags. */
2212 kbdhook.suppress_lone = 0;
2213 kbdhook.winseen = 0;
2215 if (!kbdhook.send_win_up)
2217 /* Swallow this release message, as not to confuse
2218 applications who did not get to see the original
2219 WM_KEYDOWN message either. */
2220 return 1;
2222 kbdhook.send_win_up = 0;
2225 else if (kbdhook.winsdown > 0)
2227 /* Some other key was pressed while a captured Win key is down.
2228 This is either an Emacs registered hotkey combination, or a
2229 system hotkey. */
2230 if ((kbdhook.lwindown && kbdhook.lwin_hooked[hs->vkCode]) ||
2231 (kbdhook.rwindown && kbdhook.rwin_hooked[hs->vkCode]))
2233 /* Hooked Win-x combination, do not pass the keypress to Windows. */
2234 kbdhook.suppress_lone = 1;
2236 else if (!kbdhook.suppress_lone)
2238 /* Unhooked S-x combination; simulate the combination now
2239 (will be seen by the system). */
2240 memset (inputs, 0, sizeof (inputs));
2241 inputs[0].type = INPUT_KEYBOARD;
2242 inputs[0].ki.wVk = kbdhook.lwindown ? VK_LWIN : VK_RWIN;
2243 inputs[0].ki.wScan = kbdhook.lwindown ? VK_LWIN : VK_RWIN;
2244 inputs[0].ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
2245 inputs[0].ki.time = 0;
2246 inputs[1].type = INPUT_KEYBOARD;
2247 inputs[1].ki.wVk = hs->vkCode;
2248 inputs[1].ki.wScan = hs->scanCode;
2249 inputs[1].ki.dwFlags =
2250 (hs->flags & LLKHF_EXTENDED) ? KEYEVENTF_EXTENDEDKEY : 0;
2251 inputs[1].ki.time = 0;
2252 SendInput (2, inputs, sizeof (INPUT));
2253 /* Stop processing of this Win sequence here; the
2254 corresponding keyup messages will come through the normal
2255 channel when the keys are released. */
2256 kbdhook.suppress_lone = 1;
2257 kbdhook.send_win_up = 1;
2258 /* Swallow the original keypress (as we want the Win key
2259 down message simulated above to precede this real message). */
2260 return 1;
2264 /* Next, handle the registered Alt-* combinations. */
2265 if ((w == WM_SYSKEYDOWN || w == WM_KEYDOWN)
2266 && kbdhook.alt_hooked[hs->vkCode]
2267 && focus != NULL
2268 && (GetAsyncKeyState (VK_MENU) & 0x8000))
2270 /* Prevent the system from getting this Alt-* key - suppress the
2271 message and post as a normal keypress to Emacs. */
2272 if (console)
2274 INPUT_RECORD rec;
2275 DWORD n;
2276 rec.EventType = KEY_EVENT;
2277 rec.Event.KeyEvent.bKeyDown = TRUE;
2278 rec.Event.KeyEvent.wVirtualKeyCode = hs->vkCode;
2279 rec.Event.KeyEvent.wVirtualScanCode = hs->scanCode;
2280 rec.Event.KeyEvent.uChar.UnicodeChar = 0;
2281 rec.Event.KeyEvent.dwControlKeyState =
2282 ((GetAsyncKeyState (VK_LMENU) & 0x8000) ? LEFT_ALT_PRESSED : 0)
2283 | ((GetAsyncKeyState (VK_RMENU) & 0x8000) ? RIGHT_ALT_PRESSED : 0)
2284 | ((GetAsyncKeyState (VK_LCONTROL) & 0x8000) ? LEFT_CTRL_PRESSED : 0)
2285 | ((GetAsyncKeyState (VK_RCONTROL) & 0x8000) ? RIGHT_CTRL_PRESSED : 0)
2286 | ((GetAsyncKeyState (VK_SHIFT) & 0x8000) ? SHIFT_PRESSED : 0)
2287 | ((hs->flags & LLKHF_EXTENDED) ? ENHANCED_KEY : 0);
2288 if (w32_console_unicode_input)
2289 WriteConsoleInputW (keyboard_handle, &rec, 1, &n);
2290 else
2291 WriteConsoleInputA (keyboard_handle, &rec, 1, &n);
2293 else
2294 PostMessage (focus, w, hs->vkCode, 1 | (1<<29));
2295 return 1;
2298 /* The normal case - pass the message through. */
2299 return CallNextHookEx (0, code, w, l);
2302 /* Set up the hook; can be called several times, with matching
2303 remove_w32_kbdhook calls. */
2304 void
2305 setup_w32_kbdhook (void)
2307 kbdhook.hook_count++;
2309 /* This hook gets in the way of debugging, since when Emacs stops,
2310 its input thread stops, and there's nothing to process keyboard
2311 events, whereas this hook is global, and is invoked in the
2312 context of the thread that installed it. So we don't install the
2313 hook if the process is being debugged. */
2314 if (w32_kbdhook_active)
2316 IsDebuggerPresent_Proc is_debugger_present = (IsDebuggerPresent_Proc)
2317 GetProcAddress (GetModuleHandle ("kernel32.dll"), "IsDebuggerPresent");
2318 if (is_debugger_present && is_debugger_present ())
2319 return;
2322 /* Hooking is only available on NT architecture systems, as
2323 indicated by the w32_kbdhook_active variable. */
2324 if (kbdhook.hook_count == 1 && w32_kbdhook_active)
2326 /* Get the handle of the Emacs console window. As the
2327 GetConsoleWindow function is only available on Win2000+, a
2328 hackish workaround described in Microsoft KB article 124103
2329 (https://support.microsoft.com/en-us/kb/124103) is used for
2330 NT 4 systems. */
2331 GetConsoleWindow_Proc get_console = (GetConsoleWindow_Proc)
2332 GetProcAddress (GetModuleHandle ("kernel32.dll"), "GetConsoleWindow");
2334 if (get_console != NULL)
2335 kbdhook.console = get_console ();
2336 else
2338 GUID guid;
2339 wchar_t *oldTitle = malloc (1024 * sizeof(wchar_t));
2340 wchar_t newTitle[64];
2341 int i;
2343 CoCreateGuid (&guid);
2344 StringFromGUID2 (&guid, newTitle, 64);
2345 if (newTitle != NULL)
2347 GetConsoleTitleW (oldTitle, 1024);
2348 SetConsoleTitleW (newTitle);
2349 for (i = 0; i < 25; i++)
2351 Sleep (40);
2352 kbdhook.console = FindWindowW (NULL, newTitle);
2353 if (kbdhook.console != NULL)
2354 break;
2356 SetConsoleTitleW (oldTitle);
2358 free (oldTitle);
2361 /* Set the hook. */
2362 kbdhook.hook = SetWindowsHookEx (WH_KEYBOARD_LL, funhook,
2363 GetModuleHandle (NULL), 0);
2367 /* Remove the hook. */
2368 void
2369 remove_w32_kbdhook (void)
2371 kbdhook.hook_count--;
2372 if (kbdhook.hook_count == 0 && w32_kbdhook_active)
2374 UnhookWindowsHookEx (kbdhook.hook);
2375 kbdhook.hook = NULL;
2378 #endif /* WINDOWSNT */
2380 /* Mark a specific key combination as hooked, preventing it to be
2381 handled by the system. */
2382 static void
2383 hook_w32_key (int hook, int modifier, int vkey)
2385 char *tbl = NULL;
2387 switch (modifier)
2389 case VK_MENU:
2390 tbl = kbdhook.alt_hooked;
2391 break;
2392 case VK_LWIN:
2393 tbl = kbdhook.lwin_hooked;
2394 break;
2395 case VK_RWIN:
2396 tbl = kbdhook.rwin_hooked;
2397 break;
2400 if (tbl != NULL && vkey >= 0 && vkey <= 255)
2402 /* VK_ANY hooks all keys for this modifier */
2403 if (vkey == VK_ANY)
2404 memset (tbl, (char)hook, 256);
2405 else
2406 tbl[vkey] = (char)hook;
2407 /* Alt-<modifier>s should go through */
2408 kbdhook.alt_hooked[VK_MENU] = 0;
2409 kbdhook.alt_hooked[VK_LMENU] = 0;
2410 kbdhook.alt_hooked[VK_RMENU] = 0;
2411 kbdhook.alt_hooked[VK_CONTROL] = 0;
2412 kbdhook.alt_hooked[VK_LCONTROL] = 0;
2413 kbdhook.alt_hooked[VK_RCONTROL] = 0;
2414 kbdhook.alt_hooked[VK_SHIFT] = 0;
2415 kbdhook.alt_hooked[VK_LSHIFT] = 0;
2416 kbdhook.alt_hooked[VK_RSHIFT] = 0;
2420 #ifdef WINDOWSNT
2421 /* Check the current Win key pressed state. */
2423 check_w32_winkey_state (int vkey)
2425 /* The hook code handles grabbing of the Windows keys and Alt-* key
2426 combinations reserved by the system. Handling Alt is a bit
2427 easier, as Windows intends Alt-* shortcuts for application use in
2428 Windows; hotkeys such as Alt-tab and Alt-escape are special
2429 cases. Win-* hotkeys, on the other hand, are primarily meant for
2430 system use.
2432 As a result, when we want Emacs to be able to grab the Win-*
2433 keys, we must swallow all Win key presses in a low-level keyboard
2434 hook. Unfortunately, this means that the Emacs window procedure
2435 (and console input handler) never see the keypresses either.
2436 Thus, to check the modifier states properly, Emacs code must use
2437 the check_w32_winkey_state function that uses the flags directly
2438 updated by the hook callback. */
2439 switch (vkey)
2441 case VK_LWIN:
2442 return kbdhook.lwindown;
2443 case VK_RWIN:
2444 return kbdhook.rwindown;
2446 return 0;
2448 #endif /* WINDOWSNT */
2450 /* Reset the keyboard hook state. Locking the workstation with Win-L
2451 leaves the Win key(s) "down" from the hook's point of view - the
2452 keyup event is never seen. Thus, this function must be called when
2453 the system is locked. */
2454 static void
2455 reset_w32_kbdhook_state (void)
2457 kbdhook.lwindown = 0;
2458 kbdhook.rwindown = 0;
2459 kbdhook.winsdown = 0;
2460 kbdhook.send_win_up = 0;
2461 kbdhook.suppress_lone = 0;
2462 kbdhook.winseen = 0;
2465 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2466 between left and right keys as advertised. We test for this
2467 support dynamically, and set a flag when the support is absent. If
2468 absent, we keep track of the left and right control and alt keys
2469 ourselves. This is particularly necessary on keyboards that rely
2470 upon the AltGr key, which is represented as having the left control
2471 and right alt keys pressed. For these keyboards, we need to know
2472 when the left alt key has been pressed in addition to the AltGr key
2473 so that we can properly support M-AltGr-key sequences (such as M-@
2474 on Swedish keyboards). */
2476 #define EMACS_LCONTROL 0
2477 #define EMACS_RCONTROL 1
2478 #define EMACS_LMENU 2
2479 #define EMACS_RMENU 3
2481 static int modifiers[4];
2482 static int modifiers_recorded;
2483 static int modifier_key_support_tested;
2485 static void
2486 test_modifier_support (unsigned int wparam)
2488 unsigned int l, r;
2490 if (wparam != VK_CONTROL && wparam != VK_MENU)
2491 return;
2492 if (wparam == VK_CONTROL)
2494 l = VK_LCONTROL;
2495 r = VK_RCONTROL;
2497 else
2499 l = VK_LMENU;
2500 r = VK_RMENU;
2502 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2503 modifiers_recorded = 1;
2504 else
2505 modifiers_recorded = 0;
2506 modifier_key_support_tested = 1;
2509 static void
2510 record_keydown (unsigned int wparam, unsigned int lparam)
2512 int i;
2514 if (!modifier_key_support_tested)
2515 test_modifier_support (wparam);
2517 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2518 return;
2520 if (wparam == VK_CONTROL)
2521 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2522 else
2523 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2525 modifiers[i] = 1;
2528 static void
2529 record_keyup (unsigned int wparam, unsigned int lparam)
2531 int i;
2533 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2534 return;
2536 if (wparam == VK_CONTROL)
2537 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2538 else
2539 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2541 modifiers[i] = 0;
2544 /* Emacs can lose focus while a modifier key has been pressed. When
2545 it regains focus, be conservative and clear all modifiers since
2546 we cannot reconstruct the left and right modifier state. */
2547 static void
2548 reset_modifiers (void)
2550 SHORT ctrl, alt;
2552 if (GetFocus () == NULL)
2553 /* Emacs doesn't have keyboard focus. Do nothing. */
2554 return;
2556 ctrl = GetAsyncKeyState (VK_CONTROL);
2557 alt = GetAsyncKeyState (VK_MENU);
2559 if (!(ctrl & 0x08000))
2560 /* Clear any recorded control modifier state. */
2561 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2563 if (!(alt & 0x08000))
2564 /* Clear any recorded alt modifier state. */
2565 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2567 /* Update the state of all modifier keys, because modifiers used in
2568 hot-key combinations can get stuck on if Emacs loses focus as a
2569 result of a hot-key being pressed. */
2571 BYTE keystate[256];
2573 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2575 memset (keystate, 0, sizeof (keystate));
2576 GetKeyboardState (keystate);
2577 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2578 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2579 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2580 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2581 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2582 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2583 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2584 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2585 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2586 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2587 SetKeyboardState (keystate);
2591 /* Synchronize modifier state with what is reported with the current
2592 keystroke. Even if we cannot distinguish between left and right
2593 modifier keys, we know that, if no modifiers are set, then neither
2594 the left or right modifier should be set. */
2595 static void
2596 sync_modifiers (void)
2598 if (!modifiers_recorded)
2599 return;
2601 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2602 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2604 if (!(GetKeyState (VK_MENU) & 0x8000))
2605 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2608 static int
2609 modifier_set (int vkey)
2611 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2612 toggle keys is not an omission! If you want to add it, you will
2613 have to make changes in the default sub-case of the WM_KEYDOWN
2614 switch, because if the NUMLOCK modifier is set, the code there
2615 will directly convert any key that looks like an ASCII letter,
2616 and also downcase those that look like upper-case ASCII. */
2617 if (vkey == VK_CAPITAL)
2619 if (NILP (Vw32_enable_caps_lock))
2620 return 0;
2621 else
2622 return (GetKeyState (vkey) & 0x1);
2624 if (vkey == VK_SCROLL)
2626 if (NILP (Vw32_scroll_lock_modifier)
2627 /* w32-scroll-lock-modifier can be any non-nil value that is
2628 not one of the modifiers, in which case it shall be ignored. */
2629 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2630 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2631 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2632 || EQ (Vw32_scroll_lock_modifier, Qalt)
2633 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2634 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2635 return 0;
2636 else
2637 return (GetKeyState (vkey) & 0x1);
2639 #ifdef WINDOWSNT
2640 if (w32_kbdhook_active && (vkey == VK_LWIN || vkey == VK_RWIN))
2641 return check_w32_winkey_state (vkey);
2642 #endif
2644 if (!modifiers_recorded)
2645 return (GetKeyState (vkey) & 0x8000);
2647 switch (vkey)
2649 case VK_LCONTROL:
2650 return modifiers[EMACS_LCONTROL];
2651 case VK_RCONTROL:
2652 return modifiers[EMACS_RCONTROL];
2653 case VK_LMENU:
2654 return modifiers[EMACS_LMENU];
2655 case VK_RMENU:
2656 return modifiers[EMACS_RMENU];
2658 return (GetKeyState (vkey) & 0x8000);
2661 /* Convert between the modifier bits W32 uses and the modifier bits
2662 Emacs uses. */
2663 unsigned int w32_key_to_modifier (int);
2665 unsigned int
2666 w32_key_to_modifier (int key)
2668 Lisp_Object key_mapping;
2670 switch (key)
2672 case VK_LWIN:
2673 key_mapping = Vw32_lwindow_modifier;
2674 break;
2675 case VK_RWIN:
2676 key_mapping = Vw32_rwindow_modifier;
2677 break;
2678 case VK_APPS:
2679 key_mapping = Vw32_apps_modifier;
2680 break;
2681 case VK_SCROLL:
2682 key_mapping = Vw32_scroll_lock_modifier;
2683 break;
2684 default:
2685 key_mapping = Qnil;
2688 /* NB. This code runs in the input thread, asynchronously to the lisp
2689 thread, so we must be careful to ensure access to lisp data is
2690 thread-safe. The following code is safe because the modifier
2691 variable values are updated atomically from lisp and symbols are
2692 not relocated by GC. Also, we don't have to worry about seeing GC
2693 markbits here. */
2694 if (EQ (key_mapping, Qhyper))
2695 return hyper_modifier;
2696 if (EQ (key_mapping, Qsuper))
2697 return super_modifier;
2698 if (EQ (key_mapping, Qmeta))
2699 return meta_modifier;
2700 if (EQ (key_mapping, Qalt))
2701 return alt_modifier;
2702 if (EQ (key_mapping, Qctrl))
2703 return ctrl_modifier;
2704 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2705 return ctrl_modifier;
2706 if (EQ (key_mapping, Qshift))
2707 return shift_modifier;
2709 /* Don't generate any modifier if not explicitly requested. */
2710 return 0;
2713 static unsigned int
2714 w32_get_modifiers (void)
2716 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2717 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2718 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2719 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2720 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2721 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2722 (modifier_set (VK_MENU) ?
2723 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2726 /* We map the VK_* modifiers into console modifier constants
2727 so that we can use the same routines to handle both console
2728 and window input. */
2730 static int
2731 construct_console_modifiers (void)
2733 int mods;
2735 mods = 0;
2736 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2737 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2738 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2739 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2740 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2741 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2742 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2743 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2744 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2745 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2746 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2748 return mods;
2751 static int
2752 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2754 int mods;
2756 /* Convert to emacs modifiers. */
2757 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2759 return mods;
2762 unsigned int map_keypad_keys (unsigned int, unsigned int);
2764 unsigned int
2765 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2767 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2768 return virt_key;
2770 if (virt_key == VK_RETURN)
2771 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2773 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2774 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2776 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2777 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2779 if (virt_key == VK_CLEAR)
2780 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2782 return virt_key;
2785 /* List of special key combinations which w32 would normally capture,
2786 but Emacs should grab instead. Not directly visible to lisp, to
2787 simplify synchronization. Each item is an integer encoding a virtual
2788 key code and modifier combination to capture.
2789 Note: This code is not used if keyboard hooks are active
2790 (Windows 2000 and later). */
2791 static Lisp_Object w32_grabbed_keys;
2793 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2794 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2795 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2796 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2798 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2799 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2800 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2802 /* Register hot-keys for reserved key combinations when Emacs has
2803 keyboard focus, since this is the only way Emacs can receive key
2804 combinations like Alt-Tab which are used by the system. */
2806 static void
2807 register_hot_keys (HWND hwnd)
2809 Lisp_Object keylist;
2811 /* Use CONSP, since we are called asynchronously. */
2812 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2814 Lisp_Object key = XCAR (keylist);
2816 /* Deleted entries get set to nil. */
2817 if (!INTEGERP (key))
2818 continue;
2820 RegisterHotKey (hwnd, HOTKEY_ID (key),
2821 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2825 static void
2826 unregister_hot_keys (HWND hwnd)
2828 Lisp_Object keylist;
2830 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2832 Lisp_Object key = XCAR (keylist);
2834 if (!INTEGERP (key))
2835 continue;
2837 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2841 #if EMACSDEBUG
2842 const char*
2843 w32_name_of_message (UINT msg)
2845 unsigned i;
2846 static char buf[64];
2847 static const struct {
2848 UINT msg;
2849 const char* name;
2850 } msgnames[] = {
2851 #define M(msg) { msg, # msg }
2852 M (WM_PAINT),
2853 M (WM_TIMER),
2854 M (WM_USER),
2855 M (WM_MOUSEMOVE),
2856 M (WM_LBUTTONUP),
2857 M (WM_KEYDOWN),
2858 M (WM_EMACS_KILL),
2859 M (WM_EMACS_CREATEWINDOW),
2860 M (WM_EMACS_DONE),
2861 M (WM_EMACS_CREATEVSCROLLBAR),
2862 M (WM_EMACS_CREATEHSCROLLBAR),
2863 M (WM_EMACS_SHOWWINDOW),
2864 M (WM_EMACS_SETWINDOWPOS),
2865 M (WM_EMACS_DESTROYWINDOW),
2866 M (WM_EMACS_TRACKPOPUPMENU),
2867 M (WM_EMACS_SETFOCUS),
2868 M (WM_EMACS_SETFOREGROUND),
2869 M (WM_EMACS_SETLOCALE),
2870 M (WM_EMACS_SETKEYBOARDLAYOUT),
2871 M (WM_EMACS_REGISTER_HOT_KEY),
2872 M (WM_EMACS_UNREGISTER_HOT_KEY),
2873 M (WM_EMACS_TOGGLE_LOCK_KEY),
2874 M (WM_EMACS_TRACK_CARET),
2875 M (WM_EMACS_DESTROY_CARET),
2876 M (WM_EMACS_SHOW_CARET),
2877 M (WM_EMACS_HIDE_CARET),
2878 M (WM_EMACS_SETCURSOR),
2879 M (WM_EMACS_SHOWCURSOR),
2880 M (WM_EMACS_PAINT),
2881 M (WM_CHAR),
2882 #undef M
2883 { 0, 0 }
2886 for (i = 0; msgnames[i].name; ++i)
2887 if (msgnames[i].msg == msg)
2888 return msgnames[i].name;
2890 sprintf (buf, "message 0x%04x", (unsigned)msg);
2891 return buf;
2893 #endif /* EMACSDEBUG */
2895 /* Here's an overview of how Emacs input works in GUI sessions on
2896 MS-Windows. (For description of non-GUI input, see the commentary
2897 before w32_console_read_socket in w32inevt.c.)
2899 System messages are read and processed by w32_msg_pump below. This
2900 function runs in a separate thread. It handles a small number of
2901 custom WM_EMACS_* messages (posted by the main thread, look for
2902 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2903 is the main window procedure for the entire Emacs application.
2905 w32_wnd_proc also runs in the same separate input thread. It
2906 handles some messages, mostly those that need GDI calls, by itself.
2907 For the others, it calls my_post_msg, which inserts the messages
2908 into the input queue serviced by w32_read_socket.
2910 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2911 called synchronously from keyboard.c when it is known or suspected
2912 that some input is available. w32_read_socket either handles
2913 messages immediately, or converts them into Emacs input events and
2914 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2915 them and process them when read_char and its callers require
2916 input.
2918 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2919 select(2) takes the place of w32_read_socket.
2923 /* Main message dispatch loop. */
2925 static void
2926 w32_msg_pump (deferred_msg * msg_buf)
2928 MSG msg;
2929 WPARAM result;
2930 HWND focus_window;
2932 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2934 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2937 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2938 /* w32_name_of_message (msg.message), msg.time)); */
2940 if (msg.hwnd == NULL)
2942 switch (msg.message)
2944 case WM_NULL:
2945 /* Produced by complete_deferred_msg; just ignore. */
2946 break;
2947 case WM_EMACS_CREATEWINDOW:
2948 /* Initialize COM for this window. Even though we don't use it,
2949 some third party shell extensions can cause it to be used in
2950 system dialogs, which causes a crash if it is not initialized.
2951 This is a known bug in Windows, which was fixed long ago, but
2952 the patch for XP is not publicly available until XP SP3,
2953 and older versions will never be patched. */
2954 CoInitialize (NULL);
2955 w32_createwindow ((struct frame *) msg.wParam,
2956 (int *) msg.lParam);
2957 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2958 emacs_abort ();
2959 break;
2960 case WM_EMACS_SETLOCALE:
2961 SetThreadLocale (msg.wParam);
2962 /* Reply is not expected. */
2963 break;
2964 case WM_EMACS_SETKEYBOARDLAYOUT:
2965 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2966 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2967 result, 0))
2968 emacs_abort ();
2969 break;
2970 case WM_EMACS_REGISTER_HOT_KEY:
2971 focus_window = GetFocus ();
2972 if (focus_window != NULL)
2973 RegisterHotKey (focus_window,
2974 RAW_HOTKEY_ID (msg.wParam),
2975 RAW_HOTKEY_MODIFIERS (msg.wParam),
2976 RAW_HOTKEY_VK_CODE (msg.wParam));
2977 /* Reply is not expected. */
2978 break;
2979 case WM_EMACS_UNREGISTER_HOT_KEY:
2980 focus_window = GetFocus ();
2981 if (focus_window != NULL)
2982 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2983 /* Mark item as erased. NB: this code must be
2984 thread-safe. The next line is okay because the cons
2985 cell is never made into garbage and is not relocated by
2986 GC. */
2987 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
2988 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2989 emacs_abort ();
2990 break;
2991 case WM_EMACS_TOGGLE_LOCK_KEY:
2993 int vk_code = (int) msg.wParam;
2994 int cur_state = (GetKeyState (vk_code) & 1);
2995 int new_state = msg.lParam;
2997 if (new_state == -1
2998 || ((new_state & 1) != cur_state))
3000 one_w32_display_info.faked_key = vk_code;
3002 keybd_event ((BYTE) vk_code,
3003 (BYTE) MapVirtualKey (vk_code, 0),
3004 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3005 keybd_event ((BYTE) vk_code,
3006 (BYTE) MapVirtualKey (vk_code, 0),
3007 KEYEVENTF_EXTENDEDKEY | 0, 0);
3008 keybd_event ((BYTE) vk_code,
3009 (BYTE) MapVirtualKey (vk_code, 0),
3010 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3011 cur_state = !cur_state;
3013 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
3014 cur_state, 0))
3015 emacs_abort ();
3017 break;
3018 #ifdef MSG_DEBUG
3019 /* Broadcast messages make it here, so you need to be looking
3020 for something in particular for this to be useful. */
3021 default:
3022 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
3023 #endif
3026 else
3028 if (w32_unicode_gui)
3029 DispatchMessageW (&msg);
3030 else
3031 DispatchMessageA (&msg);
3034 /* Exit nested loop when our deferred message has completed. */
3035 if (msg_buf->completed)
3036 break;
3040 deferred_msg * deferred_msg_head;
3042 static deferred_msg *
3043 find_deferred_msg (HWND hwnd, UINT msg)
3045 deferred_msg * item;
3047 /* Don't actually need synchronization for read access, since
3048 modification of single pointer is always atomic. */
3049 /* enter_crit (); */
3051 for (item = deferred_msg_head; item != NULL; item = item->next)
3052 if (item->w32msg.msg.hwnd == hwnd
3053 && item->w32msg.msg.message == msg)
3054 break;
3056 /* leave_crit (); */
3058 return item;
3061 static LRESULT
3062 send_deferred_msg (deferred_msg * msg_buf,
3063 HWND hwnd,
3064 UINT msg,
3065 WPARAM wParam,
3066 LPARAM lParam)
3068 /* Only input thread can send deferred messages. */
3069 if (GetCurrentThreadId () != dwWindowsThreadId)
3070 emacs_abort ();
3072 /* It is an error to send a message that is already deferred. */
3073 if (find_deferred_msg (hwnd, msg) != NULL)
3074 emacs_abort ();
3076 /* Enforced synchronization is not needed because this is the only
3077 function that alters deferred_msg_head, and the following critical
3078 section is guaranteed to only be serially reentered (since only the
3079 input thread can call us). */
3081 /* enter_crit (); */
3083 msg_buf->completed = 0;
3084 msg_buf->next = deferred_msg_head;
3085 deferred_msg_head = msg_buf;
3086 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
3088 /* leave_crit (); */
3090 /* Start a new nested message loop to process other messages until
3091 this one is completed. */
3092 w32_msg_pump (msg_buf);
3094 deferred_msg_head = msg_buf->next;
3096 return msg_buf->result;
3099 void
3100 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
3102 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
3104 if (msg_buf == NULL)
3105 /* Message may have been canceled, so don't abort. */
3106 return;
3108 msg_buf->result = result;
3109 msg_buf->completed = 1;
3111 /* Ensure input thread is woken so it notices the completion. */
3112 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3115 static void
3116 cancel_all_deferred_msgs (void)
3118 deferred_msg * item;
3120 /* Don't actually need synchronization for read access, since
3121 modification of single pointer is always atomic. */
3122 /* enter_crit (); */
3124 for (item = deferred_msg_head; item != NULL; item = item->next)
3126 item->result = 0;
3127 item->completed = 1;
3130 /* leave_crit (); */
3132 /* Ensure input thread is woken so it notices the completion. */
3133 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
3136 DWORD WINAPI w32_msg_worker (void *);
3138 DWORD WINAPI
3139 w32_msg_worker (void *arg)
3141 MSG msg;
3142 deferred_msg dummy_buf;
3144 /* Ensure our message queue is created */
3146 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
3148 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
3149 emacs_abort ();
3151 memset (&dummy_buf, 0, sizeof (dummy_buf));
3152 dummy_buf.w32msg.msg.hwnd = NULL;
3153 dummy_buf.w32msg.msg.message = WM_NULL;
3155 /* This is the initial message loop which should only exit when the
3156 application quits. */
3157 w32_msg_pump (&dummy_buf);
3159 return 0;
3162 static void
3163 signal_user_input (void)
3165 /* Interrupt any lisp that wants to be interrupted by input. */
3166 if (!NILP (Vthrow_on_input))
3168 Vquit_flag = Vthrow_on_input;
3169 /* Calling maybe_quit from this thread is a bad idea, since this
3170 unwinds the stack of the Lisp thread, and the Windows runtime
3171 rightfully barfs. */
3176 static void
3177 post_character_message (HWND hwnd, UINT msg,
3178 WPARAM wParam, LPARAM lParam,
3179 DWORD modifiers)
3181 W32Msg wmsg;
3183 wmsg.dwModifiers = modifiers;
3185 /* Detect quit_char and set quit-flag directly. Note that we
3186 still need to post a message to ensure the main thread will be
3187 woken up if blocked in sys_select, but we do NOT want to post
3188 the quit_char message itself (because it will usually be as if
3189 the user had typed quit_char twice). Instead, we post a dummy
3190 message that has no particular effect. */
3192 int c = wParam;
3193 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
3194 c = make_ctrl_char (c) & 0377;
3195 if (c == quit_char
3196 || (wmsg.dwModifiers == 0
3197 && w32_quit_key && wParam == w32_quit_key))
3199 Vquit_flag = Qt;
3201 /* The choice of message is somewhat arbitrary, as long as
3202 the main thread handler just ignores it. */
3203 msg = WM_NULL;
3205 /* Interrupt any blocking system calls. */
3206 signal_quit ();
3208 /* As a safety precaution, forcibly complete any deferred
3209 messages. This is a kludge, but I don't see any particularly
3210 clean way to handle the situation where a deferred message is
3211 "dropped" in the lisp thread, and will thus never be
3212 completed, eg. by the user trying to activate the menubar
3213 when the lisp thread is busy, and then typing C-g when the
3214 menubar doesn't open promptly (with the result that the
3215 menubar never responds at all because the deferred
3216 WM_INITMENU message is never completed). Another problem
3217 situation is when the lisp thread calls SendMessage (to send
3218 a window manager command) when a message has been deferred;
3219 the lisp thread gets blocked indefinitely waiting for the
3220 deferred message to be completed, which itself is waiting for
3221 the lisp thread to respond.
3223 Note that we don't want to block the input thread waiting for
3224 a response from the lisp thread (although that would at least
3225 solve the deadlock problem above), because we want to be able
3226 to receive C-g to interrupt the lisp thread. */
3227 cancel_all_deferred_msgs ();
3229 else
3230 signal_user_input ();
3233 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3236 static int
3237 get_wm_chars (HWND aWnd, int *buf, int buflen, int ignore_ctrl, int ctrl,
3238 int *ctrl_cnt, int *is_dead, int vk, int exp)
3240 MSG msg;
3241 /* If doubled is at the end, ignore it. */
3242 int i = buflen, doubled = 0, code_unit;
3244 if (ctrl_cnt)
3245 *ctrl_cnt = 0;
3246 if (is_dead)
3247 *is_dead = -1;
3248 eassert (w32_unicode_gui);
3249 while (buflen
3250 /* Should be called only when w32_unicode_gui: */
3251 && PeekMessageW (&msg, aWnd, WM_KEYFIRST, WM_KEYLAST,
3252 PM_NOREMOVE | PM_NOYIELD)
3253 && (msg.message == WM_CHAR || msg.message == WM_SYSCHAR
3254 || msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR
3255 || msg.message == WM_UNICHAR))
3257 /* We extract character payload, but in this call we handle only the
3258 characters which come BEFORE the next keyup/keydown message. */
3259 int dead;
3261 GetMessageW (&msg, aWnd, msg.message, msg.message);
3262 dead = (msg.message == WM_DEADCHAR || msg.message == WM_SYSDEADCHAR);
3263 if (is_dead)
3264 *is_dead = (dead ? msg.wParam : -1);
3265 if (dead)
3266 continue;
3267 code_unit = msg.wParam;
3268 if (doubled)
3270 /* Had surrogate. */
3271 if (msg.message == WM_UNICHAR
3272 || code_unit < 0xDC00 || code_unit > 0xDFFF)
3273 { /* Mismatched first surrogate.
3274 Pass both code units as if they were two characters. */
3275 *buf++ = doubled;
3276 if (!--buflen)
3277 return i; /* Drop the 2nd char if at the end of the buffer. */
3279 else /* see https://en.wikipedia.org/wiki/UTF-16 */
3280 code_unit = (doubled << 10) + code_unit - 0x35FDC00;
3281 doubled = 0;
3283 else if (code_unit >= 0xD800 && code_unit <= 0xDBFF)
3285 /* Handle mismatched 2nd surrogate the same as a normal character. */
3286 doubled = code_unit;
3287 continue;
3290 /* The only "fake" characters delivered by ToUnicode() or
3291 TranslateMessage() are:
3292 0x01 .. 0x1a for Ctrl-letter, Enter, Tab, Ctrl-Break, Esc, Backspace
3293 0x00 and 0x1b .. 0x1f for Control- []\@^_
3294 0x7f for Control-BackSpace
3295 0x20 for Control-Space */
3296 if (ignore_ctrl
3297 && (code_unit < 0x20 || code_unit == 0x7f
3298 || (code_unit == 0x20 && ctrl)))
3300 /* Non-character payload in a WM_CHAR
3301 (Ctrl-something pressed, see above). Ignore, and report. */
3302 if (ctrl_cnt)
3303 (*ctrl_cnt)++;
3304 continue;
3306 /* Traditionally, Emacs would ignore the character payload of VK_NUMPAD*
3307 keys, and would treat them later via `function-key-map'. In addition
3308 to usual 102-key NUMPAD keys, this map also treats `kp-'-variants of
3309 space, tab, enter, separator, equal. TAB and EQUAL, apparently,
3310 cannot be generated on Win-GUI branch. ENTER is already handled
3311 by the code above. According to `lispy_function_keys', kp_space is
3312 generated by not-extended VK_CLEAR. (kp-tab != VK_OEM_NEC_EQUAL!).
3314 We do similarly for backward-compatibility, but ignore only the
3315 characters restorable later by `function-key-map'. */
3316 if (code_unit < 0x7f
3317 && ((vk >= VK_NUMPAD0 && vk <= VK_DIVIDE)
3318 || (exp && ((vk >= VK_PRIOR && vk <= VK_DOWN) ||
3319 vk == VK_INSERT || vk == VK_DELETE || vk == VK_CLEAR)))
3320 && strchr ("0123456789/*-+.,", code_unit))
3321 continue;
3322 *buf++ = code_unit;
3323 buflen--;
3325 return i - buflen;
3328 #ifdef DBG_WM_CHARS
3329 # define FPRINTF_WM_CHARS(ARG) fprintf ARG
3330 #else
3331 # define FPRINTF_WM_CHARS(ARG) (void)0
3332 #endif
3334 /* This is a heuristic only. This is supposed to track the state of the
3335 finite automaton in the language environment of Windows.
3337 However, separate windows (if with the same different language
3338 environments!) should have different values. Moreover, switching to a
3339 non-Emacs window with the same language environment, and using (dead)keys
3340 there would change the value stored in the kernel, but not this value. */
3341 /* A layout may emit deadkey=0. It looks like this would reset the state
3342 of the kernel's finite automaton (equivalent to emiting 0-length string,
3343 which is otherwise impossible in the dead-key map of a layout).
3344 Be ready to treat the case when this delivers WM_(SYS)DEADCHAR. */
3345 static int after_deadkey = -1;
3347 static int
3348 deliver_wm_chars (int do_translate, HWND hwnd, UINT msg, UINT wParam,
3349 UINT lParam, int legacy_alt_meta)
3351 /* An "old style" keyboard description may assign up to 125 UTF-16 code
3352 points to a keypress.
3353 (However, the "old style" TranslateMessage() would deliver at most 16 of
3354 them.) Be on a safe side, and prepare to treat many more. */
3355 int ctrl_cnt, buf[1024], count, is_dead, after_dead = (after_deadkey > 0);
3357 /* Since the keypress processing logic of Windows has a lot of state, it
3358 is important to call TranslateMessage() for every keyup/keydown, AND
3359 do it exactly once. (The actual change of state is done by
3360 ToUnicode[Ex](), which is called by TranslateMessage(). So one can
3361 call ToUnicode[Ex]() instead.)
3363 The "usual" message pump calls TranslateMessage() for EVERY event.
3364 Emacs calls TranslateMessage() very selectively (is it needed for doing
3365 some tricky stuff with Win95??? With newer Windows, selectiveness is,
3366 most probably, not needed -- and harms a lot).
3368 So, with the usual message pump, the following call to TranslateMessage()
3369 is not needed (and is going to be VERY harmful). With Emacs' message
3370 pump, the call is needed. */
3371 if (do_translate)
3373 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3375 windows_msg.time = GetMessageTime ();
3376 TranslateMessage (&windows_msg);
3378 count = get_wm_chars (hwnd, buf, sizeof (buf)/sizeof (*buf), 1,
3379 /* The message may have been synthesized by
3380 who knows what; be conservative. */
3381 modifier_set (VK_LCONTROL)
3382 || modifier_set (VK_RCONTROL)
3383 || modifier_set (VK_CONTROL),
3384 &ctrl_cnt, &is_dead, wParam,
3385 (lParam & 0x1000000L) != 0);
3386 if (count)
3388 W32Msg wmsg;
3389 DWORD console_modifiers = construct_console_modifiers ();
3390 int *b = buf, strip_ExtraMods = 1, hairy = 0;
3391 const char *type_CtrlAlt = NULL;
3393 /* XXXX In fact, there may be another case when we need to do the same:
3394 What happens if the string defined in the LIGATURES has length
3395 0? Probably, we will get count==0, but the state of the finite
3396 automaton would reset to 0??? */
3397 after_deadkey = -1;
3399 /* wParam is checked when converting CapsLock to Shift; this is a clone
3400 of w32_get_key_modifiers (). */
3401 wmsg.dwModifiers = w32_kbd_mods_to_emacs (console_modifiers, wParam);
3403 /* What follows is just heuristics; the correct treatement requires
3404 non-destructive ToUnicode():
3405 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Can_an_application_on_Windows_accept_keyboard_events?_Part_IV:_application-specific_modifiers
3407 What one needs to find is:
3408 * which of the present modifiers AFFECT the resulting char(s)
3409 (so should be stripped, since their EFFECT is "already
3410 taken into account" in the string in buf), and
3411 * which modifiers are not affecting buf, so should be reported to
3412 the application for further treatment.
3414 Example: assume that we know:
3415 (A) lCtrl+rCtrl+rAlt modifiers with VK_A key produce a Latin "f"
3416 ("may be logical" in JCUKEN-flavored Russian keyboard flavors);
3417 (B) removing any of lCtrl, rCtrl, rAlt changes the produced char;
3418 (C) Win-modifier is not affecting the produced character
3419 (this is the common case: happens with all "standard" layouts).
3421 Suppose the user presses Win+lCtrl+rCtrl+rAlt modifiers with VK_A.
3422 What is the intent of the user? We need to guess the intent to decide
3423 which event to deliver to the application.
3425 This looks like a reasonable logic: since Win- modifier doesn't affect
3426 the output string, the user was pressing Win for SOME OTHER purpose.
3427 So the user wanted to generate Win-SOMETHING event. Now, what is
3428 something? If one takes the mantra that "character payload is more
3429 important than the combination of keypresses which resulted in this
3430 payload", then one should ignore lCtrl+rCtrl+rAlt, ignore VK_A, and
3431 assume that the user wanted to generate Win-f.
3433 Unfortunately, without non-destructive ToUnicode(), checking (B),(C)
3434 is out of question. So we use heuristics (hopefully, covering
3435 99.9999% of cases). */
3437 /* Another thing to watch for is a possibility to use AltGr-* and
3438 Ctrl-Alt-* with different semantic.
3440 Background: the layout defining the KLLF_ALTGR bit are treated
3441 specially by the kernel: when VK_RMENU (=rightAlt, =AltGr) is pressed
3442 (released), a press (release) of VK_LCONTROL is emulated (unless Ctrl
3443 is already down). As a result, any press/release of AltGr is seen
3444 by applications as a press/release of lCtrl AND rAlt. This is
3445 applicable, in particular, to ToUnicode[Ex](). (Keyrepeat is covered
3446 the same way!)
3448 NOTE: it IS possible to see bare rAlt even with KLLF_ALTGR; but this
3449 requires a good finger coordination: doing (physically)
3450 Down-lCtrl Down-rAlt Up-lCtrl Down-a
3451 (doing quick enough, so that key repeat of rAlt [which would
3452 generate new "fake" Down-lCtrl events] does not happens before 'a'
3453 is down) results in no "fake" events, so the application will see
3454 only rAlt down when 'a' is pressed. (However, fake Up-lCtrl WILL
3455 be generated when rAlt goes UP.)
3457 In fact, note also that KLLF_ALTGR does not prohibit construction of
3458 rCtrl-rAlt (just press them in this order!).
3460 Moreover: "traditional" layouts do not define distinct modifier-masks
3461 for VK_LMENU and VK_RMENU (same for VK_L/RCONTROL). Instead, they
3462 rely on the KLLF_ALTGR bit to make the behavior of VK_LMENU and
3463 VK_RMENU distinct. As a corollary, for such layouts, the produced
3464 character is the same for AltGr-* (=rAlt-*) and Ctrl-Alt-* (in any
3465 combination of handedness). For description of masks, see
3467 http://search.cpan.org/~ilyaz/UI-KeyboardLayout/lib/UI/KeyboardLayout.pm#Keyboard_input_on_Windows,_Part_I:_what_is_the_kernel_doing?
3469 By default, Emacs was using these coincidences via the following
3470 heuristics: it was treating:
3471 (*) keypresses with lCtrl-rAlt modifiers as if they are carrying
3472 ONLY the character payload (no matter what the actual keyboard
3473 was defining: if lCtrl-lAlt-b was delivering U+05df=beta, then
3474 Emacs saw [beta]; if lCtrl-lAlt-b was undefined in the layout,
3475 the keypress was completely ignored), and
3476 (*) keypresses with the other combinations of handedness of Ctrl-Alt
3477 modifiers (e.g., lCtrl-lAlt) as if they NEVER carry a character
3478 payload (so they were reported "raw": if lCtrl-lAlt-b was
3479 delivering beta, then Emacs saw event [C-A-b], and not [beta]).
3480 This worked good for "traditional" layouts: users could type both
3481 AltGr-x and Ctrl-Alt-x, and one was a character, another a bindable
3482 event.
3484 However, for layouts which deliver different characters for AltGr-x
3485 and lCtrl-lAlt-x, this scheme makes the latter character unaccessible
3486 in Emacs. While it is easy to access functionality of [C-M-x] in
3487 Emacs by other means (for example, by the `controlify' prefix, or
3488 using lCtrl-rCtrl-x, or rCtrl-rAlt-x [in this order]), missing
3489 characters cannot be reconstructed without a tedious manual work. */
3491 /* These two cases are often going to be distinguishable, since at most
3492 one of these character is defined with KBDCTRL | KBDMENU modifier
3493 bitmap. (This heuristic breaks if both lCtrl-lAlt- AND lCtrl-rAlt-
3494 are translated to modifier bitmaps distinct from KBDCTRL | KBDMENU,
3495 or in the cases when lCtrl-lAlt-* and lCtrl-rAlt-* are generally
3496 different, but lCtrl-lAlt-x and lCtrl-rAlt-x happen to deliver the
3497 same character.)
3499 So we have 2 chunks of info:
3500 (A) is it lCtrl-rAlt-, or lCtrl-lAlt, or some other combination?
3501 (B) is the delivered character defined with KBDCTRL | KBDMENU bits?
3502 Basing on (A) and (B), we should decide whether to ignore the
3503 delivered character. (Before, Emacs was completely ignoring (B), and
3504 was treating the 3-state of (A) as a bit.) This means that we have 6
3505 bits of customization.
3507 Additionally, a presence of two Ctrl down may be AltGr-rCtrl-. */
3509 /* Strip all non-Shift modifiers if:
3510 - more than one UTF-16 code point delivered (can't call VkKeyScanW ())
3511 - or the character is a result of combining with a prefix key. */
3512 if (!after_dead && count == 1 && *b < 0x10000)
3514 if (console_modifiers & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
3515 && console_modifiers & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
3517 type_CtrlAlt = "bB"; /* generic bindable Ctrl-Alt- modifiers */
3518 if ((console_modifiers & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3519 == (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED))
3520 /* double-Ctrl:
3521 e.g. AltGr-rCtrl on some layouts (in this order!) */
3522 type_CtrlAlt = "dD";
3523 else if ((console_modifiers
3524 & (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3525 == (LEFT_CTRL_PRESSED | LEFT_ALT_PRESSED))
3526 type_CtrlAlt = "lL"; /* Ctrl-Alt- modifiers on the left */
3527 else if (!NILP (Vw32_recognize_altgr)
3528 && ((console_modifiers
3529 & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)))
3530 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
3531 type_CtrlAlt = "gG"; /* modifiers as in AltGr */
3533 else if (wmsg.dwModifiers & (alt_modifier | meta_modifier)
3534 || ((console_modifiers
3535 & (LEFT_WIN_PRESSED | RIGHT_WIN_PRESSED
3536 | APPS_PRESSED | SCROLLLOCK_ON))))
3538 /* Pure Alt (or combination of Alt, Win, APPS, scrolllock. */
3539 type_CtrlAlt = "aA";
3541 if (type_CtrlAlt)
3543 /* Out of bound bitmap: */
3544 SHORT r = VkKeyScanW (*b), bitmap = 0x1FF;
3546 FPRINTF_WM_CHARS((stderr, "VkKeyScanW %#06x %#04x\n", (int)r,
3547 wParam));
3548 if ((r & 0xFF) == wParam)
3549 bitmap = r>>8; /* *b is reachable via simple interface */
3550 else
3552 /* VkKeyScanW() (essentially) returns the FIRST key with
3553 the specified character; so here the pressed key is the
3554 SECONDARY key producing the character.
3556 Essentially, we have no information about the "role" of
3557 modifiers on this key: which contribute into the
3558 produced character (so "are consumed"), and which are
3559 "extra" (must attache to bindable events).
3561 The default above would consume ALL modifiers, so the
3562 character is reported "as is". However, on many layouts
3563 the ordering of the keys (in the layout table) is not
3564 thought out well, so the "secondary" keys are often those
3565 which the users would prefer to use with Alt-CHAR.
3566 (Moreover - with e.g. Czech-QWERTY - the ASCII
3567 punctuation is accessible from two equally [nu]preferable
3568 AltGr-keys.)
3570 SO: Heuristic: if the reported char is ASCII, AND Meta
3571 modifier is a candidate, behave as if Meta is present
3572 (fallback to the legacy branch; bug#23251).
3574 (This would break layouts
3575 - delivering ASCII characters
3576 - on SECONDARY keys
3577 - with not Shift/AltGr-like modifier combinations.
3578 All 3 conditions together must be pretty exotic
3579 cases - and a workaround exists: use "primary" keys!) */
3580 if (*b < 0x80
3581 && (wmsg.dwModifiers
3582 & (alt_modifier | meta_modifier
3583 | super_modifier | hyper_modifier)))
3584 return 0;
3586 if (*type_CtrlAlt == 'a') /* Simple Alt seen */
3588 if ((bitmap & ~1) == 0) /* 1: KBDSHIFT */
3590 /* In "traditional" layouts, Alt without Ctrl does not
3591 change the delivered character. This detects this
3592 situation; it is safe to report this as Alt-something
3593 -- as opposed to delivering the reported character
3594 without modifiers. */
3595 if (legacy_alt_meta
3596 && *b > 0x7f && ('A' <= wParam && wParam <= 'Z'))
3597 /* For backward-compatibility with older Emacsen, let
3598 this be processed by another branch below (which
3599 would convert it to Alt-Latin char via wParam). */
3600 return 0;
3602 else
3603 hairy = 1;
3605 /* Check whether the delivered character(s) is accessible via
3606 KBDCTRL | KBDALT ( | KBDSHIFT ) modifier mask (which is 7). */
3607 else if ((bitmap & ~1) != 6)
3609 /* The character is not accessible via plain Ctrl-Alt(-Shift)
3610 (which is, probably, same as AltGr) modifiers.
3611 Either it was after a prefix key, or is combined with
3612 modifier keys which we don't see, or there is an asymmetry
3613 between left-hand and right-hand modifiers, or other hairy
3614 stuff. */
3615 hairy = 1;
3617 /* The best solution is to delegate these tough (but rarely
3618 needed) choices to the user. Temporarily (???), it is
3619 implemented as C macros.
3621 Essentially, there are 3 things to do: return 0 (handle to the
3622 legacy processing code [ignoring the character payload]; keep
3623 some modifiers (so that they will be processed by the binding
3624 system [on top of the character payload]; strip modifiers [so
3625 that `self-insert' is going to be triggered with the character
3626 payload]).
3628 The default below should cover 99.9999% of cases:
3629 (a) strip Alt- in the hairy case only;
3630 (stripping = not ignoring)
3631 (l) for lAlt-lCtrl, ignore the char in simple cases only;
3632 (g) for what looks like AltGr, ignore the modifiers;
3633 (d) for what looks like lCtrl-rCtrl-Alt (probably
3634 AltGr-rCtrl), ignore the character in simple cases only;
3635 (b) for other cases of Ctrl-Alt, ignore the character in
3636 simple cases only.
3638 Essentially, in all hairy cases, and in looks-like-AltGr case,
3639 we keep the character, ignoring the modifiers. In all the
3640 other cases, we ignore the delivered character. */
3641 #define S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD "aldb"
3642 #define S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS ""
3643 if (strchr (S_TYPES_TO_IGNORE_CHARACTER_PAYLOAD,
3644 type_CtrlAlt[hairy]))
3645 return 0;
3646 /* If in neither list, report all the modifiers we see COMBINED
3647 WITH the reported character. */
3648 if (strchr (S_TYPES_TO_REPORT_CHARACTER_PAYLOAD_WITH_MODIFIERS,
3649 type_CtrlAlt[hairy]))
3650 strip_ExtraMods = 0;
3653 if (strip_ExtraMods)
3654 wmsg.dwModifiers = wmsg.dwModifiers & shift_modifier;
3656 signal_user_input ();
3657 while (count--)
3659 FPRINTF_WM_CHARS((stderr, "unichar %#06x\n", *b));
3660 my_post_msg (&wmsg, hwnd, WM_UNICHAR, *b++, lParam);
3662 if (!ctrl_cnt) /* Process ALSO as ctrl */
3663 return 1;
3664 else
3665 FPRINTF_WM_CHARS((stderr, "extra ctrl char\n"));
3666 return -1;
3668 else if (is_dead >= 0)
3670 FPRINTF_WM_CHARS((stderr, "dead %#06x\n", is_dead));
3671 after_deadkey = is_dead;
3672 return 1;
3674 return 0;
3677 /* Main window procedure */
3679 static LRESULT CALLBACK
3680 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
3682 struct frame *f;
3683 struct w32_display_info *dpyinfo = &one_w32_display_info;
3684 W32Msg wmsg;
3685 int windows_translate;
3686 int key;
3688 /* Note that it is okay to call x_window_to_frame, even though we are
3689 not running in the main lisp thread, because frame deletion
3690 requires the lisp thread to synchronize with this thread. Thus, if
3691 a frame struct is returned, it can be used without concern that the
3692 lisp thread might make it disappear while we are using it.
3694 NB. Walking the frame list in this thread is safe (as long as
3695 writes of Lisp_Object slots are atomic, which they are on Windows).
3696 Although delete-frame can destructively modify the frame list while
3697 we are walking it, a garbage collection cannot occur until after
3698 delete-frame has synchronized with this thread.
3700 It is also safe to use functions that make GDI calls, such as
3701 w32_clear_rect, because these functions must obtain a DC handle
3702 from the frame struct using get_frame_dc which is thread-aware. */
3704 switch (msg)
3706 case WM_ERASEBKGND:
3707 f = x_window_to_frame (dpyinfo, hwnd);
3708 if (f)
3710 HDC hdc = get_frame_dc (f);
3711 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
3712 w32_clear_rect (f, hdc, &wmsg.rect);
3713 release_frame_dc (f, hdc);
3715 #if defined (W32_DEBUG_DISPLAY)
3716 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
3718 wmsg.rect.left, wmsg.rect.top,
3719 wmsg.rect.right, wmsg.rect.bottom));
3720 #endif /* W32_DEBUG_DISPLAY */
3722 return 1;
3723 case WM_PALETTECHANGED:
3724 /* ignore our own changes */
3725 if ((HWND)wParam != hwnd)
3727 f = x_window_to_frame (dpyinfo, hwnd);
3728 if (f)
3729 /* get_frame_dc will realize our palette and force all
3730 frames to be redrawn if needed. */
3731 release_frame_dc (f, get_frame_dc (f));
3733 return 0;
3734 case WM_PAINT:
3736 PAINTSTRUCT paintStruct;
3737 RECT update_rect;
3738 memset (&update_rect, 0, sizeof (update_rect));
3740 f = x_window_to_frame (dpyinfo, hwnd);
3741 if (f == 0)
3743 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
3744 return 0;
3747 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
3748 fails. Apparently this can happen under some
3749 circumstances. */
3750 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
3752 enter_crit ();
3753 BeginPaint (hwnd, &paintStruct);
3755 /* The rectangles returned by GetUpdateRect and BeginPaint
3756 do not always match. Play it safe by assuming both areas
3757 are invalid. */
3758 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
3760 #if defined (W32_DEBUG_DISPLAY)
3761 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
3763 wmsg.rect.left, wmsg.rect.top,
3764 wmsg.rect.right, wmsg.rect.bottom));
3765 DebPrint ((" [update region is %d,%d-%d,%d]\n",
3766 update_rect.left, update_rect.top,
3767 update_rect.right, update_rect.bottom));
3768 #endif
3769 EndPaint (hwnd, &paintStruct);
3770 leave_crit ();
3772 /* Change the message type to prevent Windows from
3773 combining WM_PAINT messages in the Lisp thread's queue,
3774 since Windows assumes that each message queue is
3775 dedicated to one frame and does not bother checking
3776 that hwnd matches before combining them. */
3777 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
3779 return 0;
3782 /* If GetUpdateRect returns 0 (meaning there is no update
3783 region), assume the whole window needs to be repainted. */
3784 GetClientRect (hwnd, &wmsg.rect);
3785 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3786 return 0;
3789 case WM_INPUTLANGCHANGE:
3790 /* Inform lisp thread of keyboard layout changes. */
3791 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3793 /* The state of the finite automaton is separate per every input
3794 language environment (so it does not change when one switches
3795 to a different window with the same environment). Moreover,
3796 the experiments show that the state is not remembered when
3797 one switches back to the pre-previous environment. */
3798 after_deadkey = -1;
3800 /* XXXX??? What follows is a COMPLETE misunderstanding of Windows! */
3802 /* Clear dead keys in the keyboard state; for simplicity only
3803 preserve modifier key states. */
3805 int i;
3806 BYTE keystate[256];
3808 GetKeyboardState (keystate);
3809 for (i = 0; i < 256; i++)
3810 if (1
3811 && i != VK_SHIFT
3812 && i != VK_LSHIFT
3813 && i != VK_RSHIFT
3814 && i != VK_CAPITAL
3815 && i != VK_NUMLOCK
3816 && i != VK_SCROLL
3817 && i != VK_CONTROL
3818 && i != VK_LCONTROL
3819 && i != VK_RCONTROL
3820 && i != VK_MENU
3821 && i != VK_LMENU
3822 && i != VK_RMENU
3823 && i != VK_LWIN
3824 && i != VK_RWIN)
3825 keystate[i] = 0;
3826 SetKeyboardState (keystate);
3828 goto dflt;
3830 case WM_HOTKEY:
3831 /* Synchronize hot keys with normal input. */
3832 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
3833 return (0);
3835 case WM_KEYUP:
3836 case WM_SYSKEYUP:
3837 record_keyup (wParam, lParam);
3838 goto dflt;
3840 case WM_KEYDOWN:
3841 case WM_SYSKEYDOWN:
3842 /* Ignore keystrokes we fake ourself; see below. */
3843 if (dpyinfo->faked_key == wParam)
3845 dpyinfo->faked_key = 0;
3846 /* Make sure TranslateMessage sees them though (as long as
3847 they don't produce WM_CHAR messages). This ensures that
3848 indicator lights are toggled promptly on Windows 9x, for
3849 example. */
3850 if (wParam < 256 && lispy_function_keys[wParam])
3852 windows_translate = 1;
3853 goto translate;
3855 return 0;
3858 /* Synchronize modifiers with current keystroke. */
3859 sync_modifiers ();
3860 record_keydown (wParam, lParam);
3861 if (w32_use_fallback_wm_chars_method)
3862 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3864 windows_translate = 0;
3866 switch (wParam)
3868 case VK_LWIN:
3869 if (!w32_kbdhook_active && NILP (Vw32_pass_lwindow_to_system))
3871 /* Prevent system from acting on keyup (which opens the
3872 Start menu if no other key was pressed) by simulating a
3873 press of Space which we will ignore. */
3874 if (GetAsyncKeyState (wParam) & 1)
3876 if (NUMBERP (Vw32_phantom_key_code))
3877 key = XUINT (Vw32_phantom_key_code) & 255;
3878 else
3879 key = VK_SPACE;
3880 dpyinfo->faked_key = key;
3881 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3884 if (!NILP (Vw32_lwindow_modifier))
3885 return 0;
3886 break;
3887 case VK_RWIN:
3888 if (!w32_kbdhook_active && NILP (Vw32_pass_rwindow_to_system))
3890 if (GetAsyncKeyState (wParam) & 1)
3892 if (NUMBERP (Vw32_phantom_key_code))
3893 key = XUINT (Vw32_phantom_key_code) & 255;
3894 else
3895 key = VK_SPACE;
3896 dpyinfo->faked_key = key;
3897 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3900 if (!NILP (Vw32_rwindow_modifier))
3901 return 0;
3902 break;
3903 case VK_APPS:
3904 if (!NILP (Vw32_apps_modifier))
3905 return 0;
3906 break;
3907 case VK_MENU:
3908 if (NILP (Vw32_pass_alt_to_system))
3909 /* Prevent DefWindowProc from activating the menu bar if an
3910 Alt key is pressed and released by itself. */
3911 return 0;
3912 windows_translate = 1;
3913 break;
3914 case VK_CAPITAL:
3915 /* Decide whether to treat as modifier or function key. */
3916 if (NILP (Vw32_enable_caps_lock))
3917 goto disable_lock_key;
3918 windows_translate = 1;
3919 break;
3920 case VK_NUMLOCK:
3921 /* Decide whether to treat as modifier or function key. */
3922 if (NILP (Vw32_enable_num_lock))
3923 goto disable_lock_key;
3924 windows_translate = 1;
3925 break;
3926 case VK_SCROLL:
3927 /* Decide whether to treat as modifier or function key. */
3928 if (NILP (Vw32_scroll_lock_modifier))
3929 goto disable_lock_key;
3930 windows_translate = 1;
3931 break;
3932 disable_lock_key:
3933 /* Ensure the appropriate lock key state (and indicator light)
3934 remains in the same state. We do this by faking another
3935 press of the relevant key. Apparently, this really is the
3936 only way to toggle the state of the indicator lights. */
3937 dpyinfo->faked_key = wParam;
3938 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3939 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3940 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3941 KEYEVENTF_EXTENDEDKEY | 0, 0);
3942 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3943 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3944 /* Ensure indicator lights are updated promptly on Windows 9x
3945 (TranslateMessage apparently does this), after forwarding
3946 input event. */
3947 post_character_message (hwnd, msg, wParam, lParam,
3948 w32_get_key_modifiers (wParam, lParam));
3949 windows_translate = 1;
3950 break;
3951 case VK_CONTROL:
3952 case VK_SHIFT:
3953 case VK_PROCESSKEY: /* Generated by IME. */
3954 windows_translate = 1;
3955 break;
3956 case VK_CANCEL:
3957 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3958 which is confusing for purposes of key binding; convert
3959 VK_CANCEL events into VK_PAUSE events. */
3960 wParam = VK_PAUSE;
3961 break;
3962 case VK_PAUSE:
3963 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3964 for purposes of key binding; convert these back into
3965 VK_NUMLOCK events, at least when we want to see NumLock key
3966 presses. (Note that there is never any possibility that
3967 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3968 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3969 wParam = VK_NUMLOCK;
3970 break;
3971 default:
3972 if (w32_unicode_gui && !w32_use_fallback_wm_chars_method)
3974 /* If this event generates characters or deadkeys, do
3975 not interpret it as a "raw combination of modifiers
3976 and keysym". Hide deadkeys, and use the generated
3977 character(s) instead of the keysym. (Backward
3978 compatibility: exceptions for numpad keys generating
3979 0-9 . , / * - +, and for extra-Alt combined with a
3980 non-Latin char.)
3982 Try to not report modifiers which have effect on
3983 which character or deadkey is generated.
3985 Example (contrived): if rightAlt-? generates f (on a
3986 Cyrillic keyboard layout), and Ctrl, leftAlt do not
3987 affect the generated character, one wants to report
3988 Ctrl-leftAlt-f if the user presses
3989 Ctrl-leftAlt-rightAlt-?. */
3990 int res;
3991 #if 0
3992 /* Some of WM_CHAR may be fed to us directly, some are
3993 results of TranslateMessage(). Using 0 as the first
3994 argument (in a separate call) might help us
3995 distinguish these two cases.
3997 However, the keypress feeders would most probably
3998 expect the "standard" message pump, when
3999 TranslateMessage() is called on EVERY KeyDown/KeyUp
4000 event. So they may feed us Down-Ctrl Down-FAKE
4001 Char-o and expect us to recognize it as Ctrl-o.
4002 Using 0 as the first argument would interfere with
4003 this. */
4004 deliver_wm_chars (0, hwnd, msg, wParam, lParam, 1);
4005 #endif
4006 /* Processing the generated WM_CHAR messages *WHILE* we
4007 handle KEYDOWN/UP event is the best choice, since
4008 without any fuss, we know all 3 of: scancode, virtual
4009 keycode, and expansion. (Additionally, one knows
4010 boundaries of expansion of different keypresses.) */
4011 res = deliver_wm_chars (1, hwnd, msg, wParam, lParam, 1);
4012 windows_translate = -(res != 0);
4013 if (res > 0) /* Bound to character(s) or a deadkey */
4014 break;
4015 /* deliver_wm_chars may make some branches after this vestigal. */
4017 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
4018 /* If not defined as a function key, change it to a WM_CHAR message. */
4019 if (wParam > 255 || !lispy_function_keys[wParam])
4021 DWORD modifiers = construct_console_modifiers ();
4023 if (!NILP (Vw32_recognize_altgr)
4024 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
4026 /* Always let TranslateMessage handle AltGr key chords;
4027 for some reason, ToAscii doesn't always process AltGr
4028 chords correctly. */
4029 windows_translate = 1;
4031 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
4033 /* Handle key chords including any modifiers other
4034 than shift directly, in order to preserve as much
4035 modifier information as possible. */
4036 if ('A' <= wParam && wParam <= 'Z')
4038 /* Don't translate modified alphabetic keystrokes,
4039 so the user doesn't need to constantly switch
4040 layout to type control or meta keystrokes when
4041 the normal layout translates alphabetic
4042 characters to non-ascii characters. */
4043 if (!modifier_set (VK_SHIFT))
4044 wParam += ('a' - 'A');
4045 msg = WM_CHAR;
4047 else
4049 /* Try to handle other keystrokes by determining the
4050 base character (ie. translating the base key plus
4051 shift modifier). */
4052 int add;
4053 KEY_EVENT_RECORD key;
4055 key.bKeyDown = TRUE;
4056 key.wRepeatCount = 1;
4057 key.wVirtualKeyCode = wParam;
4058 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
4059 key.uChar.AsciiChar = 0;
4060 key.dwControlKeyState = modifiers;
4062 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
4063 /* 0 means an unrecognized keycode, negative means
4064 dead key. Ignore both. */
4065 while (--add >= 0)
4067 /* Forward asciified character sequence. */
4068 post_character_message
4069 (hwnd, WM_CHAR,
4070 (unsigned char) key.uChar.AsciiChar, lParam,
4071 w32_get_key_modifiers (wParam, lParam));
4072 w32_kbd_patch_key (&key, w32_keyboard_codepage);
4074 return 0;
4077 else
4079 /* Let TranslateMessage handle everything else. */
4080 windows_translate = 1;
4085 if (windows_translate == -1)
4086 break;
4087 translate:
4088 if (windows_translate)
4090 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
4091 windows_msg.time = GetMessageTime ();
4092 TranslateMessage (&windows_msg);
4093 goto dflt;
4096 /* Fall through */
4098 case WM_SYSCHAR:
4099 case WM_CHAR:
4100 if (wParam > 255 )
4102 W32Msg wmsg;
4104 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4105 signal_user_input ();
4106 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
4109 else
4110 post_character_message (hwnd, msg, wParam, lParam,
4111 w32_get_key_modifiers (wParam, lParam));
4112 break;
4114 case WM_UNICHAR:
4115 /* WM_UNICHAR looks promising from the docs, but the exact
4116 circumstances in which TranslateMessage sends it is one of those
4117 Microsoft secret API things that EU and US courts are supposed
4118 to have put a stop to already. Spy++ shows it being sent to Notepad
4119 and other MS apps, but never to Emacs.
4121 Some third party IMEs send it in accordance with the official
4122 documentation though, so handle it here.
4124 UNICODE_NOCHAR is used to test for support for this message.
4125 TRUE indicates that the message is supported. */
4126 if (wParam == UNICODE_NOCHAR)
4127 return TRUE;
4130 W32Msg wmsg;
4131 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4132 signal_user_input ();
4133 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4135 break;
4137 case WM_IME_CHAR:
4138 /* If we can't get the IME result as Unicode, use default processing,
4139 which will at least allow characters decodable in the system locale
4140 get through. */
4141 if (!get_composition_string_fn)
4142 goto dflt;
4144 else if (!ignore_ime_char)
4146 wchar_t * buffer;
4147 int size, i;
4148 W32Msg wmsg;
4149 HIMC context = get_ime_context_fn (hwnd);
4150 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
4151 /* Get buffer size. */
4152 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
4153 buffer = alloca (size);
4154 size = get_composition_string_fn (context, GCS_RESULTSTR,
4155 buffer, size);
4156 release_ime_context_fn (hwnd, context);
4158 signal_user_input ();
4159 for (i = 0; i < size / sizeof (wchar_t); i++)
4161 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
4162 lParam);
4164 /* Ignore the messages for the rest of the
4165 characters in the string that was output above. */
4166 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
4168 else
4169 ignore_ime_char--;
4171 break;
4173 case WM_IME_STARTCOMPOSITION:
4174 if (!set_ime_composition_window_fn)
4175 goto dflt;
4176 else
4178 COMPOSITIONFORM form;
4179 HIMC context;
4180 struct window *w;
4182 /* Implementation note: The code below does something that
4183 one shouldn't do: it accesses the window object from a
4184 separate thread, while the main (a.k.a. "Lisp") thread
4185 runs and can legitimately delete and even GC it. That is
4186 why we are extra careful not to futz with a window that
4187 is different from the one recorded when the system caret
4188 coordinates were last modified. That is also why we are
4189 careful not to move the IME window if the window
4190 described by W was deleted, as indicated by its buffer
4191 field being reset to nil. */
4192 f = x_window_to_frame (dpyinfo, hwnd);
4193 if (!(f && FRAME_LIVE_P (f)))
4194 goto dflt;
4195 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
4196 /* Punt if someone changed the frame's selected window
4197 behind our back. */
4198 if (w != w32_system_caret_window)
4199 goto dflt;
4201 form.dwStyle = CFS_RECT;
4202 form.ptCurrentPos.x = w32_system_caret_x;
4203 form.ptCurrentPos.y = w32_system_caret_y;
4205 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
4206 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
4207 + w32_system_caret_hdr_height);
4208 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
4209 - WINDOW_RIGHT_MARGIN_WIDTH (w)
4210 - WINDOW_RIGHT_FRINGE_WIDTH (w));
4211 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
4212 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
4213 - w32_system_caret_mode_height);
4215 /* Punt if the window was deleted behind our back. */
4216 if (!BUFFERP (w->contents))
4217 goto dflt;
4219 context = get_ime_context_fn (hwnd);
4221 if (!context)
4222 goto dflt;
4224 set_ime_composition_window_fn (context, &form);
4225 release_ime_context_fn (hwnd, context);
4227 /* We should "goto dflt" here to pass WM_IME_STARTCOMPOSITION to
4228 DefWindowProc, so that the composition window will actually
4229 be displayed. But doing so causes trouble with displaying
4230 dialog boxes, such as the file selection dialog or font
4231 selection dialog. So something else is needed to fix the
4232 former without breaking the latter. See bug#11732. */
4233 break;
4235 case WM_IME_ENDCOMPOSITION:
4236 ignore_ime_char = 0;
4237 goto dflt;
4239 /* Simulate middle mouse button events when left and right buttons
4240 are used together, but only if user has two button mouse. */
4241 case WM_LBUTTONDOWN:
4242 case WM_RBUTTONDOWN:
4243 if (w32_num_mouse_buttons > 2)
4244 goto handle_plain_button;
4247 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
4248 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
4250 if (button_state & this)
4251 return 0;
4253 if (button_state == 0)
4254 SetCapture (hwnd);
4256 button_state |= this;
4258 if (button_state & other)
4260 if (mouse_button_timer)
4262 KillTimer (hwnd, mouse_button_timer);
4263 mouse_button_timer = 0;
4265 /* Generate middle mouse event instead. */
4266 msg = WM_MBUTTONDOWN;
4267 button_state |= MMOUSE;
4269 else if (button_state & MMOUSE)
4271 /* Ignore button event if we've already generated a
4272 middle mouse down event. This happens if the
4273 user releases and press one of the two buttons
4274 after we've faked a middle mouse event. */
4275 return 0;
4277 else
4279 /* Flush out saved message. */
4280 post_msg (&saved_mouse_button_msg);
4282 wmsg.dwModifiers = w32_get_modifiers ();
4283 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4284 signal_user_input ();
4286 /* Clear message buffer. */
4287 saved_mouse_button_msg.msg.hwnd = 0;
4289 else
4291 /* Hold onto message for now. */
4292 mouse_button_timer =
4293 SetTimer (hwnd, MOUSE_BUTTON_ID,
4294 w32_mouse_button_tolerance, NULL);
4295 saved_mouse_button_msg.msg.hwnd = hwnd;
4296 saved_mouse_button_msg.msg.message = msg;
4297 saved_mouse_button_msg.msg.wParam = wParam;
4298 saved_mouse_button_msg.msg.lParam = lParam;
4299 saved_mouse_button_msg.msg.time = GetMessageTime ();
4300 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
4303 return 0;
4305 case WM_LBUTTONUP:
4306 case WM_RBUTTONUP:
4307 if (w32_num_mouse_buttons > 2)
4308 goto handle_plain_button;
4311 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
4312 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
4314 if ((button_state & this) == 0)
4315 return 0;
4317 button_state &= ~this;
4319 if (button_state & MMOUSE)
4321 /* Only generate event when second button is released. */
4322 if ((button_state & other) == 0)
4324 msg = WM_MBUTTONUP;
4325 button_state &= ~MMOUSE;
4327 if (button_state) emacs_abort ();
4329 else
4330 return 0;
4332 else
4334 /* Flush out saved message if necessary. */
4335 if (saved_mouse_button_msg.msg.hwnd)
4337 post_msg (&saved_mouse_button_msg);
4340 wmsg.dwModifiers = w32_get_modifiers ();
4341 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4342 signal_user_input ();
4344 /* Always clear message buffer and cancel timer. */
4345 saved_mouse_button_msg.msg.hwnd = 0;
4346 KillTimer (hwnd, mouse_button_timer);
4347 mouse_button_timer = 0;
4349 if (button_state == 0)
4350 ReleaseCapture ();
4352 return 0;
4354 case WM_XBUTTONDOWN:
4355 case WM_XBUTTONUP:
4356 if (w32_pass_extra_mouse_buttons_to_system)
4357 goto dflt;
4358 /* else fall through and process them. */
4359 case WM_MBUTTONDOWN:
4360 case WM_MBUTTONUP:
4361 handle_plain_button:
4363 BOOL up;
4364 int button;
4366 /* Ignore middle and extra buttons as long as the menu is active. */
4367 f = x_window_to_frame (dpyinfo, hwnd);
4368 if (f && f->output_data.w32->menubar_active)
4369 return 0;
4371 if (parse_button (msg, HIWORD (wParam), &button, &up))
4373 if (up) ReleaseCapture ();
4374 else SetCapture (hwnd);
4375 button = (button == 0) ? LMOUSE :
4376 ((button == 1) ? MMOUSE : RMOUSE);
4377 if (up)
4378 button_state &= ~button;
4379 else
4380 button_state |= button;
4384 wmsg.dwModifiers = w32_get_modifiers ();
4385 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4386 signal_user_input ();
4388 /* Need to return true for XBUTTON messages, false for others,
4389 to indicate that we processed the message. */
4390 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
4392 case WM_MOUSEMOVE:
4393 f = x_window_to_frame (dpyinfo, hwnd);
4394 if (f)
4396 /* Ignore mouse movements as long as the menu is active.
4397 These movements are processed by the window manager
4398 anyway, and it's wrong to handle them as if they happened
4399 on the underlying frame. */
4400 if (f->output_data.w32->menubar_active)
4401 return 0;
4403 /* If the mouse moved, and the mouse pointer is invisible,
4404 make it visible again. We do this here so as to be able
4405 to show the mouse pointer even when the main
4406 (a.k.a. "Lisp") thread is busy doing something. */
4407 static int last_x, last_y;
4408 int x = GET_X_LPARAM (lParam);
4409 int y = GET_Y_LPARAM (lParam);
4411 if (f->pointer_invisible
4412 && (x != last_x || y != last_y))
4413 f->pointer_invisible = false;
4415 last_x = x;
4416 last_y = y;
4419 /* If the mouse has just moved into the frame, start tracking
4420 it, so we will be notified when it leaves the frame. Mouse
4421 tracking only works under W98 and NT4 and later. On earlier
4422 versions, there is no way of telling when the mouse leaves the
4423 frame, so we just have to put up with help-echo and mouse
4424 highlighting remaining while the frame is not active. */
4425 if (track_mouse_event_fn && !track_mouse_window
4426 /* If the menu bar is active, turning on tracking of mouse
4427 movement events might send these events to the tooltip
4428 frame, if the user happens to move the mouse pointer over
4429 the tooltip. But since we don't process events for
4430 tooltip frames, this causes Windows to present a
4431 hourglass cursor, which is ugly and unexpected. So don't
4432 enable tracking mouse events in this case; they will be
4433 restarted when the menu pops down. (Confusingly, the
4434 menubar_active member of f->output_data.w32, tested
4435 above, is only set when a menu was popped up _not_ from
4436 the frame's menu bar, but via x-popup-menu.) */
4437 && !menubar_in_use)
4439 TRACKMOUSEEVENT tme;
4440 tme.cbSize = sizeof (tme);
4441 tme.dwFlags = TME_LEAVE;
4442 tme.hwndTrack = hwnd;
4443 tme.dwHoverTime = HOVER_DEFAULT;
4445 track_mouse_event_fn (&tme);
4446 track_mouse_window = hwnd;
4448 case WM_HSCROLL:
4449 case WM_VSCROLL:
4450 if (w32_mouse_move_interval <= 0
4451 || (msg == WM_MOUSEMOVE && button_state == 0))
4453 wmsg.dwModifiers = w32_get_modifiers ();
4454 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4455 return 0;
4458 /* Hang onto mouse move and scroll messages for a bit, to avoid
4459 sending such events to Emacs faster than it can process them.
4460 If we get more events before the timer from the first message
4461 expires, we just replace the first message. */
4463 if (saved_mouse_move_msg.msg.hwnd == 0)
4464 mouse_move_timer =
4465 SetTimer (hwnd, MOUSE_MOVE_ID,
4466 w32_mouse_move_interval, NULL);
4468 /* Hold onto message for now. */
4469 saved_mouse_move_msg.msg.hwnd = hwnd;
4470 saved_mouse_move_msg.msg.message = msg;
4471 saved_mouse_move_msg.msg.wParam = wParam;
4472 saved_mouse_move_msg.msg.lParam = lParam;
4473 saved_mouse_move_msg.msg.time = GetMessageTime ();
4474 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
4476 return 0;
4478 case WM_MOUSEWHEEL:
4479 case WM_DROPFILES:
4480 wmsg.dwModifiers = w32_get_modifiers ();
4481 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4482 signal_user_input ();
4483 return 0;
4485 case WM_APPCOMMAND:
4486 if (w32_pass_multimedia_buttons_to_system)
4487 goto dflt;
4488 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
4489 case WM_MOUSEHWHEEL:
4490 wmsg.dwModifiers = w32_get_modifiers ();
4491 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4492 signal_user_input ();
4493 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
4494 handled, to prevent the system trying to handle it by faking
4495 scroll bar events. */
4496 return 1;
4498 case WM_TIMER:
4499 /* Flush out saved messages if necessary. */
4500 if (wParam == mouse_button_timer)
4502 if (saved_mouse_button_msg.msg.hwnd)
4504 post_msg (&saved_mouse_button_msg);
4505 signal_user_input ();
4506 saved_mouse_button_msg.msg.hwnd = 0;
4508 KillTimer (hwnd, mouse_button_timer);
4509 mouse_button_timer = 0;
4511 else if (wParam == mouse_move_timer)
4513 if (saved_mouse_move_msg.msg.hwnd)
4515 post_msg (&saved_mouse_move_msg);
4516 saved_mouse_move_msg.msg.hwnd = 0;
4518 KillTimer (hwnd, mouse_move_timer);
4519 mouse_move_timer = 0;
4521 else if (wParam == menu_free_timer)
4523 KillTimer (hwnd, menu_free_timer);
4524 menu_free_timer = 0;
4525 f = x_window_to_frame (dpyinfo, hwnd);
4526 /* If a popup menu is active, don't wipe its strings. */
4527 if (menubar_in_use
4528 && current_popup_menu == NULL)
4530 /* Free memory used by owner-drawn and help-echo strings. */
4531 w32_free_menu_strings (hwnd);
4532 if (f)
4533 f->output_data.w32->menubar_active = 0;
4534 menubar_in_use = 0;
4537 return 0;
4539 case WM_NCACTIVATE:
4540 /* Windows doesn't send us focus messages when putting up and
4541 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
4542 The only indication we get that something happened is receiving
4543 this message afterwards. So this is a good time to reset our
4544 keyboard modifiers' state. */
4545 reset_modifiers ();
4546 goto dflt;
4548 case WM_INITMENU:
4549 button_state = 0;
4550 ReleaseCapture ();
4551 /* We must ensure menu bar is fully constructed and up to date
4552 before allowing user interaction with it. To achieve this
4553 we send this message to the lisp thread and wait for a
4554 reply (whose value is not actually needed) to indicate that
4555 the menu bar is now ready for use, so we can now return.
4557 To remain responsive in the meantime, we enter a nested message
4558 loop that can process all other messages.
4560 However, we skip all this if the message results from calling
4561 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
4562 thread a message because it is blocked on us at this point. We
4563 set menubar_active before calling TrackPopupMenu to indicate
4564 this (there is no possibility of confusion with real menubar
4565 being active). */
4567 f = x_window_to_frame (dpyinfo, hwnd);
4568 if (f
4569 && (f->output_data.w32->menubar_active
4570 /* We can receive this message even in the absence of a
4571 menubar (ie. when the system menu is activated) - in this
4572 case we do NOT want to forward the message, otherwise it
4573 will cause the menubar to suddenly appear when the user
4574 had requested it to be turned off! */
4575 || f->output_data.w32->menubar_widget == NULL))
4576 return 0;
4579 deferred_msg msg_buf;
4581 /* Detect if message has already been deferred; in this case
4582 we cannot return any sensible value to ignore this. */
4583 if (find_deferred_msg (hwnd, msg) != NULL)
4584 emacs_abort ();
4586 menubar_in_use = 1;
4588 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
4591 case WM_EXITMENULOOP:
4592 f = x_window_to_frame (dpyinfo, hwnd);
4594 /* If a menu is still active, check again after a short delay,
4595 since Windows often (always?) sends the WM_EXITMENULOOP
4596 before the corresponding WM_COMMAND message.
4597 Don't do this if a popup menu is active, since it is only
4598 menubar menus that require cleaning up in this way.
4600 if (f && menubar_in_use && current_popup_menu == NULL)
4601 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
4603 /* If hourglass cursor should be displayed, display it now. */
4604 if (f && f->output_data.w32->hourglass_p)
4605 SetCursor (f->output_data.w32->hourglass_cursor);
4607 goto dflt;
4609 case WM_MENUSELECT:
4610 /* Direct handling of help_echo in menus. Should be safe now
4611 that we generate the help_echo by placing a help event in the
4612 keyboard buffer. */
4614 HMENU menu = (HMENU) lParam;
4615 UINT menu_item = (UINT) LOWORD (wParam);
4616 UINT flags = (UINT) HIWORD (wParam);
4618 w32_menu_display_help (hwnd, menu, menu_item, flags);
4620 return 0;
4622 case WM_MEASUREITEM:
4623 f = x_window_to_frame (dpyinfo, hwnd);
4624 if (f)
4626 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
4628 if (pMis->CtlType == ODT_MENU)
4630 /* Work out dimensions for popup menu titles. */
4631 char * title = (char *) pMis->itemData;
4632 HDC hdc = GetDC (hwnd);
4633 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4634 LOGFONT menu_logfont;
4635 HFONT old_font;
4636 SIZE size;
4638 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4639 menu_logfont.lfWeight = FW_BOLD;
4640 menu_font = CreateFontIndirect (&menu_logfont);
4641 old_font = SelectObject (hdc, menu_font);
4643 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
4644 if (title)
4646 if (unicode_append_menu)
4647 GetTextExtentPoint32W (hdc, (WCHAR *) title,
4648 wcslen ((WCHAR *) title),
4649 &size);
4650 else
4651 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
4653 pMis->itemWidth = size.cx;
4654 if (pMis->itemHeight < size.cy)
4655 pMis->itemHeight = size.cy;
4657 else
4658 pMis->itemWidth = 0;
4660 SelectObject (hdc, old_font);
4661 DeleteObject (menu_font);
4662 ReleaseDC (hwnd, hdc);
4663 return TRUE;
4666 return 0;
4668 case WM_DRAWITEM:
4669 f = x_window_to_frame (dpyinfo, hwnd);
4670 if (f)
4672 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
4674 if (pDis->CtlType == ODT_MENU)
4676 /* Draw popup menu title. */
4677 char * title = (char *) pDis->itemData;
4678 if (title)
4680 HDC hdc = pDis->hDC;
4681 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
4682 LOGFONT menu_logfont;
4683 HFONT old_font;
4685 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
4686 menu_logfont.lfWeight = FW_BOLD;
4687 menu_font = CreateFontIndirect (&menu_logfont);
4688 old_font = SelectObject (hdc, menu_font);
4690 /* Always draw title as if not selected. */
4691 if (unicode_append_menu)
4692 ExtTextOutW (hdc,
4693 pDis->rcItem.left
4694 + GetSystemMetrics (SM_CXMENUCHECK),
4695 pDis->rcItem.top,
4696 ETO_OPAQUE, &pDis->rcItem,
4697 (WCHAR *) title,
4698 wcslen ((WCHAR *) title), NULL);
4699 else
4700 ExtTextOut (hdc,
4701 pDis->rcItem.left
4702 + GetSystemMetrics (SM_CXMENUCHECK),
4703 pDis->rcItem.top,
4704 ETO_OPAQUE, &pDis->rcItem,
4705 title, strlen (title), NULL);
4707 SelectObject (hdc, old_font);
4708 DeleteObject (menu_font);
4710 return TRUE;
4713 return 0;
4715 #if 0
4716 /* Still not right - can't distinguish between clicks in the
4717 client area of the frame from clicks forwarded from the scroll
4718 bars - may have to hook WM_NCHITTEST to remember the mouse
4719 position and then check if it is in the client area ourselves. */
4720 case WM_MOUSEACTIVATE:
4721 /* Discard the mouse click that activates a frame, allowing the
4722 user to click anywhere without changing point (or worse!).
4723 Don't eat mouse clicks on scrollbars though!! */
4724 if (LOWORD (lParam) == HTCLIENT )
4725 return MA_ACTIVATEANDEAT;
4726 goto dflt;
4727 #endif
4729 case WM_MOUSELEAVE:
4730 /* No longer tracking mouse. */
4731 track_mouse_window = NULL;
4733 case WM_ACTIVATEAPP:
4734 case WM_ACTIVATE:
4735 case WM_WINDOWPOSCHANGED:
4736 case WM_SHOWWINDOW:
4737 /* Inform lisp thread that a frame might have just been obscured
4738 or exposed, so should recheck visibility of all frames. */
4739 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4740 goto dflt;
4742 case WM_SETFOCUS:
4743 dpyinfo->faked_key = 0;
4744 reset_modifiers ();
4745 if (!w32_kbdhook_active)
4746 register_hot_keys (hwnd);
4747 goto command;
4748 case WM_KILLFOCUS:
4749 if (!w32_kbdhook_active)
4750 unregister_hot_keys (hwnd);
4751 button_state = 0;
4752 ReleaseCapture ();
4753 /* Relinquish the system caret. */
4754 if (w32_system_caret_hwnd)
4756 w32_visible_system_caret_hwnd = NULL;
4757 w32_system_caret_hwnd = NULL;
4758 DestroyCaret ();
4760 goto command;
4761 case WM_COMMAND:
4762 menubar_in_use = 0;
4763 f = x_window_to_frame (dpyinfo, hwnd);
4764 if (f && HIWORD (wParam) == 0)
4766 if (menu_free_timer)
4768 KillTimer (hwnd, menu_free_timer);
4769 menu_free_timer = 0;
4772 case WM_MOVE:
4773 case WM_SIZE:
4774 command:
4775 wmsg.dwModifiers = w32_get_modifiers ();
4776 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4777 goto dflt;
4779 #ifdef WINDOWSNT
4780 case WM_CREATE:
4781 setup_w32_kbdhook ();
4782 goto dflt;
4783 #endif
4785 case WM_DESTROY:
4786 #ifdef WINDOWSNT
4787 remove_w32_kbdhook ();
4788 #endif
4789 CoUninitialize ();
4790 return 0;
4792 case WM_WTSSESSION_CHANGE:
4793 if (wParam == WTS_SESSION_LOCK)
4794 reset_w32_kbdhook_state ();
4795 goto dflt;
4797 case WM_CLOSE:
4798 wmsg.dwModifiers = w32_get_modifiers ();
4799 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4800 return 0;
4802 case WM_ENDSESSION:
4803 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4804 /* If we return, the process will be terminated immediately. */
4805 sleep (1000);
4807 case WM_WINDOWPOSCHANGING:
4808 /* Don't restrict the sizing of any kind of frames. If the window
4809 manager doesn't, there's no reason to do it ourselves. */
4810 return 0;
4812 case WM_GETMINMAXINFO:
4813 /* Hack to allow resizing the Emacs frame above the screen size.
4814 Note that Windows 9x limits coordinates to 16-bits. */
4815 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
4816 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
4817 return 0;
4819 case WM_SETCURSOR:
4820 if (LOWORD (lParam) == HTCLIENT)
4822 f = x_window_to_frame (dpyinfo, hwnd);
4823 if (f)
4825 if (f->output_data.w32->hourglass_p
4826 && !menubar_in_use && !current_popup_menu)
4827 SetCursor (f->output_data.w32->hourglass_cursor);
4828 else if (f->pointer_invisible)
4829 SetCursor (NULL);
4830 else
4831 SetCursor (f->output_data.w32->current_cursor);
4834 return 0;
4836 goto dflt;
4838 case WM_EMACS_SETCURSOR:
4840 Cursor cursor = (Cursor) wParam;
4841 f = x_window_to_frame (dpyinfo, hwnd);
4842 if (f && cursor)
4844 f->output_data.w32->current_cursor = cursor;
4845 /* Don't change the cursor while menu-bar menu is in use. */
4846 if (!f->output_data.w32->menubar_active
4847 && !f->output_data.w32->hourglass_p)
4849 if (f->pointer_invisible)
4850 SetCursor (NULL);
4851 else
4852 SetCursor (cursor);
4855 return 0;
4858 case WM_EMACS_SHOWCURSOR:
4860 ShowCursor ((BOOL) wParam);
4862 return 0;
4865 case WM_EMACS_CREATEVSCROLLBAR:
4866 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
4867 (struct scroll_bar *) lParam);
4869 case WM_EMACS_CREATEHSCROLLBAR:
4870 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
4871 (struct scroll_bar *) lParam);
4873 case WM_EMACS_SHOWWINDOW:
4874 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4876 case WM_EMACS_BRINGTOTOP:
4877 case WM_EMACS_SETFOREGROUND:
4879 HWND foreground_window;
4880 DWORD foreground_thread, retval;
4882 /* On NT 5.0, and apparently Windows 98, it is necessary to
4883 attach to the thread that currently has focus in order to
4884 pull the focus away from it. */
4885 foreground_window = GetForegroundWindow ();
4886 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4887 if (!foreground_window
4888 || foreground_thread == GetCurrentThreadId ()
4889 || !AttachThreadInput (GetCurrentThreadId (),
4890 foreground_thread, TRUE))
4891 foreground_thread = 0;
4893 retval = SetForegroundWindow ((HWND) wParam);
4894 if (msg == WM_EMACS_BRINGTOTOP)
4895 retval = BringWindowToTop ((HWND) wParam);
4897 /* Detach from the previous foreground thread. */
4898 if (foreground_thread)
4899 AttachThreadInput (GetCurrentThreadId (),
4900 foreground_thread, FALSE);
4902 return retval;
4905 case WM_EMACS_SETWINDOWPOS:
4907 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4908 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4909 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4912 case WM_EMACS_DESTROYWINDOW:
4913 DragAcceptFiles ((HWND) wParam, FALSE);
4914 return DestroyWindow ((HWND) wParam);
4916 case WM_EMACS_HIDE_CARET:
4917 return HideCaret (hwnd);
4919 case WM_EMACS_SHOW_CARET:
4920 return ShowCaret (hwnd);
4922 case WM_EMACS_DESTROY_CARET:
4923 w32_system_caret_hwnd = NULL;
4924 w32_visible_system_caret_hwnd = NULL;
4925 return DestroyCaret ();
4927 case WM_EMACS_TRACK_CARET:
4928 /* If there is currently no system caret, create one. */
4929 if (w32_system_caret_hwnd == NULL)
4931 /* Use the default caret width, and avoid changing it
4932 unnecessarily, as it confuses screen reader software. */
4933 w32_system_caret_hwnd = hwnd;
4934 CreateCaret (hwnd, NULL, 0,
4935 w32_system_caret_height);
4938 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4939 return 0;
4940 /* Ensure visible caret gets turned on when requested. */
4941 else if (w32_use_visible_system_caret
4942 && w32_visible_system_caret_hwnd != hwnd)
4944 w32_visible_system_caret_hwnd = hwnd;
4945 return ShowCaret (hwnd);
4947 /* Ensure visible caret gets turned off when requested. */
4948 else if (!w32_use_visible_system_caret
4949 && w32_visible_system_caret_hwnd)
4951 w32_visible_system_caret_hwnd = NULL;
4952 return HideCaret (hwnd);
4954 else
4955 return 1;
4957 case WM_EMACS_TRACKPOPUPMENU:
4959 UINT flags;
4960 POINT *pos;
4961 int retval;
4962 pos = (POINT *)lParam;
4963 flags = TPM_CENTERALIGN;
4964 if (button_state & LMOUSE)
4965 flags |= TPM_LEFTBUTTON;
4966 else if (button_state & RMOUSE)
4967 flags |= TPM_RIGHTBUTTON;
4969 /* Remember we did a SetCapture on the initial mouse down event,
4970 so for safety, we make sure the capture is canceled now. */
4971 ReleaseCapture ();
4972 button_state = 0;
4974 /* Use menubar_active to indicate that WM_INITMENU is from
4975 TrackPopupMenu below, and should be ignored. */
4976 f = x_window_to_frame (dpyinfo, hwnd);
4977 if (f)
4978 f->output_data.w32->menubar_active = 1;
4980 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4981 0, hwnd, NULL))
4983 MSG amsg;
4984 /* Eat any mouse messages during popupmenu */
4985 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4986 PM_REMOVE));
4987 /* Get the menu selection, if any */
4988 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4990 retval = LOWORD (amsg.wParam);
4992 else
4994 retval = 0;
4997 else
4999 retval = -1;
5002 return retval;
5004 case WM_EMACS_FILENOTIFY:
5005 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5006 return 1;
5008 default:
5009 /* Check for messages registered at runtime. */
5010 if (msg == msh_mousewheel)
5012 wmsg.dwModifiers = w32_get_modifiers ();
5013 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5014 signal_user_input ();
5015 return 0;
5018 dflt:
5019 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
5022 /* The most common default return code for handled messages is 0. */
5023 return 0;
5026 static void
5027 my_create_window (struct frame * f)
5029 MSG msg;
5030 static int coords[2];
5031 Lisp_Object left, top;
5032 struct w32_display_info *dpyinfo = &one_w32_display_info;
5034 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
5035 anything that is not a number and is not Qunbound. */
5036 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
5037 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
5038 if (EQ (left, Qunbound))
5039 coords[0] = CW_USEDEFAULT;
5040 else
5041 coords[0] = XINT (left);
5042 if (EQ (top, Qunbound))
5043 coords[1] = CW_USEDEFAULT;
5044 else
5045 coords[1] = XINT (top);
5047 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
5048 (WPARAM)f, (LPARAM)coords))
5049 emacs_abort ();
5050 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5054 /* Create a tooltip window. Unlike my_create_window, we do not do this
5055 indirectly via the Window thread, as we do not need to process Window
5056 messages for the tooltip. Creating tooltips indirectly also creates
5057 deadlocks when tooltips are created for menu items. */
5058 static void
5059 my_create_tip_window (struct frame *f)
5061 RECT rect;
5063 rect.left = rect.top = 0;
5064 rect.right = FRAME_PIXEL_WIDTH (f);
5065 rect.bottom = FRAME_PIXEL_HEIGHT (f);
5067 AdjustWindowRect (&rect, f->output_data.w32->dwStyle, false);
5069 tip_window = FRAME_W32_WINDOW (f)
5070 = CreateWindow (EMACS_CLASS,
5071 f->namebuf,
5072 f->output_data.w32->dwStyle,
5073 f->left_pos,
5074 f->top_pos,
5075 rect.right - rect.left,
5076 rect.bottom - rect.top,
5077 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5078 NULL,
5079 hinst,
5080 NULL);
5082 if (tip_window)
5084 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
5085 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
5086 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
5087 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5089 /* Tip frames have no scrollbars. */
5090 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
5091 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
5093 /* Do this to discard the default setting specified by our parent. */
5094 ShowWindow (tip_window, SW_HIDE);
5099 /* Create and set up the w32 window for frame F. */
5101 static void
5102 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
5104 block_input ();
5106 /* Use the resource name as the top-level window name
5107 for looking up resources. Make a non-Lisp copy
5108 for the window manager, so GC relocation won't bother it.
5110 Elsewhere we specify the window name for the window manager. */
5111 f->namebuf = xlispstrdup (Vx_resource_name);
5113 my_create_window (f);
5115 validate_x_resource_name ();
5117 /* x_set_name normally ignores requests to set the name if the
5118 requested name is the same as the current name. This is the one
5119 place where that assumption isn't correct; f->name is set, but
5120 the server hasn't been told. */
5122 Lisp_Object name;
5123 int explicit = f->explicit_name;
5125 f->explicit_name = 0;
5126 name = f->name;
5127 fset_name (f, Qnil);
5128 x_set_name (f, name, explicit);
5131 unblock_input ();
5133 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5134 initialize_frame_menubar (f);
5136 if (FRAME_W32_WINDOW (f) == 0)
5137 error ("Unable to create window");
5140 /* Handle the icon stuff for this window. Perhaps later we might
5141 want an x_set_icon_position which can be called interactively as
5142 well. */
5144 static void
5145 x_icon (struct frame *f, Lisp_Object parms)
5147 Lisp_Object icon_x, icon_y;
5148 struct w32_display_info *dpyinfo = &one_w32_display_info;
5150 /* Set the position of the icon. Note that Windows 95 groups all
5151 icons in the tray. */
5152 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5153 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5154 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5156 CHECK_NUMBER (icon_x);
5157 CHECK_NUMBER (icon_y);
5159 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5160 error ("Both left and top icon corners of icon must be specified");
5162 block_input ();
5164 #if 0 /* TODO */
5165 /* Start up iconic or window? */
5166 x_wm_set_window_state
5167 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5168 ? IconicState
5169 : NormalState));
5171 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
5172 ? f->icon_name
5173 : f->name)));
5174 #endif
5176 unblock_input ();
5180 static void
5181 x_make_gc (struct frame *f)
5183 XGCValues gc_values;
5185 block_input ();
5187 /* Create the GC's of this frame.
5188 Note that many default values are used. */
5190 /* Normal video */
5191 gc_values.font = FRAME_FONT (f);
5193 /* Cursor has cursor-color background, background-color foreground. */
5194 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5195 gc_values.background = f->output_data.w32->cursor_pixel;
5196 f->output_data.w32->cursor_gc
5197 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5198 (GCFont | GCForeground | GCBackground),
5199 &gc_values);
5201 /* Reliefs. */
5202 f->output_data.w32->white_relief.gc = 0;
5203 f->output_data.w32->black_relief.gc = 0;
5205 unblock_input ();
5209 /* Handler for signals raised during x_create_frame and
5210 x_create_tip_frame. FRAME is the frame which is partially
5211 constructed. */
5213 static Lisp_Object
5214 unwind_create_frame (Lisp_Object frame)
5216 struct frame *f = XFRAME (frame);
5218 /* If frame is ``official'', nothing to do. */
5219 if (NILP (Fmemq (frame, Vframe_list)))
5221 #ifdef GLYPH_DEBUG
5222 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5224 /* If the frame's image cache refcount is still the same as our
5225 private shadow variable, it means we are unwinding a frame
5226 for which we didn't yet call init_frame_faces, where the
5227 refcount is incremented. Therefore, we increment it here, so
5228 that free_frame_faces, called in x_free_frame_resources
5229 below, will not mistakenly decrement the counter that was not
5230 incremented yet to account for this new frame. */
5231 if (FRAME_IMAGE_CACHE (f) != NULL
5232 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
5233 FRAME_IMAGE_CACHE (f)->refcount++;
5234 #endif
5236 x_free_frame_resources (f);
5237 free_glyphs (f);
5239 #ifdef GLYPH_DEBUG
5240 /* Check that reference counts are indeed correct. */
5241 eassert (dpyinfo->reference_count == dpyinfo_refcount);
5242 eassert ((dpyinfo->terminal->image_cache == NULL
5243 && image_cache_refcount == 0)
5244 || (dpyinfo->terminal->image_cache != NULL
5245 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
5246 #endif
5247 return Qt;
5250 return Qnil;
5253 static void
5254 do_unwind_create_frame (Lisp_Object frame)
5256 unwind_create_frame (frame);
5259 static void
5260 x_default_font_parameter (struct frame *f, Lisp_Object parms)
5262 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5263 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
5264 RES_TYPE_STRING);
5265 Lisp_Object font;
5266 if (EQ (font_param, Qunbound))
5267 font_param = Qnil;
5268 font = !NILP (font_param) ? font_param
5269 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
5271 if (!STRINGP (font))
5273 int i;
5274 static const char *names[]
5275 = { "Courier New-10",
5276 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
5277 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
5278 "Fixedsys",
5279 NULL };
5281 for (i = 0; names[i]; i++)
5283 font = font_open_by_name (f, build_unibyte_string (names[i]));
5284 if (! NILP (font))
5285 break;
5287 if (NILP (font))
5288 error ("No suitable font was found");
5290 else if (!NILP (font_param))
5292 /* Remember the explicit font parameter, so we can re-apply it after
5293 we've applied the `default' face settings. */
5294 x_set_frame_parameters (f, Fcons (Fcons (Qfont_parameter, font_param),
5295 Qnil));
5297 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
5300 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5301 1, 1, 0,
5302 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5303 Return an Emacs frame object.
5304 PARAMETERS is an alist of frame parameters.
5305 If the parameters specify that the frame should not have a minibuffer,
5306 and do not specify a specific minibuffer window to use,
5307 then `default-minibuffer-frame' must be a frame whose minibuffer can
5308 be shared by the new frame.
5310 This function is an internal primitive--use `make-frame' instead. */)
5311 (Lisp_Object parameters)
5313 struct frame *f;
5314 Lisp_Object frame, tem;
5315 Lisp_Object name;
5316 bool minibuffer_only = false;
5317 long window_prompting = 0;
5318 ptrdiff_t count = SPECPDL_INDEX ();
5319 Lisp_Object display;
5320 struct w32_display_info *dpyinfo = NULL;
5321 Lisp_Object parent;
5322 struct kboard *kb;
5323 int x_width = 0, x_height = 0;
5325 if (!FRAME_W32_P (SELECTED_FRAME ())
5326 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
5327 error ("Cannot create a GUI frame in a -nw session");
5329 /* Make copy of frame parameters because the original is in pure
5330 storage now. */
5331 parameters = Fcopy_alist (parameters);
5333 /* Use this general default value to start with
5334 until we know if this frame has a specified name. */
5335 Vx_resource_name = Vinvocation_name;
5337 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
5338 if (EQ (display, Qunbound))
5339 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
5340 if (EQ (display, Qunbound))
5341 display = Qnil;
5342 dpyinfo = check_x_display_info (display);
5343 kb = dpyinfo->terminal->kboard;
5345 if (!dpyinfo->terminal->name)
5346 error ("Terminal is not live, can't create new frames on it");
5348 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5349 if (!STRINGP (name)
5350 && ! EQ (name, Qunbound)
5351 && ! NILP (name))
5352 error ("Invalid frame name--not a string or nil");
5354 if (STRINGP (name))
5355 Vx_resource_name = name;
5357 /* See if parent window is specified. */
5358 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5359 if (EQ (parent, Qunbound))
5360 parent = Qnil;
5361 if (! NILP (parent))
5362 CHECK_NUMBER (parent);
5364 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5365 /* No need to protect DISPLAY because that's not used after passing
5366 it to make_frame_without_minibuffer. */
5367 frame = Qnil;
5368 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5369 RES_TYPE_SYMBOL);
5370 if (EQ (tem, Qnone) || NILP (tem))
5371 f = make_frame_without_minibuffer (Qnil, kb, display);
5372 else if (EQ (tem, Qonly))
5374 f = make_minibuffer_frame ();
5375 minibuffer_only = true;
5377 else if (WINDOWP (tem))
5378 f = make_frame_without_minibuffer (tem, kb, display);
5379 else
5380 f = make_frame (true);
5382 XSETFRAME (frame, f);
5384 /* By default, make scrollbars the system standard width and height. */
5385 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5386 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5388 f->terminal = dpyinfo->terminal;
5390 f->output_method = output_w32;
5391 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5392 FRAME_FONTSET (f) = -1;
5394 fset_icon_name
5395 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5396 RES_TYPE_STRING));
5397 if (! STRINGP (f->icon_name))
5398 fset_icon_name (f, Qnil);
5400 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5402 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5403 record_unwind_protect (do_unwind_create_frame, frame);
5405 #ifdef GLYPH_DEBUG
5406 image_cache_refcount =
5407 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5408 dpyinfo_refcount = dpyinfo->reference_count;
5409 #endif /* GLYPH_DEBUG */
5411 /* Specify the parent under which to make this window. */
5412 if (!NILP (parent))
5414 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5415 pointer from integer of different size. */
5416 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5417 f->output_data.w32->explicit_parent = true;
5419 else
5421 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5422 f->output_data.w32->explicit_parent = false;
5425 /* Set the name; the functions to which we pass f expect the name to
5426 be set. */
5427 if (EQ (name, Qunbound) || NILP (name))
5429 fset_name (f, build_string (dpyinfo->w32_id_name));
5430 f->explicit_name = false;
5432 else
5434 fset_name (f, name);
5435 f->explicit_name = true;
5436 /* Use the frame's title when getting resources for this frame. */
5437 specbind (Qx_resource_name, name);
5440 if (uniscribe_available)
5441 register_font_driver (&uniscribe_font_driver, f);
5442 register_font_driver (&w32font_driver, f);
5444 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5445 "fontBackend", "FontBackend", RES_TYPE_STRING);
5447 /* Extract the window parameters from the supplied values
5448 that are needed to determine window geometry. */
5449 x_default_font_parameter (f, parameters);
5451 x_default_parameter (f, parameters, Qborder_width, make_number (2),
5452 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5454 /* We recognize either internalBorderWidth or internalBorder
5455 (which is what xterm calls it). */
5456 if (NILP (Fassq (Qinternal_border_width, parameters)))
5458 Lisp_Object value;
5460 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5461 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5462 if (! EQ (value, Qunbound))
5463 parameters = Fcons (Fcons (Qinternal_border_width, value),
5464 parameters);
5466 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5467 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5468 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5469 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5470 NULL, NULL, RES_TYPE_NUMBER);
5471 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5472 NULL, NULL, RES_TYPE_NUMBER);
5473 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5474 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5475 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5476 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5478 /* Also do the stuff which must be set before the window exists. */
5479 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5480 "foreground", "Foreground", RES_TYPE_STRING);
5481 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5482 "background", "Background", RES_TYPE_STRING);
5483 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5484 "pointerColor", "Foreground", RES_TYPE_STRING);
5485 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5486 "borderColor", "BorderColor", RES_TYPE_STRING);
5487 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5488 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5489 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5490 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5491 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5492 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5493 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5494 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5495 /* Process alpha here (Bug#16619). */
5496 x_default_parameter (f, parameters, Qalpha, Qnil,
5497 "alpha", "Alpha", RES_TYPE_NUMBER);
5499 /* Init faces first since we need the frame's column width/line
5500 height in various occasions. */
5501 init_frame_faces (f);
5503 /* The following call of change_frame_size is needed since otherwise
5504 x_set_tool_bar_lines will already work with the character sizes
5505 installed by init_frame_faces while the frame's pixel size is
5506 still calculated from a character size of 1 and we subsequently
5507 hit the (height >= 0) assertion in window_box_height.
5509 The non-pixelwise code apparently worked around this because it
5510 had one frame line vs one toolbar line which left us with a zero
5511 root window height which was obviously wrong as well ... */
5512 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5513 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5514 Qx_create_frame_1);
5516 /* The X resources controlling the menu-bar and tool-bar are
5517 processed specially at startup, and reflected in the mode
5518 variables; ignore them here. */
5519 x_default_parameter (f, parameters, Qmenu_bar_lines,
5520 NILP (Vmenu_bar_mode)
5521 ? make_number (0) : make_number (1),
5522 NULL, NULL, RES_TYPE_NUMBER);
5523 x_default_parameter (f, parameters, Qtool_bar_lines,
5524 NILP (Vtool_bar_mode)
5525 ? make_number (0) : make_number (1),
5526 NULL, NULL, RES_TYPE_NUMBER);
5528 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5529 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5530 x_default_parameter (f, parameters, Qtitle, Qnil,
5531 "title", "Title", RES_TYPE_STRING);
5533 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5534 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5536 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5537 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5538 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5539 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5540 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5541 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5542 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5544 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5546 window_prompting = x_figure_window_size (f, parameters, true, &x_width, &x_height);
5548 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5549 f->no_split = minibuffer_only || EQ (tem, Qt);
5551 w32_window (f, window_prompting, minibuffer_only);
5552 x_icon (f, parameters);
5554 x_make_gc (f);
5556 /* Now consider the frame official. */
5557 f->terminal->reference_count++;
5558 FRAME_DISPLAY_INFO (f)->reference_count++;
5559 Vframe_list = Fcons (frame, Vframe_list);
5561 /* We need to do this after creating the window, so that the
5562 icon-creation functions can say whose icon they're describing. */
5563 x_default_parameter (f, parameters, Qicon_type, Qnil,
5564 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5566 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5567 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5568 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5569 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5570 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5571 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5572 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5573 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5574 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
5575 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
5577 /* Allow x_set_window_size, now. */
5578 f->can_x_set_window_size = true;
5580 if (x_width > 0)
5581 SET_FRAME_WIDTH (f, x_width);
5582 if (x_height > 0)
5583 SET_FRAME_HEIGHT (f, x_height);
5585 /* Tell the server what size and position, etc, we want, and how
5586 badly we want them. This should be done after we have the menu
5587 bar so that its size can be taken into account. */
5588 block_input ();
5589 x_wm_set_size_hint (f, window_prompting, false);
5590 unblock_input ();
5592 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
5593 Qx_create_frame_2);
5595 /* Process fullscreen parameter here in the hope that normalizing a
5596 fullheight/fullwidth frame will produce the size set by the last
5597 adjust_frame_size call. */
5598 x_default_parameter (f, parameters, Qfullscreen, Qnil,
5599 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5601 /* Make the window appear on the frame and enable display, unless
5602 the caller says not to. However, with explicit parent, Emacs
5603 cannot control visibility, so don't try. */
5604 if (! f->output_data.w32->explicit_parent)
5606 Lisp_Object visibility;
5608 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5609 if (EQ (visibility, Qunbound))
5610 visibility = Qt;
5612 if (EQ (visibility, Qicon))
5613 x_iconify_frame (f);
5614 else if (! NILP (visibility))
5615 x_make_frame_visible (f);
5616 else
5618 /* Must have been Qnil. */
5623 /* Initialize `default-minibuffer-frame' in case this is the first
5624 frame on this terminal. */
5625 if (FRAME_HAS_MINIBUF_P (f)
5626 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
5627 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
5628 kset_default_minibuffer_frame (kb, frame);
5630 /* All remaining specified parameters, which have not been "used"
5631 by x_get_arg and friends, now go in the misc. alist of the frame. */
5632 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
5633 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
5634 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
5636 /* Make sure windows on this frame appear in calls to next-window
5637 and similar functions. */
5638 Vwindow_list = Qnil;
5640 return unbind_to (count, frame);
5643 /* FRAME is used only to get a handle on the X display. We don't pass the
5644 display info directly because we're called from frame.c, which doesn't
5645 know about that structure. */
5646 Lisp_Object
5647 x_get_focus_frame (struct frame *frame)
5649 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
5650 Lisp_Object xfocus;
5651 if (! dpyinfo->w32_focus_frame)
5652 return Qnil;
5654 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5655 return xfocus;
5658 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
5659 doc: /* Internal function called by `color-defined-p', which see.
5660 \(Note that the Nextstep version of this function ignores FRAME.) */)
5661 (Lisp_Object color, Lisp_Object frame)
5663 XColor foo;
5664 struct frame *f = decode_window_system_frame (frame);
5666 CHECK_STRING (color);
5668 if (w32_defined_color (f, SSDATA (color), &foo, false))
5669 return Qt;
5670 else
5671 return Qnil;
5674 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
5675 doc: /* Internal function called by `color-values', which see. */)
5676 (Lisp_Object color, Lisp_Object frame)
5678 XColor foo;
5679 struct frame *f = decode_window_system_frame (frame);
5681 CHECK_STRING (color);
5683 if (w32_defined_color (f, SSDATA (color), &foo, false))
5684 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
5685 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
5686 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
5687 else
5688 return Qnil;
5691 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
5692 doc: /* Internal function called by `display-color-p', which see. */)
5693 (Lisp_Object display)
5695 struct w32_display_info *dpyinfo = check_x_display_info (display);
5697 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
5698 return Qnil;
5700 return Qt;
5703 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
5704 Sx_display_grayscale_p, 0, 1, 0,
5705 doc: /* Return t if DISPLAY supports shades of gray.
5706 Note that color displays do support shades of gray.
5707 The optional argument DISPLAY specifies which display to ask about.
5708 DISPLAY should be either a frame or a display name (a string).
5709 If omitted or nil, that stands for the selected frame's display. */)
5710 (Lisp_Object display)
5712 struct w32_display_info *dpyinfo = check_x_display_info (display);
5714 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
5715 return Qnil;
5717 return Qt;
5720 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
5721 Sx_display_pixel_width, 0, 1, 0,
5722 doc: /* Return the width in pixels of DISPLAY.
5723 The optional argument DISPLAY specifies which display to ask about.
5724 DISPLAY should be either a frame or a display name (a string).
5725 If omitted or nil, that stands for the selected frame's display.
5727 On \"multi-monitor\" setups this refers to the pixel width for all
5728 physical monitors associated with DISPLAY. To get information for
5729 each physical monitor, use `display-monitor-attributes-list'. */)
5730 (Lisp_Object display)
5732 struct w32_display_info *dpyinfo = check_x_display_info (display);
5734 return make_number (x_display_pixel_width (dpyinfo));
5737 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
5738 Sx_display_pixel_height, 0, 1, 0,
5739 doc: /* Return the height in pixels of DISPLAY.
5740 The optional argument DISPLAY specifies which display to ask about.
5741 DISPLAY should be either a frame or a display name (a string).
5742 If omitted or nil, that stands for the selected frame's display.
5744 On \"multi-monitor\" setups this refers to the pixel height for all
5745 physical monitors associated with DISPLAY. To get information for
5746 each physical monitor, use `display-monitor-attributes-list'. */)
5747 (Lisp_Object display)
5749 struct w32_display_info *dpyinfo = check_x_display_info (display);
5751 return make_number (x_display_pixel_height (dpyinfo));
5754 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
5755 0, 1, 0,
5756 doc: /* Return the number of bitplanes of DISPLAY.
5757 The optional argument DISPLAY specifies which display to ask about.
5758 DISPLAY should be either a frame or a display name (a string).
5759 If omitted or nil, that stands for the selected frame's display. */)
5760 (Lisp_Object display)
5762 struct w32_display_info *dpyinfo = check_x_display_info (display);
5764 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
5767 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
5768 0, 1, 0,
5769 doc: /* Return the number of color cells of DISPLAY.
5770 The optional argument DISPLAY specifies which display to ask about.
5771 DISPLAY should be either a frame or a display name (a string).
5772 If omitted or nil, that stands for the selected frame's display. */)
5773 (Lisp_Object display)
5775 struct w32_display_info *dpyinfo = check_x_display_info (display);
5776 int cap;
5778 /* Don't use NCOLORS: it returns incorrect results under remote
5779 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
5780 * overflow and because probably is more meaningful on Windows
5781 * anyway. */
5783 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
5784 return make_number (cap);
5787 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
5788 Sx_server_max_request_size,
5789 0, 1, 0,
5790 doc: /* Return the maximum request size of the server of DISPLAY.
5791 The optional argument DISPLAY specifies which display to ask about.
5792 DISPLAY should be either a frame or a display name (a string).
5793 If omitted or nil, that stands for the selected frame's display. */)
5794 (Lisp_Object display)
5796 return make_number (1);
5799 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
5800 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
5802 \(Labeling every distributor as a "vendor" embodies the false assumption
5803 that operating systems cannot be developed and distributed noncommercially.)
5805 For GNU and Unix systems, this queries the X server software; for
5806 MS-Windows, this queries the OS.
5808 The optional argument TERMINAL specifies which display to ask about.
5809 TERMINAL should be a terminal object, a frame or a display name (a string).
5810 If omitted or nil, that stands for the selected frame's display. */)
5811 (Lisp_Object terminal)
5813 return build_string ("Microsoft Corp.");
5816 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
5817 doc: /* Return the version numbers of the GUI software on TERMINAL.
5818 The value is a list of three integers specifying the version of the GUI
5819 software in use.
5821 For GNU and Unix system, the first 2 numbers are the version of the X
5822 Protocol used on TERMINAL and the 3rd number is the distributor-specific
5823 release number. For MS-Windows, the 3 numbers report the version and
5824 the build number of the OS.
5826 See also the function `x-server-vendor'.
5828 The optional argument TERMINAL specifies which display to ask about.
5829 TERMINAL should be a terminal object, a frame or a display name (a string).
5830 If omitted or nil, that stands for the selected frame's display. */)
5831 (Lisp_Object terminal)
5833 return list3i (w32_major_version, w32_minor_version, w32_build_number);
5836 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
5837 doc: /* Return the number of screens on the server of DISPLAY.
5838 The optional argument DISPLAY specifies which display to ask about.
5839 DISPLAY should be either a frame or a display name (a string).
5840 If omitted or nil, that stands for the selected frame's display. */)
5841 (Lisp_Object display)
5843 return make_number (1);
5846 DEFUN ("x-display-mm-height", Fx_display_mm_height,
5847 Sx_display_mm_height, 0, 1, 0,
5848 doc: /* Return the height in millimeters of DISPLAY.
5849 The optional argument DISPLAY specifies which display to ask about.
5850 DISPLAY should be either a frame or a display name (a string).
5851 If omitted or nil, that stands for the selected frame's display.
5853 On \"multi-monitor\" setups this refers to the height in millimeters for
5854 all physical monitors associated with DISPLAY. To get information
5855 for each physical monitor, use `display-monitor-attributes-list'. */)
5856 (Lisp_Object display)
5858 struct w32_display_info *dpyinfo = check_x_display_info (display);
5859 HDC hdc;
5860 double mm_per_pixel;
5862 hdc = GetDC (NULL);
5863 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5864 / GetDeviceCaps (hdc, VERTRES));
5865 ReleaseDC (NULL, hdc);
5867 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5870 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5871 doc: /* Return the width in millimeters of DISPLAY.
5872 The optional argument DISPLAY specifies which display to ask about.
5873 DISPLAY should be either a frame or a display name (a string).
5874 If omitted or nil, that stands for the selected frame's display.
5876 On \"multi-monitor\" setups this refers to the width in millimeters for
5877 all physical monitors associated with TERMINAL. To get information
5878 for each physical monitor, use `display-monitor-attributes-list'. */)
5879 (Lisp_Object display)
5881 struct w32_display_info *dpyinfo = check_x_display_info (display);
5882 HDC hdc;
5883 double mm_per_pixel;
5885 hdc = GetDC (NULL);
5886 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5887 / GetDeviceCaps (hdc, HORZRES));
5888 ReleaseDC (NULL, hdc);
5890 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5893 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5894 Sx_display_backing_store, 0, 1, 0,
5895 doc: /* Return an indication of whether DISPLAY does backing store.
5896 The value may be `always', `when-mapped', or `not-useful'.
5897 The optional argument DISPLAY specifies which display to ask about.
5898 DISPLAY should be either a frame or a display name (a string).
5899 If omitted or nil, that stands for the selected frame's display. */)
5900 (Lisp_Object display)
5902 return intern ("not-useful");
5905 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5906 Sx_display_visual_class, 0, 1, 0,
5907 doc: /* Return the visual class of DISPLAY.
5908 The value is one of the symbols `static-gray', `gray-scale',
5909 `static-color', `pseudo-color', `true-color', or `direct-color'.
5911 The optional argument DISPLAY specifies which display to ask about.
5912 DISPLAY should be either a frame or a display name (a string).
5913 If omitted or nil, that stands for the selected frame's display. */)
5914 (Lisp_Object display)
5916 struct w32_display_info *dpyinfo = check_x_display_info (display);
5917 Lisp_Object result = Qnil;
5919 if (dpyinfo->has_palette)
5920 result = intern ("pseudo-color");
5921 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5922 result = intern ("static-grey");
5923 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5924 result = intern ("static-color");
5925 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5926 result = intern ("true-color");
5928 return result;
5931 DEFUN ("x-display-save-under", Fx_display_save_under,
5932 Sx_display_save_under, 0, 1, 0,
5933 doc: /* Return t if DISPLAY supports the save-under feature.
5934 The optional argument DISPLAY specifies which display to ask about.
5935 DISPLAY should be either a frame or a display name (a string).
5936 If omitted or nil, that stands for the selected frame's display. */)
5937 (Lisp_Object display)
5939 return Qnil;
5942 static BOOL CALLBACK ALIGN_STACK
5943 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5945 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5947 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5949 return TRUE;
5952 static Lisp_Object
5953 w32_display_monitor_attributes_list (void)
5955 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5956 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5957 int i, n_monitors;
5958 HMONITOR *monitors;
5960 if (!(enum_display_monitors_fn && get_monitor_info_fn
5961 && monitor_from_window_fn))
5962 return Qnil;
5964 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5965 (LPARAM) &monitor_list)
5966 || NILP (monitor_list))
5967 return Qnil;
5969 n_monitors = 0;
5970 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5971 n_monitors++;
5973 monitors = xmalloc (n_monitors * sizeof (*monitors));
5974 for (i = 0; i < n_monitors; i++)
5976 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5977 monitor_list = XCDR (monitor_list);
5980 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5981 FOR_EACH_FRAME (rest, frame)
5983 struct frame *f = XFRAME (frame);
5985 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5987 HMONITOR monitor =
5988 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5989 MONITOR_DEFAULT_TO_NEAREST);
5991 for (i = 0; i < n_monitors; i++)
5992 if (monitors[i] == monitor)
5993 break;
5995 if (i < n_monitors)
5996 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
6000 for (i = 0; i < n_monitors; i++)
6002 Lisp_Object geometry, workarea, name, attributes = Qnil;
6003 HDC hdc;
6004 int width_mm, height_mm;
6005 struct MONITOR_INFO_EX mi;
6007 mi.cbSize = sizeof (mi);
6008 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
6009 continue;
6011 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
6012 if (hdc == NULL)
6013 continue;
6014 width_mm = GetDeviceCaps (hdc, HORZSIZE);
6015 height_mm = GetDeviceCaps (hdc, VERTSIZE);
6016 DeleteDC (hdc);
6018 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
6019 attributes);
6021 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
6023 attributes = Fcons (Fcons (Qname, name), attributes);
6025 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6026 attributes);
6028 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
6029 mi.rcWork.right - mi.rcWork.left,
6030 mi.rcWork.bottom - mi.rcWork.top);
6031 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6033 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
6034 mi.rcMonitor.right - mi.rcMonitor.left,
6035 mi.rcMonitor.bottom - mi.rcMonitor.top);
6036 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6038 if (mi.dwFlags & MONITORINFOF_PRIMARY)
6039 primary_monitor_attributes = attributes;
6040 else
6041 attributes_list = Fcons (attributes, attributes_list);
6044 if (!NILP (primary_monitor_attributes))
6045 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
6047 xfree (monitors);
6049 return attributes_list;
6052 static Lisp_Object
6053 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
6055 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
6056 HDC hdc;
6057 double mm_per_pixel;
6058 int pixel_width, pixel_height, width_mm, height_mm;
6059 RECT workarea_rect;
6061 /* Fallback: treat (possibly) multiple physical monitors as if they
6062 formed a single monitor as a whole. This should provide a
6063 consistent result at least on single monitor environments. */
6064 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
6065 attributes);
6067 frames = Qnil;
6068 FOR_EACH_FRAME (rest, frame)
6070 struct frame *f = XFRAME (frame);
6072 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
6073 frames = Fcons (frame, frames);
6075 attributes = Fcons (Fcons (Qframes, frames), attributes);
6077 pixel_width = x_display_pixel_width (dpyinfo);
6078 pixel_height = x_display_pixel_height (dpyinfo);
6080 hdc = GetDC (NULL);
6081 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6082 / GetDeviceCaps (hdc, HORZRES));
6083 width_mm = pixel_width * mm_per_pixel + 0.5;
6084 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6085 / GetDeviceCaps (hdc, VERTRES));
6086 height_mm = pixel_height * mm_per_pixel + 0.5;
6087 ReleaseDC (NULL, hdc);
6088 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6089 attributes);
6091 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
6092 we don't care. */
6093 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
6094 GetSystemMetrics (SM_YVIRTUALSCREEN),
6095 pixel_width, pixel_height);
6096 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
6097 workarea = list4i (workarea_rect.left, workarea_rect.top,
6098 workarea_rect.right - workarea_rect.left,
6099 workarea_rect.bottom - workarea_rect.top);
6100 else
6101 workarea = geometry;
6102 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6104 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6106 return list1 (attributes);
6109 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
6110 Sw32_display_monitor_attributes_list,
6111 0, 1, 0,
6112 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
6114 The optional argument DISPLAY specifies which display to ask about.
6115 DISPLAY should be either a frame or a display name (a string).
6116 If omitted or nil, that stands for the selected frame's display.
6118 Internal use only, use `display-monitor-attributes-list' instead. */)
6119 (Lisp_Object display)
6121 struct w32_display_info *dpyinfo = check_x_display_info (display);
6122 Lisp_Object attributes_list;
6124 block_input ();
6125 attributes_list = w32_display_monitor_attributes_list ();
6126 if (NILP (attributes_list))
6127 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
6128 unblock_input ();
6130 return attributes_list;
6133 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
6134 doc: /* Set the sound generated when the bell is rung.
6135 SOUND is `asterisk', `exclamation', `hand', `question', `ok', or `silent'
6136 to use the corresponding system sound for the bell. The `silent' sound
6137 prevents Emacs from making any sound at all.
6138 SOUND is nil to use the normal beep. */)
6139 (Lisp_Object sound)
6141 CHECK_SYMBOL (sound);
6143 if (NILP (sound))
6144 sound_type = 0xFFFFFFFF;
6145 else if (EQ (sound, intern ("asterisk")))
6146 sound_type = MB_ICONASTERISK;
6147 else if (EQ (sound, intern ("exclamation")))
6148 sound_type = MB_ICONEXCLAMATION;
6149 else if (EQ (sound, intern ("hand")))
6150 sound_type = MB_ICONHAND;
6151 else if (EQ (sound, intern ("question")))
6152 sound_type = MB_ICONQUESTION;
6153 else if (EQ (sound, intern ("ok")))
6154 sound_type = MB_OK;
6155 else if (EQ (sound, intern ("silent")))
6156 sound_type = MB_EMACS_SILENT;
6157 else
6158 sound_type = 0xFFFFFFFF;
6160 return sound;
6163 #if 0 /* unused */
6165 x_screen_planes (register struct frame *f)
6167 return FRAME_DISPLAY_INFO (f)->n_planes;
6169 #endif
6171 /* Return the display structure for the display named NAME.
6172 Open a new connection if necessary. */
6174 struct w32_display_info *
6175 x_display_info_for_name (Lisp_Object name)
6177 struct w32_display_info *dpyinfo;
6179 CHECK_STRING (name);
6181 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
6182 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
6183 return dpyinfo;
6185 /* Use this general default value to start with. */
6186 Vx_resource_name = Vinvocation_name;
6188 validate_x_resource_name ();
6190 dpyinfo = w32_term_init (name, NULL, SSDATA (Vx_resource_name));
6192 if (dpyinfo == 0)
6193 error ("Cannot connect to server %s", SDATA (name));
6195 XSETFASTINT (Vwindow_system_version, w32_major_version);
6197 return dpyinfo;
6200 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6201 1, 3, 0, doc: /* Open a connection to a display server.
6202 DISPLAY is the name of the display to connect to.
6203 Optional second arg XRM-STRING is a string of resources in xrdb format.
6204 If the optional third arg MUST-SUCCEED is non-nil,
6205 terminate Emacs if we can't open the connection.
6206 \(In the Nextstep version, the last two arguments are currently ignored.) */)
6207 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
6209 char *xrm_option;
6210 struct w32_display_info *dpyinfo;
6212 CHECK_STRING (display);
6214 /* Signal an error in order to encourage correct use from callers.
6215 * If we ever support multiple window systems in the same Emacs,
6216 * we'll need callers to be precise about what window system they
6217 * want. */
6219 if (strcmp (SSDATA (display), "w32") != 0)
6220 error ("The name of the display in this Emacs must be \"w32\"");
6222 /* If initialization has already been done, return now to avoid
6223 overwriting critical parts of one_w32_display_info. */
6224 if (window_system_available (NULL))
6225 return Qnil;
6227 if (! NILP (xrm_string))
6228 CHECK_STRING (xrm_string);
6230 /* Allow color mapping to be defined externally; first look in user's
6231 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6233 Lisp_Object color_file;
6235 color_file = build_string ("~/rgb.txt");
6237 if (NILP (Ffile_readable_p (color_file)))
6238 color_file =
6239 Fexpand_file_name (build_string ("rgb.txt"),
6240 Fsymbol_value (intern ("data-directory")));
6242 Vw32_color_map = Fx_load_color_file (color_file);
6244 if (NILP (Vw32_color_map))
6245 Vw32_color_map = w32_default_color_map ();
6247 /* Merge in system logical colors. */
6248 add_system_logical_colors_to_map (&Vw32_color_map);
6250 if (! NILP (xrm_string))
6251 xrm_option = SSDATA (xrm_string);
6252 else
6253 xrm_option = NULL;
6255 /* Use this general default value to start with. */
6256 /* First remove .exe suffix from invocation-name - it looks ugly. */
6258 char basename[ MAX_PATH ], *str;
6260 lispstpcpy (basename, Vinvocation_name);
6261 str = strrchr (basename, '.');
6262 if (str) *str = 0;
6263 Vinvocation_name = build_string (basename);
6265 Vx_resource_name = Vinvocation_name;
6267 validate_x_resource_name ();
6269 /* This is what opens the connection and sets x_current_display.
6270 This also initializes many symbols, such as those used for input. */
6271 dpyinfo = w32_term_init (display, xrm_option, SSDATA (Vx_resource_name));
6273 if (dpyinfo == 0)
6275 if (!NILP (must_succeed))
6276 fatal ("Cannot connect to server %s.\n",
6277 SDATA (display));
6278 else
6279 error ("Cannot connect to server %s", SDATA (display));
6282 XSETFASTINT (Vwindow_system_version, w32_major_version);
6283 return Qnil;
6286 DEFUN ("x-close-connection", Fx_close_connection,
6287 Sx_close_connection, 1, 1, 0,
6288 doc: /* Close the connection to DISPLAY's server.
6289 For DISPLAY, specify either a frame or a display name (a string).
6290 If DISPLAY is nil, that stands for the selected frame's display. */)
6291 (Lisp_Object display)
6293 struct w32_display_info *dpyinfo = check_x_display_info (display);
6295 if (dpyinfo->reference_count > 0)
6296 error ("Display still has frames on it");
6298 block_input ();
6299 x_destroy_all_bitmaps (dpyinfo);
6301 x_delete_display (dpyinfo);
6302 unblock_input ();
6304 return Qnil;
6307 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6308 doc: /* Return the list of display names that Emacs has connections to. */)
6309 (void)
6311 Lisp_Object result = Qnil;
6312 struct w32_display_info *wdi;
6314 for (wdi = x_display_list; wdi; wdi = wdi->next)
6315 result = Fcons (XCAR (wdi->name_list_element), result);
6317 return result;
6320 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6321 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
6322 This function only has an effect on X Windows. With MS Windows, it is
6323 defined but does nothing.
6325 If ON is nil, allow buffering of requests.
6326 Turning on synchronization prohibits the Xlib routines from buffering
6327 requests and seriously degrades performance, but makes debugging much
6328 easier.
6329 The optional second argument TERMINAL specifies which display to act on.
6330 TERMINAL should be a terminal object, a frame or a display name (a string).
6331 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
6332 (Lisp_Object on, Lisp_Object display)
6334 return Qnil;
6339 /***********************************************************************
6340 Window properties
6341 ***********************************************************************/
6343 #if 0 /* TODO : port window properties to W32 */
6345 DEFUN ("x-change-window-property", Fx_change_window_property,
6346 Sx_change_window_property, 2, 6, 0,
6347 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6348 PROP must be a string. VALUE may be a string or a list of conses,
6349 numbers and/or strings. If an element in the list is a string, it is
6350 converted to an atom and the value of the Atom is used. If an element
6351 is a cons, it is converted to a 32 bit number where the car is the 16
6352 top bits and the cdr is the lower 16 bits.
6354 FRAME nil or omitted means use the selected frame.
6355 If TYPE is given and non-nil, it is the name of the type of VALUE.
6356 If TYPE is not given or nil, the type is STRING.
6357 FORMAT gives the size in bits of each element if VALUE is a list.
6358 It must be one of 8, 16 or 32.
6359 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6360 If OUTER-P is non-nil, the property is changed for the outer X window of
6361 FRAME. Default is to change on the edit X window. */)
6362 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6363 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6365 struct frame *f = decode_window_system_frame (frame);
6366 Atom prop_atom;
6368 CHECK_STRING (prop);
6369 CHECK_STRING (value);
6371 block_input ();
6372 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6373 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6374 prop_atom, XA_STRING, 8, PropModeReplace,
6375 SDATA (value), SCHARS (value));
6377 /* Make sure the property is set when we return. */
6378 XFlush (FRAME_W32_DISPLAY (f));
6379 unblock_input ();
6381 return value;
6385 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6386 Sx_delete_window_property, 1, 2, 0,
6387 doc: /* Remove window property PROP from X window of FRAME.
6388 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6389 (Lisp_Object prop, Lisp_Object frame)
6391 struct frame *f = decode_window_system_frame (frame);
6392 Atom prop_atom;
6394 CHECK_STRING (prop);
6395 block_input ();
6396 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6397 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6399 /* Make sure the property is removed when we return. */
6400 XFlush (FRAME_W32_DISPLAY (f));
6401 unblock_input ();
6403 return prop;
6407 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6408 1, 6, 0,
6409 doc: /* Value is the value of window property PROP on FRAME.
6410 If FRAME is nil or omitted, use the selected frame.
6412 On X Windows, the following optional arguments are also accepted:
6413 If TYPE is nil or omitted, get the property as a string.
6414 Otherwise TYPE is the name of the atom that denotes the type expected.
6415 If SOURCE is non-nil, get the property on that window instead of from
6416 FRAME. The number 0 denotes the root window.
6417 If DELETE-P is non-nil, delete the property after retrieving it.
6418 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6420 On MS Windows, this function accepts but ignores those optional arguments.
6422 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6423 no value of TYPE (always string in the MS Windows case). */)
6424 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6425 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6427 struct frame *f = decode_window_system_frame (frame);
6428 Atom prop_atom;
6429 int rc;
6430 Lisp_Object prop_value = Qnil;
6431 char *tmp_data = NULL;
6432 Atom actual_type;
6433 int actual_format;
6434 unsigned long actual_size, bytes_remaining;
6436 CHECK_STRING (prop);
6437 block_input ();
6438 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6439 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6440 prop_atom, 0, 0, False, XA_STRING,
6441 &actual_type, &actual_format, &actual_size,
6442 &bytes_remaining, (unsigned char **) &tmp_data);
6443 if (rc == Success)
6445 int size = bytes_remaining;
6447 XFree (tmp_data);
6448 tmp_data = NULL;
6450 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6451 prop_atom, 0, bytes_remaining,
6452 False, XA_STRING,
6453 &actual_type, &actual_format,
6454 &actual_size, &bytes_remaining,
6455 (unsigned char **) &tmp_data);
6456 if (rc == Success)
6457 prop_value = make_string (tmp_data, size);
6459 XFree (tmp_data);
6462 unblock_input ();
6464 return prop_value;
6466 return Qnil;
6469 #endif /* TODO */
6471 /***********************************************************************
6472 Tool tips
6473 ***********************************************************************/
6475 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6476 Lisp_Object, int, int, int *, int *);
6478 /* The frame of a currently visible tooltip. */
6480 Lisp_Object tip_frame;
6482 /* If non-nil, a timer started that hides the last tooltip when it
6483 fires. */
6485 Lisp_Object tip_timer;
6486 Window tip_window;
6488 /* If non-nil, a vector of 3 elements containing the last args
6489 with which x-show-tip was called. See there. */
6491 Lisp_Object last_show_tip_args;
6494 static void
6495 unwind_create_tip_frame (Lisp_Object frame)
6497 Lisp_Object deleted;
6499 deleted = unwind_create_frame (frame);
6500 if (EQ (deleted, Qt))
6502 tip_window = NULL;
6503 tip_frame = Qnil;
6508 /* Create a frame for a tooltip on the display described by DPYINFO.
6509 PARMS is a list of frame parameters. Value is the frame.
6511 Note that functions called here, esp. x_default_parameter can
6512 signal errors, for instance when a specified color name is
6513 undefined. We have to make sure that we're in a consistent state
6514 when this happens. */
6516 static Lisp_Object
6517 x_create_tip_frame (struct w32_display_info *dpyinfo, Lisp_Object parms)
6519 struct frame *f;
6520 Lisp_Object frame;
6521 Lisp_Object name;
6522 int width, height;
6523 ptrdiff_t count = SPECPDL_INDEX ();
6524 struct kboard *kb;
6525 bool face_change_before = face_change;
6526 int x_width = 0, x_height = 0;
6528 /* Use this general default value to start with until we know if
6529 this frame has a specified name. */
6530 Vx_resource_name = Vinvocation_name;
6532 kb = dpyinfo->terminal->kboard;
6534 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6535 avoid destructive changes behind our caller's back. */
6536 parms = Fcopy_alist (parms);
6538 /* Get the name of the frame to use for resource lookup. */
6539 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6540 if (!STRINGP (name)
6541 && !EQ (name, Qunbound)
6542 && !NILP (name))
6543 error ("Invalid frame name--not a string or nil");
6544 Vx_resource_name = name;
6546 frame = Qnil;
6547 /* Make a frame without minibuffer nor mode-line. */
6548 f = make_frame (false);
6549 f->wants_modeline = false;
6550 XSETFRAME (frame, f);
6552 record_unwind_protect (unwind_create_tip_frame, frame);
6554 /* By setting the output method, we're essentially saying that
6555 the frame is live, as per FRAME_LIVE_P. If we get a signal
6556 from this point on, x_destroy_window might screw up reference
6557 counts etc. */
6558 f->terminal = dpyinfo->terminal;
6559 f->output_method = output_w32;
6560 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6562 FRAME_FONTSET (f) = -1;
6563 fset_icon_name (f, Qnil);
6565 #ifdef GLYPH_DEBUG
6566 image_cache_refcount =
6567 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6568 dpyinfo_refcount = dpyinfo->reference_count;
6569 #endif /* GLYPH_DEBUG */
6570 FRAME_KBOARD (f) = kb;
6571 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6572 f->output_data.w32->explicit_parent = false;
6574 /* Set the name; the functions to which we pass f expect the name to
6575 be set. */
6576 if (EQ (name, Qunbound) || NILP (name))
6578 fset_name (f, build_string (dpyinfo->w32_id_name));
6579 f->explicit_name = false;
6581 else
6583 fset_name (f, name);
6584 f->explicit_name = true;
6585 /* Use the frame's title when getting resources for this frame. */
6586 specbind (Qx_resource_name, name);
6589 if (uniscribe_available)
6590 register_font_driver (&uniscribe_font_driver, f);
6591 register_font_driver (&w32font_driver, f);
6593 x_default_parameter (f, parms, Qfont_backend, Qnil,
6594 "fontBackend", "FontBackend", RES_TYPE_STRING);
6596 /* Extract the window parameters from the supplied values
6597 that are needed to determine window geometry. */
6598 x_default_font_parameter (f, parms);
6600 x_default_parameter (f, parms, Qborder_width, make_number (2),
6601 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6602 /* This defaults to 2 in order to match xterm. We recognize either
6603 internalBorderWidth or internalBorder (which is what xterm calls
6604 it). */
6605 if (NILP (Fassq (Qinternal_border_width, parms)))
6607 Lisp_Object value;
6609 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6610 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
6611 if (! EQ (value, Qunbound))
6612 parms = Fcons (Fcons (Qinternal_border_width, value),
6613 parms);
6616 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6617 "internalBorderWidth", "internalBorderWidth",
6618 RES_TYPE_NUMBER);
6619 /* Also do the stuff which must be set before the window exists. */
6620 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6621 "foreground", "Foreground", RES_TYPE_STRING);
6622 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6623 "background", "Background", RES_TYPE_STRING);
6624 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6625 "pointerColor", "Foreground", RES_TYPE_STRING);
6626 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6627 "cursorColor", "Foreground", RES_TYPE_STRING);
6628 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6629 "borderColor", "BorderColor", RES_TYPE_STRING);
6631 /* Init faces before x_default_parameter is called for the
6632 scroll-bar-width parameter because otherwise we end up in
6633 init_iterator with a null face cache, which should not happen. */
6634 init_frame_faces (f);
6636 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6637 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6639 x_figure_window_size (f, parms, true, &x_width, &x_height);
6641 /* No fringes on tip frame. */
6642 f->fringe_cols = 0;
6643 f->left_fringe_width = 0;
6644 f->right_fringe_width = 0;
6645 /* No dividers on tip frame. */
6646 f->right_divider_width = 0;
6647 f->bottom_divider_width = 0;
6649 block_input ();
6650 my_create_tip_window (f);
6651 unblock_input ();
6653 x_make_gc (f);
6655 x_default_parameter (f, parms, Qauto_raise, Qnil,
6656 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6657 x_default_parameter (f, parms, Qauto_lower, Qnil,
6658 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6659 x_default_parameter (f, parms, Qcursor_type, Qbox,
6660 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6661 /* Process alpha here (Bug#17344). */
6662 x_default_parameter (f, parms, Qalpha, Qnil,
6663 "alpha", "Alpha", RES_TYPE_NUMBER);
6665 /* Dimensions, especially FRAME_LINES (f), must be done via
6666 change_frame_size. Change will not be effected unless different
6667 from the current FRAME_LINES (f). */
6668 width = FRAME_COLS (f);
6669 height = FRAME_LINES (f);
6670 SET_FRAME_COLS (f, 0);
6671 SET_FRAME_LINES (f, 0);
6672 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
6673 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
6674 /* Add `tooltip' frame parameter's default value. */
6675 if (NILP (Fframe_parameter (frame, Qtooltip)))
6676 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
6678 /* Set up faces after all frame parameters are known. This call
6679 also merges in face attributes specified for new frames.
6681 Frame parameters may be changed if .Xdefaults contains
6682 specifications for the default font. For example, if there is an
6683 `Emacs.default.attributeBackground: pink', the `background-color'
6684 attribute of the frame get's set, which let's the internal border
6685 of the tooltip frame appear in pink. Prevent this. */
6687 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
6688 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
6689 Lisp_Object colors = Qnil;
6691 call2 (Qface_set_after_frame_default, frame, Qnil);
6693 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
6694 colors = Fcons (Fcons (Qbackground_color, bg), colors);
6695 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
6696 colors = Fcons (Fcons (Qforeground_color, fg), colors);
6698 if (!NILP (colors))
6699 Fmodify_frame_parameters (frame, colors);
6702 f->no_split = true;
6704 /* Now that the frame is official, it counts as a reference to
6705 its display. */
6706 FRAME_DISPLAY_INFO (f)->reference_count++;
6707 f->terminal->reference_count++;
6709 /* It is now ok to make the frame official even if we get an error
6710 below. And the frame needs to be on Vframe_list or making it
6711 visible won't work. */
6712 Vframe_list = Fcons (frame, Vframe_list);
6713 f->can_x_set_window_size = true;
6715 /* Setting attributes of faces of the tooltip frame from resources
6716 and similar will set face_change, which leads to the
6717 clearing of all current matrices. Since this isn't necessary
6718 here, avoid it by resetting face_change to the value it
6719 had before we created the tip frame. */
6720 face_change = face_change_before;
6722 /* Discard the unwind_protect. */
6723 return unbind_to (count, frame);
6727 /* Compute where to display tip frame F. PARMS is the list of frame
6728 parameters for F. DX and DY are specified offsets from the current
6729 location of the mouse. WIDTH and HEIGHT are the width and height
6730 of the tooltip. Return coordinates relative to the root window of
6731 the display in *ROOT_X and *ROOT_Y. */
6733 static void
6734 compute_tip_xy (struct frame *f,
6735 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
6736 int width, int height, int *root_x, int *root_y)
6738 Lisp_Object left, top, right, bottom;
6739 int min_x, min_y, max_x, max_y;
6741 /* User-specified position? */
6742 left = Fcdr (Fassq (Qleft, parms));
6743 top = Fcdr (Fassq (Qtop, parms));
6744 right = Fcdr (Fassq (Qright, parms));
6745 bottom = Fcdr (Fassq (Qbottom, parms));
6747 /* Move the tooltip window where the mouse pointer is. Resize and
6748 show it. */
6749 if ((!INTEGERP (left) && !INTEGERP (right))
6750 || (!INTEGERP (top) && !INTEGERP (bottom)))
6752 POINT pt;
6754 /* Default min and max values. */
6755 min_x = 0;
6756 min_y = 0;
6757 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
6758 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
6760 block_input ();
6761 GetCursorPos (&pt);
6762 *root_x = pt.x;
6763 *root_y = pt.y;
6764 unblock_input ();
6766 /* If multiple monitor support is available, constrain the tip onto
6767 the current monitor. This improves the above by allowing negative
6768 co-ordinates if monitor positions are such that they are valid, and
6769 snaps a tooltip onto a single monitor if we are close to the edge
6770 where it would otherwise flow onto the other monitor (or into
6771 nothingness if there is a gap in the overlap). */
6772 if (monitor_from_point_fn && get_monitor_info_fn)
6774 struct MONITOR_INFO info;
6775 HMONITOR monitor
6776 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
6777 info.cbSize = sizeof (info);
6779 if (get_monitor_info_fn (monitor, &info))
6781 min_x = info.rcWork.left;
6782 min_y = info.rcWork.top;
6783 max_x = info.rcWork.right;
6784 max_y = info.rcWork.bottom;
6789 if (INTEGERP (top))
6790 *root_y = XINT (top);
6791 else if (INTEGERP (bottom))
6792 *root_y = XINT (bottom) - height;
6793 else if (*root_y + XINT (dy) <= min_y)
6794 *root_y = min_y; /* Can happen for negative dy */
6795 else if (*root_y + XINT (dy) + height <= max_y)
6796 /* It fits below the pointer */
6797 *root_y += XINT (dy);
6798 else if (height + XINT (dy) + min_y <= *root_y)
6799 /* It fits above the pointer. */
6800 *root_y -= height + XINT (dy);
6801 else
6802 /* Put it on the top. */
6803 *root_y = min_y;
6805 if (INTEGERP (left))
6806 *root_x = XINT (left);
6807 else if (INTEGERP (right))
6808 *root_x = XINT (right) - width;
6809 else if (*root_x + XINT (dx) <= min_x)
6810 *root_x = 0; /* Can happen for negative dx */
6811 else if (*root_x + XINT (dx) + width <= max_x)
6812 /* It fits to the right of the pointer. */
6813 *root_x += XINT (dx);
6814 else if (width + XINT (dx) + min_x <= *root_x)
6815 /* It fits to the left of the pointer. */
6816 *root_x -= width + XINT (dx);
6817 else
6818 /* Put it left justified on the screen -- it ought to fit that way. */
6819 *root_x = min_x;
6822 /* Hide tooltip. Delete its frame if DELETE is true. */
6823 static Lisp_Object
6824 x_hide_tip (bool delete)
6826 if (!NILP (tip_timer))
6828 call1 (Qcancel_timer, tip_timer);
6829 tip_timer = Qnil;
6832 if (NILP (tip_frame)
6833 || (!delete && FRAMEP (tip_frame)
6834 && !FRAME_VISIBLE_P (XFRAME (tip_frame))))
6835 return Qnil;
6836 else
6838 ptrdiff_t count;
6839 Lisp_Object was_open = Qnil;
6841 count = SPECPDL_INDEX ();
6842 specbind (Qinhibit_redisplay, Qt);
6843 specbind (Qinhibit_quit, Qt);
6845 if (FRAMEP (tip_frame))
6847 if (delete)
6849 delete_frame (tip_frame, Qnil);
6850 tip_frame = Qnil;
6852 else
6853 x_make_frame_invisible (XFRAME (tip_frame));
6855 was_open = Qt;
6857 else
6858 tip_frame = Qnil;
6860 return unbind_to (count, was_open);
6865 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
6866 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
6867 A tooltip window is a small window displaying a string.
6869 This is an internal function; Lisp code should call `tooltip-show'.
6871 FRAME nil or omitted means use the selected frame.
6873 PARMS is an optional list of frame parameters which can be
6874 used to change the tooltip's appearance.
6876 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6877 means use the default timeout of 5 seconds.
6879 If the list of frame parameters PARMS contains a `left' parameter,
6880 display the tooltip at that x-position. If the list of frame parameters
6881 PARMS contains no `left' but a `right' parameter, display the tooltip
6882 right-adjusted at that x-position. Otherwise display it at the
6883 x-position of the mouse, with offset DX added (default is 5 if DX isn't
6884 specified).
6886 Likewise for the y-position: If a `top' frame parameter is specified, it
6887 determines the position of the upper edge of the tooltip window. If a
6888 `bottom' parameter but no `top' frame parameter is specified, it
6889 determines the position of the lower edge of the tooltip window.
6890 Otherwise display the tooltip window at the y-position of the mouse,
6891 with offset DY added (default is -10).
6893 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6894 Text larger than the specified size is clipped. */)
6895 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6897 struct frame *tip_f;
6898 struct window *w;
6899 int root_x, root_y;
6900 struct buffer *old_buffer;
6901 struct text_pos pos;
6902 int width, height;
6903 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6904 ptrdiff_t count = SPECPDL_INDEX ();
6905 ptrdiff_t count_1;
6906 Lisp_Object window, size;
6907 AUTO_STRING (tip, " *tip*");
6909 specbind (Qinhibit_redisplay, Qt);
6911 CHECK_STRING (string);
6912 decode_window_system_frame (frame);
6913 if (NILP (timeout))
6914 timeout = make_number (5);
6915 else
6916 CHECK_NATNUM (timeout);
6918 if (NILP (dx))
6919 dx = make_number (5);
6920 else
6921 CHECK_NUMBER (dx);
6923 if (NILP (dy))
6924 dy = make_number (-10);
6925 else
6926 CHECK_NUMBER (dy);
6928 if (NILP (last_show_tip_args))
6929 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6931 if (FRAMEP (tip_frame) && FRAME_LIVE_P (XFRAME (tip_frame)))
6933 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6934 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6935 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6937 if (FRAME_VISIBLE_P (XFRAME (tip_frame))
6938 && EQ (frame, last_frame)
6939 && !NILP (Fequal_including_properties (last_string, string))
6940 && !NILP (Fequal (last_parms, parms)))
6942 /* Only DX and DY have changed. */
6943 tip_f = XFRAME (tip_frame);
6944 if (!NILP (tip_timer))
6946 Lisp_Object timer = tip_timer;
6948 tip_timer = Qnil;
6949 call1 (Qcancel_timer, timer);
6952 block_input ();
6953 compute_tip_xy (tip_f, parms, dx, dy, FRAME_PIXEL_WIDTH (tip_f),
6954 FRAME_PIXEL_HEIGHT (tip_f), &root_x, &root_y);
6956 /* Put tooltip in topmost group and in position. */
6957 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
6958 root_x, root_y, 0, 0,
6959 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6961 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6962 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
6963 0, 0, 0, 0,
6964 SWP_NOMOVE | SWP_NOSIZE
6965 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6967 /* Let redisplay know that we have made the frame visible already. */
6968 SET_FRAME_VISIBLE (tip_f, 1);
6969 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
6970 unblock_input ();
6972 goto start_timer;
6974 else if (tooltip_reuse_hidden_frame && EQ (frame, last_frame))
6976 bool delete = false;
6977 Lisp_Object tail, elt, parm, last;
6979 /* Check if every parameter in PARMS has the same value in
6980 last_parms. This may destruct last_parms which, however,
6981 will be recreated below. */
6982 for (tail = parms; CONSP (tail); tail = XCDR (tail))
6984 elt = XCAR (tail);
6985 parm = Fcar (elt);
6986 /* The left, top, right and bottom parameters are handled
6987 by compute_tip_xy so they can be ignored here. */
6988 if (!EQ (parm, Qleft) && !EQ (parm, Qtop)
6989 && !EQ (parm, Qright) && !EQ (parm, Qbottom))
6991 last = Fassq (parm, last_parms);
6992 if (NILP (Fequal (Fcdr (elt), Fcdr (last))))
6994 /* We lost, delete the old tooltip. */
6995 delete = true;
6996 break;
6998 else
6999 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7001 else
7002 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7005 /* Now check if there's a parameter left in last_parms with a
7006 non-nil value. */
7007 for (tail = last_parms; CONSP (tail); tail = XCDR (tail))
7009 elt = XCAR (tail);
7010 parm = Fcar (elt);
7011 if (!EQ (parm, Qleft) && !EQ (parm, Qtop) && !EQ (parm, Qright)
7012 && !EQ (parm, Qbottom) && !NILP (Fcdr (elt)))
7014 /* We lost, delete the old tooltip. */
7015 delete = true;
7016 break;
7020 x_hide_tip (delete);
7022 else
7023 x_hide_tip (true);
7025 else
7026 x_hide_tip (true);
7028 ASET (last_show_tip_args, 0, string);
7029 ASET (last_show_tip_args, 1, frame);
7030 ASET (last_show_tip_args, 2, parms);
7032 /* Block input until the tip has been fully drawn, to avoid crashes
7033 when drawing tips in menus. */
7034 block_input ();
7036 if (!FRAMEP (tip_frame) || !FRAME_LIVE_P (XFRAME (tip_frame)))
7038 /* Add default values to frame parameters. */
7039 if (NILP (Fassq (Qname, parms)))
7040 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7041 if (NILP (Fassq (Qinternal_border_width, parms)))
7042 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7043 if (NILP (Fassq (Qborder_width, parms)))
7044 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7045 if (NILP (Fassq (Qborder_color, parms)))
7046 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7047 if (NILP (Fassq (Qbackground_color, parms)))
7048 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7049 parms);
7051 /* Create a frame for the tooltip, and record it in the global
7052 variable tip_frame. */
7053 struct frame *f; /* The value is unused. */
7054 if (NILP (tip_frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms)))
7056 /* Creating the tip frame failed. */
7057 unblock_input ();
7058 return unbind_to (count, Qnil);
7062 tip_f = XFRAME (tip_frame);
7063 window = FRAME_ROOT_WINDOW (tip_f);
7064 set_window_buffer (window, Fget_buffer_create (tip), false, false);
7065 w = XWINDOW (window);
7066 w->pseudo_window_p = true;
7068 /* Set up the frame's root window. Note: The following code does not
7069 try to size the window or its frame correctly. Its only purpose is
7070 to make the subsequent text size calculations work. The right
7071 sizes should get installed when the toolkit gets back to us. */
7072 w->left_col = 0;
7073 w->top_line = 0;
7074 w->pixel_left = 0;
7075 w->pixel_top = 0;
7077 if (CONSP (Vx_max_tooltip_size)
7078 && RANGED_INTEGERP (1, XCAR (Vx_max_tooltip_size), INT_MAX)
7079 && RANGED_INTEGERP (1, XCDR (Vx_max_tooltip_size), INT_MAX))
7081 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
7082 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
7084 else
7086 w->total_cols = 80;
7087 w->total_lines = 40;
7090 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (tip_f);
7091 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (tip_f);
7092 FRAME_TOTAL_COLS (tip_f) = WINDOW_TOTAL_COLS (w);
7093 adjust_frame_glyphs (tip_f);
7095 /* Insert STRING into the root window's buffer and fit the frame to
7096 the buffer. */
7097 count_1 = SPECPDL_INDEX ();
7098 old_buffer = current_buffer;
7099 set_buffer_internal_1 (XBUFFER (w->contents));
7100 bset_truncate_lines (current_buffer, Qnil);
7101 specbind (Qinhibit_read_only, Qt);
7102 specbind (Qinhibit_modification_hooks, Qt);
7103 specbind (Qinhibit_point_motion_hooks, Qt);
7104 Ferase_buffer ();
7105 Finsert (1, &string);
7106 clear_glyph_matrix (w->desired_matrix);
7107 clear_glyph_matrix (w->current_matrix);
7108 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7109 try_window (window, pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
7110 /* Calculate size of tooltip window. */
7111 size = Fwindow_text_pixel_size (window, Qnil, Qnil, Qnil,
7112 make_number (w->pixel_height), Qnil);
7113 /* Add the frame's internal border to calculated size. */
7114 width = XINT (Fcar (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7115 height = XINT (Fcdr (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7116 /* Calculate position of tooltip frame. */
7117 compute_tip_xy (tip_f, parms, dx, dy, width, height, &root_x, &root_y);
7119 /* Show tooltip frame. */
7121 RECT rect;
7122 int pad = (NUMBERP (Vw32_tooltip_extra_pixels)
7123 ? max (0, XINT (Vw32_tooltip_extra_pixels))
7124 : FRAME_COLUMN_WIDTH (tip_f));
7126 rect.left = rect.top = 0;
7127 rect.right = width;
7128 rect.bottom = height;
7129 AdjustWindowRect (&rect, tip_f->output_data.w32->dwStyle,
7130 FRAME_EXTERNAL_MENU_BAR (tip_f));
7132 /* Position and size tooltip and put it in the topmost group. */
7133 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7134 root_x, root_y,
7135 rect.right - rect.left + pad,
7136 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7138 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7139 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7140 0, 0, 0, 0,
7141 SWP_NOMOVE | SWP_NOSIZE
7142 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7144 /* Let redisplay know that we have made the frame visible already. */
7145 SET_FRAME_VISIBLE (tip_f, 1);
7147 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7150 w->must_be_updated_p = true;
7151 update_single_window (w);
7152 set_buffer_internal_1 (old_buffer);
7153 unbind_to (count_1, Qnil);
7154 unblock_input ();
7155 windows_or_buffers_changed = old_windows_or_buffers_changed;
7157 start_timer:
7158 /* Let the tip disappear after timeout seconds. */
7159 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7160 intern ("x-hide-tip"));
7162 return unbind_to (count, Qnil);
7166 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7167 doc: /* Hide the current tooltip window, if there is any.
7168 Value is t if tooltip was open, nil otherwise. */)
7169 (void)
7171 return x_hide_tip (!tooltip_reuse_hidden_frame);
7174 /***********************************************************************
7175 File selection dialog
7176 ***********************************************************************/
7178 #define FILE_NAME_TEXT_FIELD edt1
7179 #define FILE_NAME_COMBO_BOX cmb13
7180 #define FILE_NAME_LIST lst1
7182 /* Callback for altering the behavior of the Open File dialog.
7183 Makes the Filename text field contain "Current Directory" and be
7184 read-only when "Directories" is selected in the filter. This
7185 allows us to work around the fact that the standard Open File
7186 dialog does not support directories. */
7187 static UINT_PTR CALLBACK
7188 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
7190 if (msg == WM_NOTIFY)
7192 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
7193 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
7194 int dropdown_changed;
7195 int dir_index;
7196 #ifdef NTGUI_UNICODE
7197 const int use_unicode = 1;
7198 #else /* !NTGUI_UNICODE */
7199 int use_unicode = w32_unicode_filenames;
7200 #endif /* NTGUI_UNICODE */
7202 /* Detect when the Filter dropdown is changed. */
7203 if (use_unicode)
7204 dropdown_changed =
7205 notify_w->hdr.code == CDN_TYPECHANGE
7206 || notify_w->hdr.code == CDN_INITDONE;
7207 else
7208 dropdown_changed =
7209 notify_a->hdr.code == CDN_TYPECHANGE
7210 || notify_a->hdr.code == CDN_INITDONE;
7211 if (dropdown_changed)
7213 HWND dialog = GetParent (hwnd);
7214 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7215 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
7216 int hdr_code;
7218 /* At least on Windows 7, the above attempt to get the window handle
7219 to the File Name Text Field fails. The following code does the
7220 job though. Note that this code is based on my examination of the
7221 window hierarchy using Microsoft Spy++. bk */
7222 if (edit_control == NULL)
7224 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
7225 if (tmp)
7227 tmp = GetWindow (tmp, GW_CHILD);
7228 if (tmp)
7229 edit_control = GetWindow (tmp, GW_CHILD);
7233 /* Directories is in index 2. */
7234 if (use_unicode)
7236 dir_index = notify_w->lpOFN->nFilterIndex;
7237 hdr_code = notify_w->hdr.code;
7239 else
7241 dir_index = notify_a->lpOFN->nFilterIndex;
7242 hdr_code = notify_a->hdr.code;
7244 if (dir_index == 2)
7246 if (use_unicode)
7247 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7248 (LPARAM)L"Current Directory");
7249 else
7250 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7251 (LPARAM)"Current Directory");
7252 EnableWindow (edit_control, FALSE);
7253 /* Note that at least on Windows 7, the above call to EnableWindow
7254 disables the window that would ordinarily have focus. If we
7255 do not set focus to some other window here, focus will land in
7256 no man's land and the user will be unable to tab through the
7257 dialog box (pressing tab will only result in a beep).
7258 Avoid that problem by setting focus to the list here. */
7259 if (hdr_code == CDN_INITDONE)
7260 SetFocus (list);
7262 else
7264 /* Don't override default filename on init done. */
7265 if (hdr_code == CDN_TYPECHANGE)
7267 if (use_unicode)
7268 SendMessageW (dialog, CDM_SETCONTROLTEXT,
7269 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
7270 else
7271 SendMessageA (dialog, CDM_SETCONTROLTEXT,
7272 FILE_NAME_TEXT_FIELD, (LPARAM)"");
7274 EnableWindow (edit_control, TRUE);
7278 return 0;
7281 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7282 doc: /* Read file name, prompting with PROMPT in directory DIR.
7283 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
7284 selection box, if specified. If MUSTMATCH is non-nil, the returned file
7285 or directory must exist.
7287 This function is only defined on NS, MS Windows, and X Windows with the
7288 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
7289 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
7290 On Windows 7 and later, the file selection dialog "remembers" the last
7291 directory where the user selected a file, and will open that directory
7292 instead of DIR on subsequent invocations of this function with the same
7293 value of DIR as in previous invocations; this is standard Windows behavior. */)
7294 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
7296 /* Filter index: 1: All Files, 2: Directories only */
7297 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
7298 #ifndef NTGUI_UNICODE
7299 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
7300 #endif
7302 Lisp_Object filename = default_filename;
7303 struct frame *f = SELECTED_FRAME ();
7304 BOOL file_opened = FALSE;
7305 Lisp_Object orig_dir = dir;
7306 Lisp_Object orig_prompt = prompt;
7308 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
7309 compatibility) we end up with the old file dialogs. Define a big
7310 enough struct for the new dialog to trick GetOpenFileName into
7311 giving us the new dialogs on newer versions of Windows. */
7312 struct {
7313 OPENFILENAMEW details;
7314 #if _WIN32_WINNT < 0x500 /* < win2k */
7315 PVOID pvReserved;
7316 DWORD dwReserved;
7317 DWORD FlagsEx;
7318 #endif /* < win2k */
7319 } new_file_details_w;
7321 #ifdef NTGUI_UNICODE
7322 wchar_t filename_buf_w[32*1024 + 1]; /* NT kernel maximum */
7323 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7324 const int use_unicode = 1;
7325 #else /* not NTGUI_UNICODE */
7326 struct {
7327 OPENFILENAMEA details;
7328 #if _WIN32_WINNT < 0x500 /* < win2k */
7329 PVOID pvReserved;
7330 DWORD dwReserved;
7331 DWORD FlagsEx;
7332 #endif /* < win2k */
7333 } new_file_details_a;
7334 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7335 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7336 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7337 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7338 int use_unicode = w32_unicode_filenames;
7339 wchar_t *prompt_w;
7340 char *prompt_a;
7341 int len;
7342 char fname_ret[MAX_UTF8_PATH];
7343 #endif /* NTGUI_UNICODE */
7346 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7347 system file encoding expected by the platform APIs (e.g. Cygwin's
7348 POSIX implementation) may not be the same as the encoding expected
7349 by the Windows "ANSI" APIs! */
7351 CHECK_STRING (prompt);
7352 CHECK_STRING (dir);
7354 dir = Fexpand_file_name (dir, Qnil);
7356 if (STRINGP (filename))
7357 filename = Ffile_name_nondirectory (filename);
7358 else
7359 filename = empty_unibyte_string;
7361 #ifdef CYGWIN
7362 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7363 if (SCHARS (filename) > 0)
7364 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7365 #endif
7367 CHECK_STRING (dir);
7368 CHECK_STRING (filename);
7370 /* The code in file_dialog_callback that attempts to set the text
7371 of the file name edit window when handling the CDN_INITDONE
7372 WM_NOTIFY message does not work. Setting filename to "Current
7373 Directory" in the only_dir_p case here does work however. */
7374 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7375 filename = build_string ("Current Directory");
7377 /* Convert the values we've computed so far to system form. */
7378 #ifdef NTGUI_UNICODE
7379 to_unicode (prompt, &prompt);
7380 to_unicode (dir, &dir);
7381 to_unicode (filename, &filename);
7382 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7383 report_file_error ("filename too long", default_filename);
7385 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7386 #else /* !NTGUI_UNICODE */
7387 prompt = ENCODE_FILE (prompt);
7388 dir = ENCODE_FILE (dir);
7389 filename = ENCODE_FILE (filename);
7391 /* We modify these in-place, so make copies for safety. */
7392 dir = Fcopy_sequence (dir);
7393 unixtodos_filename (SSDATA (dir));
7394 filename = Fcopy_sequence (filename);
7395 unixtodos_filename (SSDATA (filename));
7396 if (SBYTES (filename) >= MAX_UTF8_PATH)
7397 report_file_error ("filename too long", default_filename);
7398 if (w32_unicode_filenames)
7400 filename_to_utf16 (SSDATA (dir), dir_w);
7401 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7403 /* filename_to_utf16 sets errno to ENOENT when the file
7404 name is too long or cannot be converted to UTF-16. */
7405 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7406 report_file_error ("filename too long", default_filename);
7408 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7409 SSDATA (prompt), -1, NULL, 0);
7410 if (len > 32768)
7411 len = 32768;
7412 prompt_w = alloca (len * sizeof (wchar_t));
7413 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7414 SSDATA (prompt), -1, prompt_w, len);
7416 else
7418 filename_to_ansi (SSDATA (dir), dir_a);
7419 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7421 /* filename_to_ansi sets errno to ENOENT when the file
7422 name is too long or cannot be converted to UTF-16. */
7423 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7424 report_file_error ("filename too long", default_filename);
7426 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7427 SSDATA (prompt), -1, NULL, 0);
7428 if (len > 32768)
7429 len = 32768;
7430 prompt_w = alloca (len * sizeof (wchar_t));
7431 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7432 SSDATA (prompt), -1, prompt_w, len);
7433 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7434 if (len > 32768)
7435 len = 32768;
7436 prompt_a = alloca (len);
7437 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7439 #endif /* NTGUI_UNICODE */
7441 /* Fill in the structure for the call to GetOpenFileName below.
7442 For NTGUI_UNICODE builds (which run only on NT), we just use
7443 the actual size of the structure. For non-NTGUI_UNICODE
7444 builds, we tell the OS we're using an old version of the
7445 structure if the OS isn't new enough to support the newer
7446 version. */
7447 if (use_unicode)
7449 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7450 if (w32_major_version > 4 && w32_major_version < 95)
7451 file_details_w->lStructSize = sizeof (new_file_details_w);
7452 else
7453 file_details_w->lStructSize = sizeof (*file_details_w);
7454 /* Set up the inout parameter for the selected file name. */
7455 file_details_w->lpstrFile = filename_buf_w;
7456 file_details_w->nMaxFile =
7457 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7458 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7459 /* Undocumented Bug in Common File Dialog:
7460 If a filter is not specified, shell links are not resolved. */
7461 file_details_w->lpstrFilter = filter_w;
7462 #ifdef NTGUI_UNICODE
7463 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7464 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7465 #else
7466 file_details_w->lpstrInitialDir = dir_w;
7467 file_details_w->lpstrTitle = prompt_w;
7468 #endif
7469 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7470 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7471 | OFN_EXPLORER | OFN_ENABLEHOOK);
7472 if (!NILP (mustmatch))
7474 /* Require that the path to the parent directory exists. */
7475 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7476 /* If we are looking for a file, require that it exists. */
7477 if (NILP (only_dir_p))
7478 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7481 #ifndef NTGUI_UNICODE
7482 else
7484 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7485 if (w32_major_version > 4 && w32_major_version < 95)
7486 file_details_a->lStructSize = sizeof (new_file_details_a);
7487 else
7488 file_details_a->lStructSize = sizeof (*file_details_a);
7489 file_details_a->lpstrFile = filename_buf_a;
7490 file_details_a->nMaxFile =
7491 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7492 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7493 file_details_a->lpstrFilter = filter_a;
7494 file_details_a->lpstrInitialDir = dir_a;
7495 file_details_a->lpstrTitle = prompt_a;
7496 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7497 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7498 | OFN_EXPLORER | OFN_ENABLEHOOK);
7499 if (!NILP (mustmatch))
7501 /* Require that the path to the parent directory exists. */
7502 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7503 /* If we are looking for a file, require that it exists. */
7504 if (NILP (only_dir_p))
7505 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7508 #endif /* !NTGUI_UNICODE */
7511 int count = SPECPDL_INDEX ();
7512 /* Prevent redisplay. */
7513 specbind (Qinhibit_redisplay, Qt);
7514 block_input ();
7515 if (use_unicode)
7517 file_details_w->lpfnHook = file_dialog_callback;
7519 file_opened = GetOpenFileNameW (file_details_w);
7521 #ifndef NTGUI_UNICODE
7522 else
7524 file_details_a->lpfnHook = file_dialog_callback;
7526 file_opened = GetOpenFileNameA (file_details_a);
7528 #endif /* !NTGUI_UNICODE */
7529 unblock_input ();
7530 unbind_to (count, Qnil);
7533 if (file_opened)
7535 /* Get an Emacs string from the value Windows gave us. */
7536 #ifdef NTGUI_UNICODE
7537 filename = from_unicode_buffer (filename_buf_w);
7538 #else /* !NTGUI_UNICODE */
7539 if (use_unicode)
7540 filename_from_utf16 (filename_buf_w, fname_ret);
7541 else
7542 filename_from_ansi (filename_buf_a, fname_ret);
7543 dostounix_filename (fname_ret);
7544 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7545 #endif /* NTGUI_UNICODE */
7547 #ifdef CYGWIN
7548 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7549 #endif /* CYGWIN */
7551 /* Strip the dummy filename off the end of the string if we
7552 added it to select a directory. */
7553 if ((use_unicode && file_details_w->nFilterIndex == 2)
7554 #ifndef NTGUI_UNICODE
7555 || (!use_unicode && file_details_a->nFilterIndex == 2)
7556 #endif
7558 filename = Ffile_name_directory (filename);
7560 /* User canceled the dialog without making a selection. */
7561 else if (!CommDlgExtendedError ())
7562 filename = Qnil;
7563 /* An error occurred, fallback on reading from the mini-buffer. */
7564 else
7565 filename = Fcompleting_read (
7566 orig_prompt,
7567 intern ("read-file-name-internal"),
7568 orig_dir,
7569 mustmatch,
7570 orig_dir,
7571 Qfile_name_history,
7572 default_filename,
7573 Qnil);
7576 /* Make "Cancel" equivalent to C-g. */
7577 if (NILP (filename))
7578 quit ();
7580 return filename;
7584 #ifdef WINDOWSNT
7585 /* Moving files to the system recycle bin.
7586 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
7587 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
7588 Ssystem_move_file_to_trash, 1, 1, 0,
7589 doc: /* Move file or directory named FILENAME to the recycle bin. */)
7590 (Lisp_Object filename)
7592 Lisp_Object handler;
7593 Lisp_Object encoded_file;
7594 Lisp_Object operation;
7596 operation = Qdelete_file;
7597 if (!NILP (Ffile_directory_p (filename))
7598 && NILP (Ffile_symlink_p (filename)))
7600 operation = intern ("delete-directory");
7601 filename = Fdirectory_file_name (filename);
7604 /* Must have fully qualified file names for moving files to Recycle
7605 Bin. */
7606 filename = Fexpand_file_name (filename, Qnil);
7608 handler = Ffind_file_name_handler (filename, operation);
7609 if (!NILP (handler))
7610 return call2 (handler, operation, filename);
7611 else
7613 const char * path;
7614 int result;
7616 encoded_file = ENCODE_FILE (filename);
7618 path = map_w32_filename (SSDATA (encoded_file), NULL);
7620 /* The Unicode version of SHFileOperation is not supported on
7621 Windows 9X. */
7622 if (w32_unicode_filenames && os_subtype != OS_9X)
7624 SHFILEOPSTRUCTW file_op_w;
7625 /* We need one more element beyond MAX_PATH because this is
7626 a list of file names, with the last element double-null
7627 terminated. */
7628 wchar_t tmp_path_w[MAX_PATH + 1];
7630 memset (tmp_path_w, 0, sizeof (tmp_path_w));
7631 filename_to_utf16 (path, tmp_path_w);
7633 /* On Windows, write permission is required to delete/move files. */
7634 _wchmod (tmp_path_w, 0666);
7636 memset (&file_op_w, 0, sizeof (file_op_w));
7637 file_op_w.hwnd = HWND_DESKTOP;
7638 file_op_w.wFunc = FO_DELETE;
7639 file_op_w.pFrom = tmp_path_w;
7640 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7641 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7642 file_op_w.fAnyOperationsAborted = FALSE;
7644 result = SHFileOperationW (&file_op_w);
7646 else
7648 SHFILEOPSTRUCTA file_op_a;
7649 char tmp_path_a[MAX_PATH + 1];
7651 memset (tmp_path_a, 0, sizeof (tmp_path_a));
7652 filename_to_ansi (path, tmp_path_a);
7654 /* If a file cannot be represented in ANSI codepage, don't
7655 let them inadvertently delete other files because some
7656 characters are interpreted as a wildcards. */
7657 if (_mbspbrk ((unsigned char *)tmp_path_a,
7658 (const unsigned char *)"?*"))
7659 result = ERROR_FILE_NOT_FOUND;
7660 else
7662 _chmod (tmp_path_a, 0666);
7664 memset (&file_op_a, 0, sizeof (file_op_a));
7665 file_op_a.hwnd = HWND_DESKTOP;
7666 file_op_a.wFunc = FO_DELETE;
7667 file_op_a.pFrom = tmp_path_a;
7668 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7669 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7670 file_op_a.fAnyOperationsAborted = FALSE;
7672 result = SHFileOperationA (&file_op_a);
7675 if (result != 0)
7676 report_file_error ("Removing old name", list1 (filename));
7678 return Qnil;
7681 #endif /* WINDOWSNT */
7684 /***********************************************************************
7685 w32 specialized functions
7686 ***********************************************************************/
7688 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
7689 Sw32_send_sys_command, 1, 2, 0,
7690 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
7691 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
7692 to minimize), #xf120 to restore frame to original size, and #xf100
7693 to activate the menubar for keyboard access. #xf140 activates the
7694 screen saver if defined.
7696 If optional parameter FRAME is not specified, use selected frame. */)
7697 (Lisp_Object command, Lisp_Object frame)
7699 struct frame *f = decode_window_system_frame (frame);
7701 CHECK_NUMBER (command);
7703 if (FRAME_W32_P (f))
7704 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
7706 return Qnil;
7709 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
7710 doc: /* Get Windows to perform OPERATION on DOCUMENT.
7711 This is a wrapper around the ShellExecute system function, which
7712 invokes the application registered to handle OPERATION for DOCUMENT.
7714 OPERATION is either nil or a string that names a supported operation.
7715 What operations can be used depends on the particular DOCUMENT and its
7716 handler application, but typically it is one of the following common
7717 operations:
7719 \"open\" - open DOCUMENT, which could be a file, a directory, or an
7720 executable program (application). If it is an application,
7721 that application is launched in the current buffer's default
7722 directory. Otherwise, the application associated with
7723 DOCUMENT is launched in the buffer's default directory.
7724 \"opennew\" - like \"open\", but instruct the application to open
7725 DOCUMENT in a new window.
7726 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
7727 \"print\" - print DOCUMENT, which must be a file.
7728 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
7729 The printer should be provided in PARAMETERS, see below.
7730 \"explore\" - start the Windows Explorer on DOCUMENT.
7731 \"edit\" - launch an editor and open DOCUMENT for editing; which
7732 editor is launched depends on the association for the
7733 specified DOCUMENT.
7734 \"find\" - initiate search starting from DOCUMENT, which must specify
7735 a directory.
7736 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
7737 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
7738 the clipboard.
7739 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
7740 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
7741 which must be a directory.
7742 \"pastelink\"
7743 - create a shortcut in DOCUMENT (which must be a directory)
7744 the file or directory whose name is in the clipboard.
7745 \"runas\" - run DOCUMENT, which must be an excutable file, with
7746 elevated privileges (a.k.a. \"as Administrator\").
7747 \"properties\"
7748 - open the property sheet dialog for DOCUMENT.
7749 nil - invoke the default OPERATION, or \"open\" if default is
7750 not defined or unavailable.
7752 DOCUMENT is typically the name of a document file or a URL, but can
7753 also be an executable program to run, or a directory to open in the
7754 Windows Explorer. If it is a file or a directory, it must be a local
7755 one; this function does not support remote file names.
7757 If DOCUMENT is an executable program, the optional third arg PARAMETERS
7758 can be a string containing command line parameters, separated by blanks,
7759 that will be passed to the program. Some values of OPERATION also require
7760 parameters (e.g., \"printto\" requires the printer address). Otherwise,
7761 PARAMETERS should be nil or unspecified. Note that double quote characters
7762 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
7764 Optional fourth argument SHOW-FLAG can be used to control how the
7765 application will be displayed when it is invoked. If SHOW-FLAG is nil
7766 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
7767 specified, otherwise it is an integer between 0 and 11 representing
7768 a ShowWindow flag:
7770 0 - start hidden
7771 1 - start as normal-size window
7772 3 - start in a maximized window
7773 6 - start in a minimized window
7774 10 - start as the application itself specifies; this is the default. */)
7775 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
7777 char *errstr;
7778 Lisp_Object current_dir = BVAR (current_buffer, directory);;
7779 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
7780 #ifdef CYGWIN
7781 intptr_t result;
7782 #else
7783 int use_unicode = w32_unicode_filenames;
7784 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
7785 Lisp_Object absdoc, handler;
7786 BOOL success;
7787 #endif
7789 CHECK_STRING (document);
7791 #ifdef CYGWIN
7792 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
7793 document = Fcygwin_convert_file_name_to_windows (document, Qt);
7795 /* Encode filename, current directory and parameters. */
7796 current_dir = GUI_ENCODE_FILE (current_dir);
7797 document = GUI_ENCODE_FILE (document);
7798 doc_w = GUI_SDATA (document);
7799 if (STRINGP (parameters))
7801 parameters = GUI_ENCODE_SYSTEM (parameters);
7802 params_w = GUI_SDATA (parameters);
7804 if (STRINGP (operation))
7806 operation = GUI_ENCODE_SYSTEM (operation);
7807 ops_w = GUI_SDATA (operation);
7809 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7810 GUI_SDATA (current_dir),
7811 (INTEGERP (show_flag)
7812 ? XINT (show_flag) : SW_SHOWDEFAULT));
7814 if (result > 32)
7815 return Qt;
7817 switch (result)
7819 case SE_ERR_ACCESSDENIED:
7820 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7821 break;
7822 case SE_ERR_ASSOCINCOMPLETE:
7823 case SE_ERR_NOASSOC:
7824 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7825 break;
7826 case SE_ERR_DDEBUSY:
7827 case SE_ERR_DDEFAIL:
7828 errstr = w32_strerror (ERROR_DDE_FAIL);
7829 break;
7830 case SE_ERR_DDETIMEOUT:
7831 errstr = w32_strerror (ERROR_TIMEOUT);
7832 break;
7833 case SE_ERR_DLLNOTFOUND:
7834 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7835 break;
7836 case SE_ERR_FNF:
7837 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7838 break;
7839 case SE_ERR_OOM:
7840 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7841 break;
7842 case SE_ERR_PNF:
7843 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7844 break;
7845 case SE_ERR_SHARE:
7846 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7847 break;
7848 default:
7849 errstr = w32_strerror (0);
7850 break;
7853 #else /* !CYGWIN */
7855 const char file_url_str[] = "file:///";
7856 const int file_url_len = sizeof (file_url_str) - 1;
7857 int doclen;
7859 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
7861 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
7862 start a thread in some rare system configurations, for
7863 unknown reasons. That thread is started in the context of
7864 the Emacs process, but out of control of our code, and seems
7865 to never exit afterwards. Each such thread reserves 8MB of
7866 stack space (because that's the value recorded in the Emacs
7867 executable at link time: Emacs needs a large stack). So a
7868 large enough number of invocations of w32-shell-execute can
7869 potentially cause the Emacs process to run out of available
7870 address space, which is nasty. To work around this, we
7871 convert such URLs to local file names, which seems to prevent
7872 those threads from starting. See bug #20220. */
7873 char *p = SSDATA (document) + file_url_len;
7875 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
7876 document = Fsubstring_no_properties (document,
7877 make_number (file_url_len), Qnil);
7879 /* We have a situation here. If DOCUMENT is a relative file name,
7880 but its name includes leading directories, i.e. it lives not in
7881 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7882 will fail to find it. So we need to make the file name is
7883 absolute. But DOCUMENT does not have to be a file, it can be a
7884 URL, for example. So we make it absolute only if it is an
7885 existing file; if it is a file that does not exist, tough. */
7886 absdoc = Fexpand_file_name (document, Qnil);
7887 /* Don't call file handlers for file-exists-p, since they might
7888 attempt to access the file, which could fail or produce undesired
7889 consequences, see bug#16558 for an example. */
7890 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7891 if (NILP (handler))
7893 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7895 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7897 /* ShellExecute fails if DOCUMENT is a UNC with forward
7898 slashes (expand-file-name above converts all backslashes
7899 to forward slashes). Now that we know DOCUMENT is a
7900 file, we can mirror all forward slashes into backslashes. */
7901 unixtodos_filename (SSDATA (absdoc_encoded));
7902 document = absdoc_encoded;
7904 else
7905 document = ENCODE_FILE (document);
7907 else
7908 document = ENCODE_FILE (document);
7910 current_dir = ENCODE_FILE (current_dir);
7911 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
7912 be a URL that is not limited to MAX_PATH chararcters. */
7913 doclen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7914 SSDATA (document), -1, NULL, 0);
7915 doc_w = xmalloc (doclen * sizeof (wchar_t));
7916 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7917 SSDATA (document), -1, doc_w, doclen);
7918 if (use_unicode)
7920 wchar_t current_dir_w[MAX_PATH];
7921 SHELLEXECUTEINFOW shexinfo_w;
7923 /* Encode the current directory and parameters, and convert
7924 operation to UTF-16. */
7925 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7926 if (STRINGP (parameters))
7928 int len;
7930 parameters = ENCODE_SYSTEM (parameters);
7931 len = pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
7932 SSDATA (parameters), -1, NULL, 0);
7933 if (len > 32768)
7934 len = 32768;
7935 params_w = alloca (len * sizeof (wchar_t));
7936 pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
7937 SSDATA (parameters), -1, params_w, len);
7938 params_w[len - 1] = 0;
7940 if (STRINGP (operation))
7942 /* Assume OPERATION is pure ASCII. */
7943 const char *s = SSDATA (operation);
7944 wchar_t *d;
7945 int len = SBYTES (operation) + 1;
7947 if (len > 32768)
7948 len = 32768;
7949 d = ops_w = alloca (len * sizeof (wchar_t));
7950 while (d < ops_w + len - 1)
7951 *d++ = *s++;
7952 *d = 0;
7955 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7956 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7957 able to invoke verbs from shortcut menu extensions, not just
7958 static verbs listed in the Registry. */
7959 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7960 shexinfo_w.cbSize = sizeof (shexinfo_w);
7961 shexinfo_w.fMask =
7962 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7963 shexinfo_w.hwnd = NULL;
7964 shexinfo_w.lpVerb = ops_w;
7965 shexinfo_w.lpFile = doc_w;
7966 shexinfo_w.lpParameters = params_w;
7967 shexinfo_w.lpDirectory = current_dir_w;
7968 shexinfo_w.nShow =
7969 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7970 success = ShellExecuteExW (&shexinfo_w);
7971 xfree (doc_w);
7973 else
7975 char current_dir_a[MAX_PATH];
7976 SHELLEXECUTEINFOA shexinfo_a;
7977 int codepage = codepage_for_filenames (NULL);
7978 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
7979 NULL, NULL);
7981 doc_a = xmalloc (ldoc_a);
7982 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
7983 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7984 if (STRINGP (parameters))
7986 parameters = ENCODE_SYSTEM (parameters);
7987 params_a = SSDATA (parameters);
7989 if (STRINGP (operation))
7991 /* Assume OPERATION is pure ASCII. */
7992 ops_a = SSDATA (operation);
7994 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7995 shexinfo_a.cbSize = sizeof (shexinfo_a);
7996 shexinfo_a.fMask =
7997 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7998 shexinfo_a.hwnd = NULL;
7999 shexinfo_a.lpVerb = ops_a;
8000 shexinfo_a.lpFile = doc_a;
8001 shexinfo_a.lpParameters = params_a;
8002 shexinfo_a.lpDirectory = current_dir_a;
8003 shexinfo_a.nShow =
8004 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8005 success = ShellExecuteExA (&shexinfo_a);
8006 xfree (doc_w);
8007 xfree (doc_a);
8010 if (success)
8011 return Qt;
8013 errstr = w32_strerror (0);
8015 #endif /* !CYGWIN */
8017 /* The error string might be encoded in the locale's encoding. */
8018 if (!NILP (Vlocale_coding_system))
8020 Lisp_Object decoded =
8021 code_convert_string_norecord (build_unibyte_string (errstr),
8022 Vlocale_coding_system, 0);
8023 errstr = SSDATA (decoded);
8025 error ("ShellExecute failed: %s", errstr);
8028 /* Lookup virtual keycode from string representing the name of a
8029 non-ascii keystroke into the corresponding virtual key, using
8030 lispy_function_keys. */
8031 static int
8032 lookup_vk_code (char *key)
8034 int i;
8036 for (i = 0; i < 256; i++)
8037 if (lispy_function_keys[i]
8038 && strcmp (lispy_function_keys[i], key) == 0)
8039 return i;
8041 if (w32_kbdhook_active)
8043 /* Alphanumerics map to themselves. */
8044 if (key[1] == 0)
8046 if ((key[0] >= 'A' && key[0] <= 'Z')
8047 || (key[0] >= '0' && key[0] <= '9'))
8048 return key[0];
8049 if (key[0] >= 'a' && key[0] <= 'z')
8050 return toupper(key[0]);
8054 return -1;
8057 /* Convert a one-element vector style key sequence to a hot key
8058 definition. */
8059 static Lisp_Object
8060 w32_parse_and_hook_hot_key (Lisp_Object key, int hook)
8062 /* Copied from Fdefine_key and store_in_keymap. */
8063 register Lisp_Object c;
8064 int vk_code;
8065 int lisp_modifiers;
8066 int w32_modifiers;
8067 Lisp_Object res = Qnil;
8068 char* vkname;
8070 CHECK_VECTOR (key);
8072 if (ASIZE (key) != 1)
8073 return Qnil;
8075 c = AREF (key, 0);
8077 if (CONSP (c) && lucid_event_type_list_p (c))
8078 c = Fevent_convert_list (c);
8080 if (! INTEGERP (c) && ! SYMBOLP (c))
8081 error ("Key definition is invalid");
8083 /* Work out the base key and the modifiers. */
8084 if (SYMBOLP (c))
8086 c = parse_modifiers (c);
8087 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8088 c = Fcar (c);
8089 if (!SYMBOLP (c))
8090 emacs_abort ();
8091 vkname = SSDATA (SYMBOL_NAME (c));
8092 /* [s-], [M-], [h-]: Register all keys for this modifier */
8093 if (w32_kbdhook_active && vkname[0] == 0)
8094 vk_code = VK_ANY;
8095 else
8096 vk_code = lookup_vk_code (vkname);
8098 else if (INTEGERP (c))
8100 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8101 /* Many ascii characters are their own virtual key code. */
8102 vk_code = XINT (c) & CHARACTERBITS;
8105 if (vk_code < 0 || vk_code > 255)
8106 return Qnil;
8108 if ((lisp_modifiers & meta_modifier) != 0
8109 && !NILP (Vw32_alt_is_meta))
8110 lisp_modifiers |= alt_modifier;
8112 /* Supply defs missing from mingw32. */
8113 #ifndef MOD_ALT
8114 #define MOD_ALT 0x0001
8115 #define MOD_CONTROL 0x0002
8116 #define MOD_SHIFT 0x0004
8117 #define MOD_WIN 0x0008
8118 #endif
8120 if (w32_kbdhook_active)
8122 /* Register Alt-x combinations. */
8123 if (lisp_modifiers & alt_modifier)
8125 hook_w32_key (hook, VK_MENU, vk_code);
8126 res = Qt;
8128 /* Register Win-x combinations based on modifier mappings. */
8129 if (((lisp_modifiers & hyper_modifier)
8130 && EQ (Vw32_lwindow_modifier, Qhyper))
8131 || ((lisp_modifiers & super_modifier)
8132 && EQ (Vw32_lwindow_modifier, Qsuper)))
8134 hook_w32_key (hook, VK_LWIN, vk_code);
8135 res = Qt;
8137 if (((lisp_modifiers & hyper_modifier)
8138 && EQ (Vw32_rwindow_modifier, Qhyper))
8139 || ((lisp_modifiers & super_modifier)
8140 && EQ (Vw32_rwindow_modifier, Qsuper)))
8142 hook_w32_key (hook, VK_RWIN, vk_code);
8143 res = Qt;
8145 return res;
8147 else
8149 /* Convert lisp modifiers to Windows hot-key form. */
8150 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8151 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8152 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8153 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8155 return HOTKEY (vk_code, w32_modifiers);
8159 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8160 Sw32_register_hot_key, 1, 1, 0,
8161 doc: /* Register KEY as a hot-key combination.
8162 Certain key combinations like Alt-Tab and Win-R are reserved for
8163 system use on Windows, and therefore are normally intercepted by the
8164 system. These key combinations can be received by registering them
8165 as hot-keys, except for Win-L which always locks the computer.
8167 On Windows 98 and ME, KEY must be a one element key definition in
8168 vector form that would be acceptable to `define-key' (e.g. [A-tab] for
8169 Alt-Tab). The meta modifier is interpreted as Alt if
8170 `w32-alt-is-meta' is t, and hyper is always interpreted as the Windows
8171 modifier keys. The return value is the hotkey-id if registered, otherwise nil.
8173 On Windows versions since NT, KEY can also be specified as [M-], [s-] or
8174 [h-] to indicate that all combinations of that key should be processed
8175 by Emacs instead of the operating system. The super and hyper
8176 modifiers are interpreted according to the current values of
8177 `w32-lwindow-modifier' and `w32-rwindow-modifier'. For instance,
8178 setting `w32-lwindow-modifier' to `super' and then calling
8179 `(register-hot-key [s-])' grabs all combinations of the left Windows
8180 key to Emacs, but leaves the right Windows key free for the operating
8181 system keyboard shortcuts. The return value is t if the call affected
8182 any key combinations, otherwise nil. */)
8183 (Lisp_Object key)
8185 key = w32_parse_and_hook_hot_key (key, 1);
8187 if (!w32_kbdhook_active
8188 && !NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8190 /* Reuse an empty slot if possible. */
8191 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8193 /* Safe to add new key to list, even if we have focus. */
8194 if (NILP (item))
8195 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8196 else
8197 XSETCAR (item, key);
8199 /* Notify input thread about new hot-key definition, so that it
8200 takes effect without needing to switch focus. */
8201 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8202 (WPARAM) XINT (key), 0);
8205 return key;
8208 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8209 Sw32_unregister_hot_key, 1, 1, 0,
8210 doc: /* Unregister KEY as a hot-key combination. */)
8211 (Lisp_Object key)
8213 Lisp_Object item;
8215 if (!INTEGERP (key))
8216 key = w32_parse_and_hook_hot_key (key, 0);
8218 if (w32_kbdhook_active)
8219 return key;
8221 item = Fmemq (key, w32_grabbed_keys);
8223 if (!NILP (item))
8225 LPARAM lparam;
8227 eassert (CONSP (item));
8228 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
8229 so that it works in a --with-wide-int build as well. */
8230 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
8232 /* Notify input thread about hot-key definition being removed, so
8233 that it takes effect without needing focus switch. */
8234 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8235 (WPARAM) XINT (XCAR (item)), lparam))
8237 MSG msg;
8238 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8240 return Qt;
8242 return Qnil;
8245 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8246 Sw32_registered_hot_keys, 0, 0, 0,
8247 doc: /* Return list of registered hot-key IDs. */)
8248 (void)
8250 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8253 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8254 Sw32_reconstruct_hot_key, 1, 1, 0,
8255 doc: /* Convert hot-key ID to a lisp key combination.
8256 usage: (w32-reconstruct-hot-key ID) */)
8257 (Lisp_Object hotkeyid)
8259 int vk_code, w32_modifiers;
8260 Lisp_Object key;
8262 CHECK_NUMBER (hotkeyid);
8264 vk_code = HOTKEY_VK_CODE (hotkeyid);
8265 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8267 if (vk_code < 256 && lispy_function_keys[vk_code])
8268 key = intern (lispy_function_keys[vk_code]);
8269 else
8270 key = make_number (vk_code);
8272 key = Fcons (key, Qnil);
8273 if (w32_modifiers & MOD_SHIFT)
8274 key = Fcons (Qshift, key);
8275 if (w32_modifiers & MOD_CONTROL)
8276 key = Fcons (Qctrl, key);
8277 if (w32_modifiers & MOD_ALT)
8278 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8279 if (w32_modifiers & MOD_WIN)
8280 key = Fcons (Qhyper, key);
8282 return key;
8285 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8286 Sw32_toggle_lock_key, 1, 2, 0,
8287 doc: /* Toggle the state of the lock key KEY.
8288 KEY can be `capslock', `kp-numlock', or `scroll'.
8289 If the optional parameter NEW-STATE is a number, then the state of KEY
8290 is set to off if the low bit of NEW-STATE is zero, otherwise on.
8291 If NEW-STATE is omitted or nil, the function toggles the state,
8293 Value is the new state of the key, or nil if the function failed
8294 to change the state. */)
8295 (Lisp_Object key, Lisp_Object new_state)
8297 int vk_code;
8298 LPARAM lparam;
8300 if (EQ (key, intern ("capslock")))
8301 vk_code = VK_CAPITAL;
8302 else if (EQ (key, intern ("kp-numlock")))
8303 vk_code = VK_NUMLOCK;
8304 else if (EQ (key, intern ("scroll")))
8305 vk_code = VK_SCROLL;
8306 else
8307 return Qnil;
8309 if (!dwWindowsThreadId)
8310 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8312 if (NILP (new_state))
8313 lparam = -1;
8314 else
8315 lparam = (XUINT (new_state)) & 1;
8316 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8317 (WPARAM) vk_code, lparam))
8319 MSG msg;
8320 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8321 return make_number (msg.wParam);
8323 return Qnil;
8326 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8327 2, 2, 0,
8328 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8330 This is a direct interface to the Windows API FindWindow function. */)
8331 (Lisp_Object class, Lisp_Object name)
8333 HWND hnd;
8335 if (!NILP (class))
8336 CHECK_STRING (class);
8337 if (!NILP (name))
8338 CHECK_STRING (name);
8340 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8341 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8342 if (!hnd)
8343 return Qnil;
8344 return Qt;
8347 DEFUN ("w32-frame-geometry", Fw32_frame_geometry, Sw32_frame_geometry, 0, 1, 0,
8348 doc: /* Return geometric attributes of FRAME.
8349 FRAME must be a live frame and defaults to the selected one. The return
8350 value is an association list of the attributes listed below. All height
8351 and width values are in pixels.
8353 `outer-position' is a cons of the outer left and top edges of FRAME
8354 relative to the origin - the position (0, 0) - of FRAME's display.
8356 `outer-size' is a cons of the outer width and height of FRAME. The
8357 outer size includes the title bar and the external borders as well as
8358 any menu and/or tool bar of frame.
8360 `external-border-size' is a cons of the horizontal and vertical width of
8361 FRAME's external borders as supplied by the window manager.
8363 `title-bar-size' is a cons of the width and height of the title bar of
8364 FRAME as supplied by the window manager. If both of them are zero,
8365 FRAME has no title bar. If only the width is zero, Emacs was not
8366 able to retrieve the width information.
8368 `menu-bar-external', if non-nil, means the menu bar is external (never
8369 included in the inner edges of FRAME).
8371 `menu-bar-size' is a cons of the width and height of the menu bar of
8372 FRAME.
8374 `tool-bar-external', if non-nil, means the tool bar is external (never
8375 included in the inner edges of FRAME).
8377 `tool-bar-position' tells on which side the tool bar on FRAME is and can
8378 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
8379 has no tool bar.
8381 `tool-bar-size' is a cons of the width and height of the tool bar of
8382 FRAME.
8384 `internal-border-width' is the width of the internal border of
8385 FRAME. */)
8386 (Lisp_Object frame)
8388 struct frame *f = decode_live_frame (frame);
8390 MENUBARINFO menu_bar;
8391 WINDOWINFO window;
8392 int left, top, right, bottom;
8393 unsigned int external_border_width, external_border_height;
8394 int title_bar_width = 0, title_bar_height = 0;
8395 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8396 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8397 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8399 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8400 return Qnil;
8402 block_input ();
8403 /* Outer rectangle and borders. */
8404 window.cbSize = sizeof (window);
8405 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8406 external_border_width = window.cxWindowBorders;
8407 external_border_height = window.cyWindowBorders;
8408 /* Title bar. */
8409 if (get_title_bar_info_fn)
8411 TITLEBAR_INFO title_bar;
8413 title_bar.cbSize = sizeof (title_bar);
8414 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8415 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8416 for (int i = 0; i < 6; i++)
8417 title_bar.rgstate[i] = 0;
8418 if (get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar)
8419 && !(title_bar.rgstate[0] & 0x00008001))
8421 title_bar_width
8422 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8423 title_bar_height
8424 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8427 else if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8428 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8429 /* Menu bar. */
8430 menu_bar.cbSize = sizeof (menu_bar);
8431 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8432 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8433 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8434 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8435 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8436 unblock_input ();
8438 left = window.rcWindow.left;
8439 top = window.rcWindow.top;
8440 right = window.rcWindow.right;
8441 bottom = window.rcWindow.bottom;
8443 /* Menu bar. */
8444 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8445 /* Fix menu bar height reported by GetMenuBarInfo. */
8446 if (menu_bar_height > single_menu_bar_height)
8447 /* A wrapped menu bar. */
8448 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8449 else if (menu_bar_height > 0)
8450 /* A single line menu bar. */
8451 menu_bar_height = single_menu_bar_height;
8453 return listn (CONSTYPE_HEAP, 10,
8454 Fcons (Qouter_position,
8455 Fcons (make_number (left), make_number (top))),
8456 Fcons (Qouter_size,
8457 Fcons (make_number (right - left),
8458 make_number (bottom - top))),
8459 Fcons (Qexternal_border_size,
8460 Fcons (make_number (external_border_width),
8461 make_number (external_border_height))),
8462 Fcons (Qtitle_bar_size,
8463 Fcons (make_number (title_bar_width),
8464 make_number (title_bar_height))),
8465 Fcons (Qmenu_bar_external, Qt),
8466 Fcons (Qmenu_bar_size,
8467 Fcons (make_number
8468 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8469 make_number (menu_bar_height))),
8470 Fcons (Qtool_bar_external, Qnil),
8471 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8472 Fcons (Qtool_bar_size,
8473 Fcons (make_number
8474 (tool_bar_height
8475 ? (right - left - 2 * external_border_width
8476 - 2 * internal_border_width)
8477 : 0),
8478 make_number (tool_bar_height))),
8479 Fcons (Qinternal_border_width,
8480 make_number (internal_border_width)));
8483 DEFUN ("w32-frame-edges", Fw32_frame_edges, Sw32_frame_edges, 0, 2, 0,
8484 doc: /* Return edge coordinates of FRAME.
8485 FRAME must be a live frame and defaults to the selected one. The return
8486 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8487 in pixels relative to the origin - the position (0, 0) - of FRAME's
8488 display.
8490 If optional argument TYPE is the symbol `outer-edges', return the outer
8491 edges of FRAME. The outer edges comprise the decorations of the window
8492 manager (like the title bar or external borders) as well as any external
8493 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8494 `native-edges' or nil, return the native edges of FRAME. The native
8495 edges exclude the decorations of the window manager and any external
8496 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8497 the inner edges of FRAME. These edges exclude title bar, any borders,
8498 menu bar or tool bar of FRAME. */)
8499 (Lisp_Object frame, Lisp_Object type)
8501 struct frame *f = decode_live_frame (frame);
8503 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8504 return Qnil;
8506 if (EQ (type, Qouter_edges))
8508 RECT rectangle;
8510 block_input ();
8511 /* Outer frame rectangle, including outer borders and title bar. */
8512 GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8513 unblock_input ();
8515 return list4 (make_number (rectangle.left),
8516 make_number (rectangle.top),
8517 make_number (rectangle.right),
8518 make_number (rectangle.bottom));
8520 else
8522 RECT rectangle;
8523 POINT pt;
8524 int left, top, right, bottom;
8526 block_input ();
8527 /* Inner frame rectangle, excluding borders and title bar. */
8528 GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
8529 /* Get top-left corner of native rectangle in screen
8530 coordinates. */
8531 pt.x = 0;
8532 pt.y = 0;
8533 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
8534 unblock_input ();
8536 left = pt.x;
8537 top = pt.y;
8538 right = left + rectangle.right;
8539 bottom = top + rectangle.bottom;
8541 if (EQ (type, Qinner_edges))
8543 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8545 return list4 (make_number (left + internal_border_width),
8546 make_number (top
8547 + FRAME_TOOL_BAR_HEIGHT (f)
8548 + internal_border_width),
8549 make_number (right - internal_border_width),
8550 make_number (bottom - internal_border_width));
8552 else
8553 return list4 (make_number (left), make_number (top),
8554 make_number (right), make_number (bottom));
8558 DEFUN ("w32-mouse-absolute-pixel-position", Fw32_mouse_absolute_pixel_position,
8559 Sw32_mouse_absolute_pixel_position, 0, 0, 0,
8560 doc: /* Return absolute position of mouse cursor in pixels.
8561 The position is returned as a cons cell (X . Y) of the coordinates of
8562 the mouse cursor position in pixels relative to a position (0, 0) of the
8563 selected frame's display. */)
8564 (void)
8566 POINT pt;
8568 block_input ();
8569 GetCursorPos (&pt);
8570 unblock_input ();
8572 return Fcons (make_number (pt.x), make_number (pt.y));
8575 DEFUN ("w32-set-mouse-absolute-pixel-position", Fw32_set_mouse_absolute_pixel_position,
8576 Sw32_set_mouse_absolute_pixel_position, 2, 2, 0,
8577 doc: /* Move mouse pointer to absolute pixel position (X, Y).
8578 The coordinates X and Y are interpreted in pixels relative to a position
8579 \(0, 0) of the selected frame's display. */)
8580 (Lisp_Object x, Lisp_Object y)
8582 UINT trail_num = 0;
8583 BOOL ret = false;
8585 CHECK_TYPE_RANGED_INTEGER (int, x);
8586 CHECK_TYPE_RANGED_INTEGER (int, y);
8588 block_input ();
8589 /* When "mouse trails" are in effect, moving the mouse cursor
8590 sometimes leaves behind an annoying "ghost" of the pointer.
8591 Avoid that by momentarily switching off mouse trails. */
8592 if (os_subtype == OS_NT
8593 && w32_major_version + w32_minor_version >= 6)
8594 ret = SystemParametersInfo (SPI_GETMOUSETRAILS, 0, &trail_num, 0);
8595 SetCursorPos (XINT (x), XINT (y));
8596 if (ret)
8597 SystemParametersInfo (SPI_SETMOUSETRAILS, trail_num, NULL, 0);
8598 unblock_input ();
8600 return Qnil;
8603 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
8604 doc: /* Get power status information from Windows system.
8606 The following %-sequences are provided:
8607 %L AC line status (verbose)
8608 %B Battery status (verbose)
8609 %b Battery status, empty means high, `-' means low,
8610 `!' means critical, and `+' means charging
8611 %p Battery load percentage
8612 %s Remaining time (to charge or discharge) in seconds
8613 %m Remaining time (to charge or discharge) in minutes
8614 %h Remaining time (to charge or discharge) in hours
8615 %t Remaining time (to charge or discharge) in the form `h:min' */)
8616 (void)
8618 Lisp_Object status = Qnil;
8620 SYSTEM_POWER_STATUS system_status;
8621 if (GetSystemPowerStatus (&system_status))
8623 Lisp_Object line_status, battery_status, battery_status_symbol;
8624 Lisp_Object load_percentage, seconds, minutes, hours, remain;
8626 long seconds_left = (long) system_status.BatteryLifeTime;
8628 if (system_status.ACLineStatus == 0)
8629 line_status = build_string ("off-line");
8630 else if (system_status.ACLineStatus == 1)
8631 line_status = build_string ("on-line");
8632 else
8633 line_status = build_string ("N/A");
8635 if (system_status.BatteryFlag & 128)
8637 battery_status = build_string ("N/A");
8638 battery_status_symbol = empty_unibyte_string;
8640 else if (system_status.BatteryFlag & 8)
8642 battery_status = build_string ("charging");
8643 battery_status_symbol = build_string ("+");
8644 if (system_status.BatteryFullLifeTime != -1L)
8645 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
8647 else if (system_status.BatteryFlag & 4)
8649 battery_status = build_string ("critical");
8650 battery_status_symbol = build_string ("!");
8652 else if (system_status.BatteryFlag & 2)
8654 battery_status = build_string ("low");
8655 battery_status_symbol = build_string ("-");
8657 else if (system_status.BatteryFlag & 1)
8659 battery_status = build_string ("high");
8660 battery_status_symbol = empty_unibyte_string;
8662 else
8664 battery_status = build_string ("medium");
8665 battery_status_symbol = empty_unibyte_string;
8668 if (system_status.BatteryLifePercent > 100)
8669 load_percentage = build_string ("N/A");
8670 else
8672 char buffer[16];
8673 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
8674 load_percentage = build_string (buffer);
8677 if (seconds_left < 0)
8678 seconds = minutes = hours = remain = build_string ("N/A");
8679 else
8681 long m;
8682 double h;
8683 char buffer[16];
8684 snprintf (buffer, 16, "%ld", seconds_left);
8685 seconds = build_string (buffer);
8687 m = seconds_left / 60;
8688 snprintf (buffer, 16, "%ld", m);
8689 minutes = build_string (buffer);
8691 h = seconds_left / 3600.0;
8692 snprintf (buffer, 16, "%3.1f", h);
8693 hours = build_string (buffer);
8695 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
8696 remain = build_string (buffer);
8699 status = listn (CONSTYPE_HEAP, 8,
8700 Fcons (make_number ('L'), line_status),
8701 Fcons (make_number ('B'), battery_status),
8702 Fcons (make_number ('b'), battery_status_symbol),
8703 Fcons (make_number ('p'), load_percentage),
8704 Fcons (make_number ('s'), seconds),
8705 Fcons (make_number ('m'), minutes),
8706 Fcons (make_number ('h'), hours),
8707 Fcons (make_number ('t'), remain));
8709 return status;
8713 #ifdef WINDOWSNT
8714 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
8715 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8716 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
8717 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8719 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8720 doc: /* Return storage information about the file system FILENAME is on.
8721 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8722 storage of the file system, FREE is the free storage, and AVAIL is the
8723 storage available to a non-superuser. All 3 numbers are in bytes.
8724 If the underlying system call fails, value is nil. */)
8725 (Lisp_Object filename)
8727 Lisp_Object encoded, value;
8729 CHECK_STRING (filename);
8730 filename = Fexpand_file_name (filename, Qnil);
8731 encoded = ENCODE_FILE (filename);
8733 value = Qnil;
8735 /* Determining the required information on Windows turns out, sadly,
8736 to be more involved than one would hope. The original Windows API
8737 call for this will return bogus information on some systems, but we
8738 must dynamically probe for the replacement api, since that was
8739 added rather late on. */
8741 HMODULE hKernel = GetModuleHandle ("kernel32");
8742 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
8743 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
8744 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
8745 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
8746 bool have_pfn_GetDiskFreeSpaceEx =
8747 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
8748 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
8750 /* On Windows, we may need to specify the root directory of the
8751 volume holding FILENAME. */
8752 char rootname[MAX_UTF8_PATH];
8753 wchar_t rootname_w[MAX_PATH];
8754 char rootname_a[MAX_PATH];
8755 char *name = SSDATA (encoded);
8756 BOOL result;
8758 /* find the root name of the volume if given */
8759 if (isalpha (name[0]) && name[1] == ':')
8761 rootname[0] = name[0];
8762 rootname[1] = name[1];
8763 rootname[2] = '\\';
8764 rootname[3] = 0;
8766 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8768 char *str = rootname;
8769 int slashes = 4;
8772 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8773 break;
8774 *str++ = *name++;
8776 while ( *name );
8778 *str++ = '\\';
8779 *str = 0;
8782 if (w32_unicode_filenames)
8783 filename_to_utf16 (rootname, rootname_w);
8784 else
8785 filename_to_ansi (rootname, rootname_a);
8787 if (have_pfn_GetDiskFreeSpaceEx)
8789 /* Unsigned large integers cannot be cast to double, so
8790 use signed ones instead. */
8791 LARGE_INTEGER availbytes;
8792 LARGE_INTEGER freebytes;
8793 LARGE_INTEGER totalbytes;
8795 if (w32_unicode_filenames)
8796 result = pfn_GetDiskFreeSpaceExW (rootname_w,
8797 (ULARGE_INTEGER *)&availbytes,
8798 (ULARGE_INTEGER *)&totalbytes,
8799 (ULARGE_INTEGER *)&freebytes);
8800 else
8801 result = pfn_GetDiskFreeSpaceExA (rootname_a,
8802 (ULARGE_INTEGER *)&availbytes,
8803 (ULARGE_INTEGER *)&totalbytes,
8804 (ULARGE_INTEGER *)&freebytes);
8805 if (result)
8806 value = list3 (make_float ((double) totalbytes.QuadPart),
8807 make_float ((double) freebytes.QuadPart),
8808 make_float ((double) availbytes.QuadPart));
8810 else
8812 DWORD sectors_per_cluster;
8813 DWORD bytes_per_sector;
8814 DWORD free_clusters;
8815 DWORD total_clusters;
8817 if (w32_unicode_filenames)
8818 result = GetDiskFreeSpaceW (rootname_w,
8819 &sectors_per_cluster,
8820 &bytes_per_sector,
8821 &free_clusters,
8822 &total_clusters);
8823 else
8824 result = GetDiskFreeSpaceA (rootname_a,
8825 &sectors_per_cluster,
8826 &bytes_per_sector,
8827 &free_clusters,
8828 &total_clusters);
8829 if (result)
8830 value = list3 (make_float ((double) total_clusters
8831 * sectors_per_cluster * bytes_per_sector),
8832 make_float ((double) free_clusters
8833 * sectors_per_cluster * bytes_per_sector),
8834 make_float ((double) free_clusters
8835 * sectors_per_cluster * bytes_per_sector));
8839 return value;
8841 #endif /* WINDOWSNT */
8844 #ifdef WINDOWSNT
8845 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8846 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8847 (void)
8849 static char pname_buf[256];
8850 int err;
8851 HANDLE hPrn;
8852 PRINTER_INFO_2W *ppi2w = NULL;
8853 PRINTER_INFO_2A *ppi2a = NULL;
8854 DWORD dwNeeded = 0, dwReturned = 0;
8855 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
8856 char port_name[MAX_UTF8_PATH];
8858 /* Retrieve the default string from Win.ini (the registry).
8859 * String will be in form "printername,drivername,portname".
8860 * This is the most portable way to get the default printer. */
8861 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8862 return Qnil;
8863 /* printername precedes first "," character */
8864 strtok (pname_buf, ",");
8865 /* We want to know more than the printer name */
8866 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8867 return Qnil;
8868 /* GetPrinterW is not supported by unicows.dll. */
8869 if (w32_unicode_filenames && os_subtype != OS_9X)
8870 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
8871 else
8872 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
8873 if (dwNeeded == 0)
8875 ClosePrinter (hPrn);
8876 return Qnil;
8878 /* Call GetPrinter again with big enough memory block. */
8879 if (w32_unicode_filenames && os_subtype != OS_9X)
8881 /* Allocate memory for the PRINTER_INFO_2 struct. */
8882 ppi2w = xmalloc (dwNeeded);
8883 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
8884 ClosePrinter (hPrn);
8885 if (!err)
8887 xfree (ppi2w);
8888 return Qnil;
8891 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
8892 && ppi2w->pServerName)
8894 filename_from_utf16 (ppi2w->pServerName, server_name);
8895 filename_from_utf16 (ppi2w->pShareName, share_name);
8897 else
8899 server_name[0] = '\0';
8900 filename_from_utf16 (ppi2w->pPortName, port_name);
8903 else
8905 ppi2a = xmalloc (dwNeeded);
8906 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
8907 ClosePrinter (hPrn);
8908 if (!err)
8910 xfree (ppi2a);
8911 return Qnil;
8914 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
8915 && ppi2a->pServerName)
8917 filename_from_ansi (ppi2a->pServerName, server_name);
8918 filename_from_ansi (ppi2a->pShareName, share_name);
8920 else
8922 server_name[0] = '\0';
8923 filename_from_ansi (ppi2a->pPortName, port_name);
8927 if (server_name[0])
8929 /* a remote printer */
8930 if (server_name[0] == '\\')
8931 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
8932 share_name);
8933 else
8934 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
8935 share_name);
8936 pname_buf[sizeof (pname_buf) - 1] = '\0';
8938 else
8940 /* a local printer */
8941 strncpy (pname_buf, port_name, sizeof (pname_buf));
8942 pname_buf[sizeof (pname_buf) - 1] = '\0';
8943 /* `pPortName' can include several ports, delimited by ','.
8944 * we only use the first one. */
8945 strtok (pname_buf, ",");
8948 return DECODE_FILE (build_unibyte_string (pname_buf));
8950 #endif /* WINDOWSNT */
8953 /* Equivalent of strerror for W32 error codes. */
8954 char *
8955 w32_strerror (int error_no)
8957 static char buf[500];
8958 DWORD ret;
8960 if (error_no == 0)
8961 error_no = GetLastError ();
8963 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
8964 FORMAT_MESSAGE_IGNORE_INSERTS,
8965 NULL,
8966 error_no,
8967 0, /* choose most suitable language */
8968 buf, sizeof (buf), NULL);
8970 while (ret > 0 && (buf[ret - 1] == '\n' ||
8971 buf[ret - 1] == '\r' ))
8972 --ret;
8973 buf[ret] = '\0';
8974 if (!ret)
8975 sprintf (buf, "w32 error %d", error_no);
8977 return buf;
8980 /* For convenience when debugging. (You cannot call GetLastError
8981 directly from GDB: it will crash, because it uses the __stdcall
8982 calling convention, not the _cdecl convention assumed by GDB.) */
8983 DWORD w32_last_error (void);
8985 DWORD
8986 w32_last_error (void)
8988 return GetLastError ();
8991 /* Cache information describing the NT system for later use. */
8992 void
8993 cache_system_info (void)
8995 union
8997 struct info
8999 char major;
9000 char minor;
9001 short platform;
9002 } info;
9003 DWORD data;
9004 } version;
9006 /* Cache the module handle of Emacs itself. */
9007 hinst = GetModuleHandle (NULL);
9009 /* Cache the version of the operating system. */
9010 version.data = GetVersion ();
9011 w32_major_version = version.info.major;
9012 w32_minor_version = version.info.minor;
9014 if (version.info.platform & 0x8000)
9015 os_subtype = OS_9X;
9016 else
9017 os_subtype = OS_NT;
9019 /* Cache page size, allocation unit, processor type, etc. */
9020 GetSystemInfo (&sysinfo_cache);
9021 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
9023 /* Cache os info. */
9024 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
9025 GetVersionEx (&osinfo_cache);
9027 w32_build_number = osinfo_cache.dwBuildNumber;
9028 if (os_subtype == OS_9X)
9029 w32_build_number &= 0xffff;
9031 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
9034 #ifdef EMACSDEBUG
9035 void
9036 _DebPrint (const char *fmt, ...)
9038 char buf[1024];
9039 va_list args;
9041 va_start (args, fmt);
9042 vsprintf (buf, fmt, args);
9043 va_end (args);
9044 #if CYGWIN
9045 fprintf (stderr, "%s", buf);
9046 #endif
9047 OutputDebugString (buf);
9049 #endif
9052 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
9054 int cur_state = (GetKeyState (vk_code) & 1);
9056 if (NILP (new_state)
9057 || (NUMBERP (new_state)
9058 && ((XUINT (new_state)) & 1) != cur_state))
9060 #ifdef WINDOWSNT
9061 faked_key = vk_code;
9062 #endif /* WINDOWSNT */
9064 keybd_event ((BYTE) vk_code,
9065 (BYTE) MapVirtualKey (vk_code, 0),
9066 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9067 keybd_event ((BYTE) vk_code,
9068 (BYTE) MapVirtualKey (vk_code, 0),
9069 KEYEVENTF_EXTENDEDKEY | 0, 0);
9070 keybd_event ((BYTE) vk_code,
9071 (BYTE) MapVirtualKey (vk_code, 0),
9072 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9073 cur_state = !cur_state;
9076 return cur_state;
9079 /* Translate console modifiers to emacs modifiers.
9080 German keyboard support (Kai Morgan Zeise 2/18/95). */
9082 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
9084 int retval = 0;
9086 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
9087 pressed, first remove those modifiers. */
9088 if (!NILP (Vw32_recognize_altgr)
9089 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9090 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9091 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
9093 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
9094 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
9096 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9098 retval |= ctrl_modifier;
9099 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9100 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9101 retval |= meta_modifier;
9104 if (mods & LEFT_WIN_PRESSED)
9105 retval |= w32_key_to_modifier (VK_LWIN);
9106 if (mods & RIGHT_WIN_PRESSED)
9107 retval |= w32_key_to_modifier (VK_RWIN);
9108 if (mods & APPS_PRESSED)
9109 retval |= w32_key_to_modifier (VK_APPS);
9110 if (mods & SCROLLLOCK_ON)
9111 retval |= w32_key_to_modifier (VK_SCROLL);
9113 /* Just in case someone wanted the original behavior, make it
9114 optional by setting w32-capslock-is-shiftlock to t. */
9115 if (NILP (Vw32_capslock_is_shiftlock)
9116 /* Keys that should _not_ be affected by CapsLock. */
9117 && ( (key == VK_BACK)
9118 || (key == VK_TAB)
9119 || (key == VK_CLEAR)
9120 || (key == VK_RETURN)
9121 || (key == VK_ESCAPE)
9122 || ((key >= VK_SPACE) && (key <= VK_HELP))
9123 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
9124 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
9127 /* Only consider shift state. */
9128 if ((mods & SHIFT_PRESSED) != 0)
9129 retval |= shift_modifier;
9131 else
9133 /* Ignore CapsLock state if not enabled. */
9134 if (NILP (Vw32_enable_caps_lock))
9135 mods &= ~CAPSLOCK_ON;
9136 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
9137 retval |= shift_modifier;
9140 return retval;
9143 /* The return code indicates key code size. cpID is the codepage to
9144 use for translation to Unicode; -1 means use the current console
9145 input codepage. */
9147 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
9149 unsigned int key_code = event->wVirtualKeyCode;
9150 unsigned int mods = event->dwControlKeyState;
9151 BYTE keystate[256];
9152 static BYTE ansi_code[4];
9153 static int isdead = 0;
9155 if (isdead == 2)
9157 event->uChar.AsciiChar = ansi_code[2];
9158 isdead = 0;
9159 return 1;
9161 if (event->uChar.AsciiChar != 0)
9162 return 1;
9164 memset (keystate, 0, sizeof (keystate));
9165 keystate[key_code] = 0x80;
9166 if (mods & SHIFT_PRESSED)
9167 keystate[VK_SHIFT] = 0x80;
9168 if (mods & CAPSLOCK_ON)
9169 keystate[VK_CAPITAL] = 1;
9170 /* If we recognize right-alt and left-ctrl as AltGr, set the key
9171 states accordingly before invoking ToAscii. */
9172 if (!NILP (Vw32_recognize_altgr)
9173 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
9175 keystate[VK_CONTROL] = 0x80;
9176 keystate[VK_LCONTROL] = 0x80;
9177 keystate[VK_MENU] = 0x80;
9178 keystate[VK_RMENU] = 0x80;
9181 #if 0
9182 /* Because of an OS bug, ToAscii corrupts the stack when called to
9183 convert a dead key in console mode on NT4. Unfortunately, trying
9184 to check for dead keys using MapVirtualKey doesn't work either -
9185 these functions apparently use internal information about keyboard
9186 layout which doesn't get properly updated in console programs when
9187 changing layout (though apparently it gets partly updated,
9188 otherwise ToAscii wouldn't crash). */
9189 if (is_dead_key (event->wVirtualKeyCode))
9190 return 0;
9191 #endif
9193 /* On NT, call ToUnicode instead and then convert to the current
9194 console input codepage. */
9195 if (os_subtype == OS_NT)
9197 WCHAR buf[128];
9199 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
9200 keystate, buf, 128, 0);
9201 if (isdead > 0)
9203 /* When we are called from the GUI message processing code,
9204 we are passed the current keyboard codepage, a positive
9205 number, to use below. */
9206 if (cpId == -1)
9207 cpId = GetConsoleCP ();
9209 event->uChar.UnicodeChar = buf[isdead - 1];
9210 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
9211 (LPSTR)ansi_code, 4, NULL, NULL);
9213 else
9214 isdead = 0;
9216 else
9218 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
9219 keystate, (LPWORD) ansi_code, 0);
9222 if (isdead == 0)
9223 return 0;
9224 event->uChar.AsciiChar = ansi_code[0];
9225 return isdead;
9229 void
9230 w32_sys_ring_bell (struct frame *f)
9232 if (sound_type == 0xFFFFFFFF)
9234 Beep (666, 100);
9236 else if (sound_type == MB_EMACS_SILENT)
9238 /* Do nothing. */
9240 else
9241 MessageBeep (sound_type);
9244 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
9245 0, 0, 0,
9246 doc: /* Return non-nil when a menu-bar menu is being used.
9247 Internal use only. */)
9248 (void)
9250 return menubar_in_use ? Qt : Qnil;
9253 #if defined WINDOWSNT && !defined HAVE_DBUS
9255 /***********************************************************************
9256 Tray notifications
9257 ***********************************************************************/
9258 /* A private struct declaration to avoid compile-time limits. */
9259 typedef struct MY_NOTIFYICONDATAW {
9260 DWORD cbSize;
9261 HWND hWnd;
9262 UINT uID;
9263 UINT uFlags;
9264 UINT uCallbackMessage;
9265 HICON hIcon;
9266 WCHAR szTip[128];
9267 DWORD dwState;
9268 DWORD dwStateMask;
9269 WCHAR szInfo[256];
9270 _ANONYMOUS_UNION union {
9271 UINT uTimeout;
9272 UINT uVersion;
9273 } DUMMYUNIONNAME;
9274 WCHAR szInfoTitle[64];
9275 DWORD dwInfoFlags;
9276 GUID guidItem;
9277 HICON hBalloonIcon;
9278 } MY_NOTIFYICONDATAW;
9280 #define MYNOTIFYICONDATAW_V1_SIZE offsetof (MY_NOTIFYICONDATAW, szTip[64])
9281 #define MYNOTIFYICONDATAW_V2_SIZE offsetof (MY_NOTIFYICONDATAW, guidItem)
9282 #define MYNOTIFYICONDATAW_V3_SIZE offsetof (MY_NOTIFYICONDATAW, hBalloonIcon)
9283 #ifndef NIF_INFO
9284 # define NIF_INFO 0x00000010
9285 #endif
9286 #ifndef NIIF_NONE
9287 # define NIIF_NONE 0x00000000
9288 #endif
9289 #ifndef NIIF_INFO
9290 # define NIIF_INFO 0x00000001
9291 #endif
9292 #ifndef NIIF_WARNING
9293 # define NIIF_WARNING 0x00000002
9294 #endif
9295 #ifndef NIIF_ERROR
9296 # define NIIF_ERROR 0x00000003
9297 #endif
9300 #define EMACS_TRAY_NOTIFICATION_ID 42 /* arbitrary */
9301 #define EMACS_NOTIFICATION_MSG (WM_APP + 1)
9303 enum NI_Severity {
9304 Ni_None,
9305 Ni_Info,
9306 Ni_Warn,
9307 Ni_Err
9310 /* Report the version of a DLL given by its name. The return value is
9311 constructed using MAKEDLLVERULL. */
9312 static ULONGLONG
9313 get_dll_version (const char *dll_name)
9315 ULONGLONG version = 0;
9316 HINSTANCE hdll = LoadLibrary (dll_name);
9318 if (hdll)
9320 DLLGETVERSIONPROC pDllGetVersion
9321 = (DLLGETVERSIONPROC) GetProcAddress (hdll, "DllGetVersion");
9323 if (pDllGetVersion)
9325 DLLVERSIONINFO dvi;
9326 HRESULT result;
9328 memset (&dvi, 0, sizeof(dvi));
9329 dvi.cbSize = sizeof(dvi);
9330 result = pDllGetVersion (&dvi);
9331 if (SUCCEEDED (result))
9332 version = MAKEDLLVERULL (dvi.dwMajorVersion, dvi.dwMinorVersion,
9333 0, 0);
9335 FreeLibrary (hdll);
9338 return version;
9341 /* Return the number of bytes in UTF-8 encoded string STR that
9342 corresponds to at most LIM characters. If STR ends before LIM
9343 characters, return the number of bytes in STR including the
9344 terminating null byte. */
9345 static int
9346 utf8_mbslen_lim (const char *str, int lim)
9348 const char *p = str;
9349 int mblen = 0, nchars = 0;
9351 while (*p && nchars < lim)
9353 int nbytes = CHAR_BYTES (*p);
9355 mblen += nbytes;
9356 nchars++;
9357 p += nbytes;
9360 if (!*p && nchars < lim)
9361 mblen++;
9363 return mblen;
9366 /* Low-level subroutine to show tray notifications. All strings are
9367 supposed to be unibyte UTF-8 encoded by the caller. */
9368 static EMACS_INT
9369 add_tray_notification (struct frame *f, const char *icon, const char *tip,
9370 enum NI_Severity severity, unsigned timeout,
9371 const char *title, const char *msg)
9373 EMACS_INT retval = EMACS_TRAY_NOTIFICATION_ID;
9375 if (FRAME_W32_P (f))
9377 MY_NOTIFYICONDATAW nidw;
9378 ULONGLONG shell_dll_version = get_dll_version ("Shell32.dll");
9379 wchar_t tipw[128], msgw[256], titlew[64];
9380 int tiplen;
9382 memset (&nidw, 0, sizeof(nidw));
9384 /* MSDN says the full struct is supported since Vista, whose
9385 Shell32.dll version is said to be 6.0.6. But DllGetVersion
9386 cannot report the 3rd field value, it reports "build number"
9387 instead, which is something else. So we use the Windows 7's
9388 version 6.1 as cutoff, and Vista loses. (Actually, the loss
9389 is not a real one, since we don't expose the hBalloonIcon
9390 member of the struct to Lisp.) */
9391 if (shell_dll_version >= MAKEDLLVERULL (6, 1, 0, 0)) /* >= Windows 7 */
9392 nidw.cbSize = sizeof (nidw);
9393 else if (shell_dll_version >= MAKEDLLVERULL (6, 0, 0, 0)) /* XP */
9394 nidw.cbSize = MYNOTIFYICONDATAW_V3_SIZE;
9395 else if (shell_dll_version >= MAKEDLLVERULL (5, 0, 0, 0)) /* W2K */
9396 nidw.cbSize = MYNOTIFYICONDATAW_V2_SIZE;
9397 else
9398 nidw.cbSize = MYNOTIFYICONDATAW_V1_SIZE; /* < W2K */
9399 nidw.hWnd = FRAME_W32_WINDOW (f);
9400 nidw.uID = EMACS_TRAY_NOTIFICATION_ID;
9401 nidw.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO;
9402 nidw.uCallbackMessage = EMACS_NOTIFICATION_MSG;
9403 if (!*icon)
9404 nidw.hIcon = LoadIcon (hinst, EMACS_CLASS);
9405 else
9407 if (w32_unicode_filenames)
9409 wchar_t icon_w[MAX_PATH];
9411 if (filename_to_utf16 (icon, icon_w) != 0)
9413 errno = ENOENT;
9414 return -1;
9416 nidw.hIcon = LoadImageW (NULL, icon_w, IMAGE_ICON, 0, 0,
9417 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9419 else
9421 char icon_a[MAX_PATH];
9423 if (filename_to_ansi (icon, icon_a) != 0)
9425 errno = ENOENT;
9426 return -1;
9428 nidw.hIcon = LoadImageA (NULL, icon_a, IMAGE_ICON, 0, 0,
9429 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9432 if (!nidw.hIcon)
9434 switch (GetLastError ())
9436 case ERROR_FILE_NOT_FOUND:
9437 errno = ENOENT;
9438 break;
9439 default:
9440 errno = ENOMEM;
9441 break;
9443 return -1;
9446 /* Windows 9X and NT4 support only 64 characters in the Tip,
9447 later versions support up to 128. */
9448 if (nidw.cbSize == MYNOTIFYICONDATAW_V1_SIZE)
9450 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9451 tip, utf8_mbslen_lim (tip, 63),
9452 tipw, 64);
9453 if (tiplen >= 63)
9454 tipw[63] = 0;
9456 else
9458 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9459 tip, utf8_mbslen_lim (tip, 127),
9460 tipw, 128);
9461 if (tiplen >= 127)
9462 tipw[127] = 0;
9464 if (tiplen == 0)
9466 errno = EINVAL;
9467 retval = -1;
9468 goto done;
9470 wcscpy (nidw.szTip, tipw);
9472 /* The rest of the structure is only supported since Windows 2000. */
9473 if (nidw.cbSize > MYNOTIFYICONDATAW_V1_SIZE)
9475 int slen;
9477 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9478 msg, utf8_mbslen_lim (msg, 255),
9479 msgw, 256);
9480 if (slen >= 255)
9481 msgw[255] = 0;
9482 else if (slen == 0)
9484 errno = EINVAL;
9485 retval = -1;
9486 goto done;
9488 wcscpy (nidw.szInfo, msgw);
9489 nidw.uTimeout = timeout;
9490 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9491 title, utf8_mbslen_lim (title, 63),
9492 titlew, 64);
9493 if (slen >= 63)
9494 titlew[63] = 0;
9495 else if (slen == 0)
9497 errno = EINVAL;
9498 retval = -1;
9499 goto done;
9501 wcscpy (nidw.szInfoTitle, titlew);
9503 switch (severity)
9505 case Ni_None:
9506 nidw.dwInfoFlags = NIIF_NONE;
9507 break;
9508 case Ni_Info:
9509 default:
9510 nidw.dwInfoFlags = NIIF_INFO;
9511 break;
9512 case Ni_Warn:
9513 nidw.dwInfoFlags = NIIF_WARNING;
9514 break;
9515 case Ni_Err:
9516 nidw.dwInfoFlags = NIIF_ERROR;
9517 break;
9521 if (!Shell_NotifyIconW (NIM_ADD, (PNOTIFYICONDATAW)&nidw))
9523 /* GetLastError returns meaningless results when
9524 Shell_NotifyIcon fails. */
9525 DebPrint (("Shell_NotifyIcon ADD failed (err=%d)\n",
9526 GetLastError ()));
9527 errno = EINVAL;
9528 retval = -1;
9530 done:
9531 if (*icon && !DestroyIcon (nidw.hIcon))
9532 DebPrint (("DestroyIcon failed (err=%d)\n", GetLastError ()));
9534 return retval;
9537 /* Low-level subroutine to remove a tray notification. Note: we only
9538 pass the minimum data about the notification: its ID and the handle
9539 of the window to which it sends messages. MSDN doesn't say this is
9540 enough, but it works in practice. This allows us to avoid keeping
9541 the notification data around after we show the notification. */
9542 static void
9543 delete_tray_notification (struct frame *f, int id)
9545 if (FRAME_W32_P (f))
9547 MY_NOTIFYICONDATAW nidw;
9549 memset (&nidw, 0, sizeof(nidw));
9550 nidw.hWnd = FRAME_W32_WINDOW (f);
9551 nidw.uID = id;
9553 if (!Shell_NotifyIconW (NIM_DELETE, (PNOTIFYICONDATAW)&nidw))
9555 /* GetLastError returns meaningless results when
9556 Shell_NotifyIcon fails. */
9557 DebPrint (("Shell_NotifyIcon DELETE failed\n"));
9558 errno = EINVAL;
9559 return;
9562 return;
9565 DEFUN ("w32-notification-notify",
9566 Fw32_notification_notify, Sw32_notification_notify,
9567 0, MANY, 0,
9568 doc: /* Display an MS-Windows tray notification as specified by PARAMS.
9570 Value is the integer unique ID of the notification that can be used
9571 to remove the notification using `w32-notification-close', which see.
9572 If the function fails, the return value is nil.
9574 Tray notifications, a.k.a. \"taskbar messages\", are messages that
9575 inform the user about events unrelated to the current user activity,
9576 such as a significant system event, by briefly displaying informative
9577 text in a balloon from an icon in the notification area of the taskbar.
9579 Parameters in PARAMS are specified as keyword/value pairs. All the
9580 parameters are optional, but if no parameters are specified, the
9581 function will do nothing and return nil.
9583 The following parameters are supported:
9585 :icon ICON -- Display ICON in the system tray. If ICON is a string,
9586 it should specify a file name from which to load the
9587 icon; the specified file should be a .ico Windows icon
9588 file. If ICON is not a string, or if this parameter
9589 is not specified, the standard Emacs icon will be used.
9591 :tip TIP -- Use TIP as the tooltip for the notification. If TIP
9592 is a string, this is the text of a tooltip that will
9593 be shown when the mouse pointer hovers over the tray
9594 icon added by the notification. If TIP is not a
9595 string, or if this parameter is not specified, the
9596 default tooltip text is \"Emacs notification\". The
9597 tooltip text can be up to 127 characters long (63
9598 on Windows versions before W2K). Longer strings
9599 will be truncated.
9601 :level LEVEL -- Notification severity level, one of `info',
9602 `warning', or `error'. If given, the value
9603 determines the icon displayed to the left of the
9604 notification title, but only if the `:title'
9605 parameter (see below) is also specified and is a
9606 string.
9608 :title TITLE -- The title of the notification. If TITLE is a string,
9609 it is displayed in a larger font immediately above
9610 the body text. The title text can be up to 63
9611 characters long; longer text will be truncated.
9613 :body BODY -- The body of the notification. If BODY is a string,
9614 it specifies the text of the notification message.
9615 Use embedded newlines to control how the text is
9616 broken into lines. The body text can be up to 255
9617 characters long, and will be truncated if it's longer.
9619 Note that versions of Windows before W2K support only `:icon' and `:tip'.
9620 You can pass the other parameters, but they will be ignored on those
9621 old systems.
9623 There can be at most one active notification at any given time. An
9624 active notification must be removed by calling `w32-notification-close'
9625 before a new one can be shown.
9627 usage: (w32-notification-notify &rest PARAMS) */)
9628 (ptrdiff_t nargs, Lisp_Object *args)
9630 struct frame *f = SELECTED_FRAME ();
9631 Lisp_Object arg_plist, lres;
9632 EMACS_INT retval;
9633 char *icon, *tip, *title, *msg;
9634 enum NI_Severity severity;
9635 unsigned timeout = 0;
9637 if (nargs == 0)
9638 return Qnil;
9640 arg_plist = Flist (nargs, args);
9642 /* Icon. */
9643 lres = Fplist_get (arg_plist, QCicon);
9644 if (STRINGP (lres))
9645 icon = SSDATA (ENCODE_FILE (Fexpand_file_name (lres, Qnil)));
9646 else
9647 icon = (char *)"";
9649 /* Tip. */
9650 lres = Fplist_get (arg_plist, QCtip);
9651 if (STRINGP (lres))
9652 tip = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9653 else
9654 tip = (char *)"Emacs notification";
9656 /* Severity. */
9657 lres = Fplist_get (arg_plist, QClevel);
9658 if (NILP (lres))
9659 severity = Ni_None;
9660 else if (EQ (lres, Qinfo))
9661 severity = Ni_Info;
9662 else if (EQ (lres, Qwarning))
9663 severity = Ni_Warn;
9664 else if (EQ (lres, Qerror))
9665 severity = Ni_Err;
9666 else
9667 severity = Ni_Info;
9669 /* Title. */
9670 lres = Fplist_get (arg_plist, QCtitle);
9671 if (STRINGP (lres))
9672 title = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9673 else
9674 title = (char *)"";
9676 /* Notification body text. */
9677 lres = Fplist_get (arg_plist, QCbody);
9678 if (STRINGP (lres))
9679 msg = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9680 else
9681 msg = (char *)"";
9683 /* Do it! */
9684 retval = add_tray_notification (f, icon, tip, severity, timeout, title, msg);
9685 return (retval < 0 ? Qnil : make_number (retval));
9688 DEFUN ("w32-notification-close",
9689 Fw32_notification_close, Sw32_notification_close,
9690 1, 1, 0,
9691 doc: /* Remove the MS-Windows tray notification specified by its ID. */)
9692 (Lisp_Object id)
9694 struct frame *f = SELECTED_FRAME ();
9696 if (INTEGERP (id))
9697 delete_tray_notification (f, XINT (id));
9699 return Qnil;
9702 #endif /* WINDOWSNT && !HAVE_DBUS */
9705 /***********************************************************************
9706 Initialization
9707 ***********************************************************************/
9709 /* Keep this list in the same order as frame_parms in frame.c.
9710 Use 0 for unsupported frame parameters. */
9712 frame_parm_handler w32_frame_parm_handlers[] =
9714 x_set_autoraise,
9715 x_set_autolower,
9716 x_set_background_color,
9717 x_set_border_color,
9718 x_set_border_width,
9719 x_set_cursor_color,
9720 x_set_cursor_type,
9721 x_set_font,
9722 x_set_foreground_color,
9723 x_set_icon_name,
9724 x_set_icon_type,
9725 x_set_internal_border_width,
9726 x_set_right_divider_width,
9727 x_set_bottom_divider_width,
9728 x_set_menu_bar_lines,
9729 x_set_mouse_color,
9730 x_explicitly_set_name,
9731 x_set_scroll_bar_width,
9732 x_set_scroll_bar_height,
9733 x_set_title,
9734 x_set_unsplittable,
9735 x_set_vertical_scroll_bars,
9736 x_set_horizontal_scroll_bars,
9737 x_set_visibility,
9738 x_set_tool_bar_lines,
9739 0, /* x_set_scroll_bar_foreground, */
9740 0, /* x_set_scroll_bar_background, */
9741 x_set_screen_gamma,
9742 x_set_line_spacing,
9743 x_set_left_fringe,
9744 x_set_right_fringe,
9745 0, /* x_set_wait_for_wm, */
9746 x_set_fullscreen,
9747 x_set_font_backend,
9748 x_set_alpha,
9749 0, /* x_set_sticky */
9750 0, /* x_set_tool_bar_position */
9751 0, /* x_set_inhibit_double_buffering */
9754 void
9755 syms_of_w32fns (void)
9757 globals_of_w32fns ();
9758 track_mouse_window = NULL;
9760 w32_visible_system_caret_hwnd = NULL;
9762 DEFSYM (Qundefined_color, "undefined-color");
9763 DEFSYM (Qcancel_timer, "cancel-timer");
9764 DEFSYM (Qhyper, "hyper");
9765 DEFSYM (Qsuper, "super");
9766 DEFSYM (Qmeta, "meta");
9767 DEFSYM (Qalt, "alt");
9768 DEFSYM (Qctrl, "ctrl");
9769 DEFSYM (Qcontrol, "control");
9770 DEFSYM (Qshift, "shift");
9771 DEFSYM (Qfont_parameter, "font-parameter");
9772 DEFSYM (Qgeometry, "geometry");
9773 DEFSYM (Qworkarea, "workarea");
9774 DEFSYM (Qmm_size, "mm-size");
9775 DEFSYM (Qframes, "frames");
9776 DEFSYM (Qtip_frame, "tip-frame");
9777 DEFSYM (Qassq_delete_all, "assq-delete-all");
9778 DEFSYM (Qunicode_sip, "unicode-sip");
9779 #if defined WINDOWSNT && !defined HAVE_DBUS
9780 DEFSYM (QCicon, ":icon");
9781 DEFSYM (QCtip, ":tip");
9782 DEFSYM (QClevel, ":level");
9783 DEFSYM (Qinfo, "info");
9784 DEFSYM (Qwarning, "warning");
9785 DEFSYM (QCtitle, ":title");
9786 DEFSYM (QCbody, ":body");
9787 #endif
9789 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
9790 DEFSYM (Qgnutls, "gnutls");
9791 DEFSYM (Qlibxml2, "libxml2");
9792 DEFSYM (Qserif, "serif");
9793 DEFSYM (Qzlib, "zlib");
9795 Fput (Qundefined_color, Qerror_conditions,
9796 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
9797 Fput (Qundefined_color, Qerror_message,
9798 build_pure_c_string ("Undefined color"));
9800 staticpro (&w32_grabbed_keys);
9801 w32_grabbed_keys = Qnil;
9803 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
9804 doc: /* An array of color name mappings for Windows. */);
9805 Vw32_color_map = Qnil;
9807 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
9808 doc: /* Non-nil if Alt key presses are passed on to Windows.
9809 When non-nil, for example, Alt pressed and released and then space will
9810 open the System menu. When nil, Emacs processes the Alt key events, and
9811 then silently swallows them. */);
9812 Vw32_pass_alt_to_system = Qnil;
9814 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
9815 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
9816 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
9817 Vw32_alt_is_meta = Qt;
9819 DEFVAR_INT ("w32-quit-key", w32_quit_key,
9820 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
9821 w32_quit_key = 0;
9823 DEFVAR_LISP ("w32-pass-lwindow-to-system",
9824 Vw32_pass_lwindow_to_system,
9825 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
9827 When non-nil, the Start menu is opened by tapping the key.
9828 If you set this to nil, the left \"Windows\" key is processed by Emacs
9829 according to the value of `w32-lwindow-modifier', which see.
9831 Note that some combinations of the left \"Windows\" key with other
9832 keys are caught by Windows at low level. For example, <lwindow>-r
9833 pops up the Windows Run dialog, <lwindow>-<Pause> pops up the "System
9834 Properties" dialog, etc. On Windows 10, no \"Windows\" key
9835 combinations are normally handed to applications. To enable Emacs to
9836 process \"Windows\" key combinations, use the function
9837 `w32-register-hot-key`.
9839 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
9840 Vw32_pass_lwindow_to_system = Qt;
9842 DEFVAR_LISP ("w32-pass-rwindow-to-system",
9843 Vw32_pass_rwindow_to_system,
9844 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
9846 When non-nil, the Start menu is opened by tapping the key.
9847 If you set this to nil, the right \"Windows\" key is processed by Emacs
9848 according to the value of `w32-rwindow-modifier', which see.
9850 Note that some combinations of the right \"Windows\" key with other
9851 keys are caught by Windows at low level. For example, <rwindow>-r
9852 pops up the Windows Run dialog, <rwindow>-<Pause> pops up the "System
9853 Properties" dialog, etc. On Windows 10, no \"Windows\" key
9854 combinations are normally handed to applications. To enable Emacs to
9855 process \"Windows\" key combinations, use the function
9856 `w32-register-hot-key`.
9858 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
9859 Vw32_pass_rwindow_to_system = Qt;
9861 DEFVAR_LISP ("w32-phantom-key-code",
9862 Vw32_phantom_key_code,
9863 doc: /* Virtual key code used to generate \"phantom\" key presses.
9864 Value is a number between 0 and 255.
9866 Phantom key presses are generated in order to stop the system from
9867 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
9868 `w32-pass-rwindow-to-system' is nil.
9870 This variable is only used on Windows 98 and ME. For other Windows
9871 versions, see the documentation of the `w32-register-hot-key`
9872 function. */);
9873 /* Although 255 is technically not a valid key code, it works and
9874 means that this hack won't interfere with any real key code. */
9875 XSETINT (Vw32_phantom_key_code, 255);
9877 DEFVAR_LISP ("w32-enable-num-lock",
9878 Vw32_enable_num_lock,
9879 doc: /* If non-nil, the Num Lock key acts normally.
9880 Set to nil to handle Num Lock as the `kp-numlock' key. */);
9881 Vw32_enable_num_lock = Qt;
9883 DEFVAR_LISP ("w32-enable-caps-lock",
9884 Vw32_enable_caps_lock,
9885 doc: /* If non-nil, the Caps Lock key acts normally.
9886 Set to nil to handle Caps Lock as the `capslock' key. */);
9887 Vw32_enable_caps_lock = Qt;
9889 DEFVAR_LISP ("w32-scroll-lock-modifier",
9890 Vw32_scroll_lock_modifier,
9891 doc: /* Modifier to use for the Scroll Lock ON state.
9892 The value can be hyper, super, meta, alt, control or shift for the
9893 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
9894 Any other value will cause the Scroll Lock key to be ignored by Emacs,
9895 and it will have the same effect as in other applications. */);
9896 Vw32_scroll_lock_modifier = Qnil;
9898 DEFVAR_LISP ("w32-lwindow-modifier",
9899 Vw32_lwindow_modifier,
9900 doc: /* Modifier to use for the left \"Windows\" key.
9901 The value can be hyper, super, meta, alt, control or shift for the
9902 respective modifier, or nil to appear as the `lwindow' key.
9903 Any other value will cause the key to be ignored.
9905 Also see the documentation of the `w32-register-hot-key` function. */);
9906 Vw32_lwindow_modifier = Qnil;
9908 DEFVAR_LISP ("w32-rwindow-modifier",
9909 Vw32_rwindow_modifier,
9910 doc: /* Modifier to use for the right \"Windows\" key.
9911 The value can be hyper, super, meta, alt, control or shift for the
9912 respective modifier, or nil to appear as the `rwindow' key.
9913 Any other value will cause the key to be ignored.
9915 Also see the documentation of the `w32-register-hot-key` function. */);
9916 Vw32_rwindow_modifier = Qnil;
9918 DEFVAR_LISP ("w32-apps-modifier",
9919 Vw32_apps_modifier,
9920 doc: /* Modifier to use for the \"Apps\" key.
9921 The value can be hyper, super, meta, alt, control or shift for the
9922 respective modifier, or nil to appear as the `apps' key.
9923 Any other value will cause the key to be ignored. */);
9924 Vw32_apps_modifier = Qnil;
9926 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
9927 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
9928 w32_enable_synthesized_fonts = 0;
9930 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
9931 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
9932 Vw32_enable_palette = Qt;
9934 DEFVAR_INT ("w32-mouse-button-tolerance",
9935 w32_mouse_button_tolerance,
9936 doc: /* Analogue of double click interval for faking middle mouse events.
9937 The value is the minimum time in milliseconds that must elapse between
9938 left and right button down events before they are considered distinct events.
9939 If both mouse buttons are depressed within this interval, a middle mouse
9940 button down event is generated instead. */);
9941 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
9943 DEFVAR_INT ("w32-mouse-move-interval",
9944 w32_mouse_move_interval,
9945 doc: /* Minimum interval between mouse move events.
9946 The value is the minimum time in milliseconds that must elapse between
9947 successive mouse move (or scroll bar drag) events before they are
9948 reported as lisp events. */);
9949 w32_mouse_move_interval = 0;
9951 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
9952 w32_pass_extra_mouse_buttons_to_system,
9953 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
9954 Recent versions of Windows support mice with up to five buttons.
9955 Since most applications don't support these extra buttons, most mouse
9956 drivers will allow you to map them to functions at the system level.
9957 If this variable is non-nil, Emacs will pass them on, allowing the
9958 system to handle them. */);
9959 w32_pass_extra_mouse_buttons_to_system = 0;
9961 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
9962 w32_pass_multimedia_buttons_to_system,
9963 doc: /* If non-nil, media buttons are passed to Windows.
9964 Some modern keyboards contain buttons for controlling media players, web
9965 browsers and other applications. Generally these buttons are handled on a
9966 system wide basis, but by setting this to nil they are made available
9967 to Emacs for binding. Depending on your keyboard, additional keys that
9968 may be available are:
9970 browser-back, browser-forward, browser-refresh, browser-stop,
9971 browser-search, browser-favorites, browser-home,
9972 mail, mail-reply, mail-forward, mail-send,
9973 app-1, app-2,
9974 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
9975 spell-check, correction-list, toggle-dictate-command,
9976 media-next, media-previous, media-stop, media-play-pause, media-select,
9977 media-play, media-pause, media-record, media-fast-forward, media-rewind,
9978 media-channel-up, media-channel-down,
9979 volume-mute, volume-up, volume-down,
9980 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
9981 bass-down, bass-boost, bass-up, treble-down, treble-up */);
9982 w32_pass_multimedia_buttons_to_system = 1;
9984 #if 0 /* TODO: Mouse cursor customization. */
9985 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
9986 doc: /* The shape of the pointer when over text.
9987 Changing the value does not affect existing frames
9988 unless you set the mouse color. */);
9989 Vx_pointer_shape = Qnil;
9991 Vx_nontext_pointer_shape = Qnil;
9993 Vx_mode_pointer_shape = Qnil;
9995 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
9996 doc: /* The shape of the pointer when Emacs is busy.
9997 This variable takes effect when you create a new frame
9998 or when you set the mouse color. */);
9999 Vx_hourglass_pointer_shape = Qnil;
10001 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
10002 Vx_sensitive_text_pointer_shape,
10003 doc: /* The shape of the pointer when over mouse-sensitive text.
10004 This variable takes effect when you create a new frame
10005 or when you set the mouse color. */);
10006 Vx_sensitive_text_pointer_shape = Qnil;
10008 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
10009 Vx_window_horizontal_drag_shape,
10010 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
10011 This variable takes effect when you create a new frame
10012 or when you set the mouse color. */);
10013 Vx_window_horizontal_drag_shape = Qnil;
10015 DEFVAR_LISP ("x-window-vertical-drag-cursor",
10016 Vx_window_vertical_drag_shape,
10017 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
10018 This variable takes effect when you create a new frame
10019 or when you set the mouse color. */);
10020 Vx_window_vertical_drag_shape = Qnil;
10021 #endif
10023 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
10024 doc: /* A string indicating the foreground color of the cursor box. */);
10025 Vx_cursor_fore_pixel = Qnil;
10027 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
10028 doc: /* Maximum size for tooltips.
10029 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
10030 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
10032 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
10033 doc: /* Non-nil if no window manager is in use.
10034 Emacs doesn't try to figure this out; this is always nil
10035 unless you set it to something else. */);
10036 /* We don't have any way to find this out, so set it to nil
10037 and maybe the user would like to set it to t. */
10038 Vx_no_window_manager = Qnil;
10040 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
10041 Vx_pixel_size_width_font_regexp,
10042 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
10044 Since Emacs gets width of a font matching with this regexp from
10045 PIXEL_SIZE field of the name, font finding mechanism gets faster for
10046 such a font. This is especially effective for such large fonts as
10047 Chinese, Japanese, and Korean. */);
10048 Vx_pixel_size_width_font_regexp = Qnil;
10050 DEFVAR_LISP ("w32-bdf-filename-alist",
10051 Vw32_bdf_filename_alist,
10052 doc: /* List of bdf fonts and their corresponding filenames. */);
10053 Vw32_bdf_filename_alist = Qnil;
10055 DEFVAR_BOOL ("w32-strict-fontnames",
10056 w32_strict_fontnames,
10057 doc: /* Non-nil means only use fonts that are exact matches for those requested.
10058 Default is nil, which allows old fontnames that are not XLFD compliant,
10059 and allows third-party CJK display to work by specifying false charset
10060 fields to trick Emacs into translating to Big5, SJIS etc.
10061 Setting this to t will prevent wrong fonts being selected when
10062 fontsets are automatically created. */);
10063 w32_strict_fontnames = 0;
10065 DEFVAR_BOOL ("w32-strict-painting",
10066 w32_strict_painting,
10067 doc: /* Non-nil means use strict rules for repainting frames.
10068 Set this to nil to get the old behavior for repainting; this should
10069 only be necessary if the default setting causes problems. */);
10070 w32_strict_painting = 1;
10072 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
10073 w32_use_fallback_wm_chars_method,
10074 doc: /* Non-nil means use old method of processing character keys.
10075 This is intended only for debugging of the new processing method.
10076 Default is nil.
10078 This variable has effect only on NT family of systems, not on Windows 9X. */);
10079 w32_use_fallback_wm_chars_method = 0;
10081 DEFVAR_BOOL ("w32-disable-new-uniscribe-apis",
10082 w32_disable_new_uniscribe_apis,
10083 doc: /* Non-nil means don't use new Uniscribe APIs.
10084 The new APIs are used to access OTF features supported by fonts.
10085 This is intended only for debugging of the new Uniscribe-related code.
10086 Default is nil.
10088 This variable has effect only on Windows Vista and later. */);
10089 w32_disable_new_uniscribe_apis = 0;
10091 DEFVAR_LISP ("w32-tooltip-extra-pixels",
10092 Vw32_tooltip_extra_pixels,
10093 doc: /* Number of pixels added after tooltip text.
10094 On Windows some fonts may cause the last character of a tooltip be
10095 truncated or wrapped around to the next line. Adding some extra space
10096 at the end of the toooltip works around this problem.
10098 This variable specifies the number of pixels that shall be added. The
10099 default value t means to add the width of one canonical character of the
10100 tip frame. */);
10101 Vw32_tooltip_extra_pixels = Qt;
10103 #if 0 /* TODO: Port to W32 */
10104 defsubr (&Sx_change_window_property);
10105 defsubr (&Sx_delete_window_property);
10106 defsubr (&Sx_window_property);
10107 #endif
10108 defsubr (&Sxw_display_color_p);
10109 defsubr (&Sx_display_grayscale_p);
10110 defsubr (&Sxw_color_defined_p);
10111 defsubr (&Sxw_color_values);
10112 defsubr (&Sx_server_max_request_size);
10113 defsubr (&Sx_server_vendor);
10114 defsubr (&Sx_server_version);
10115 defsubr (&Sx_display_pixel_width);
10116 defsubr (&Sx_display_pixel_height);
10117 defsubr (&Sx_display_mm_width);
10118 defsubr (&Sx_display_mm_height);
10119 defsubr (&Sx_display_screens);
10120 defsubr (&Sx_display_planes);
10121 defsubr (&Sx_display_color_cells);
10122 defsubr (&Sx_display_visual_class);
10123 defsubr (&Sx_display_backing_store);
10124 defsubr (&Sx_display_save_under);
10125 defsubr (&Sx_create_frame);
10126 defsubr (&Sx_open_connection);
10127 defsubr (&Sx_close_connection);
10128 defsubr (&Sx_display_list);
10129 defsubr (&Sw32_frame_geometry);
10130 defsubr (&Sw32_frame_edges);
10131 defsubr (&Sw32_mouse_absolute_pixel_position);
10132 defsubr (&Sw32_set_mouse_absolute_pixel_position);
10133 defsubr (&Sx_synchronize);
10135 /* W32 specific functions */
10137 defsubr (&Sw32_define_rgb_color);
10138 defsubr (&Sw32_default_color_map);
10139 defsubr (&Sw32_display_monitor_attributes_list);
10140 defsubr (&Sw32_send_sys_command);
10141 defsubr (&Sw32_shell_execute);
10142 defsubr (&Sw32_register_hot_key);
10143 defsubr (&Sw32_unregister_hot_key);
10144 defsubr (&Sw32_registered_hot_keys);
10145 defsubr (&Sw32_reconstruct_hot_key);
10146 defsubr (&Sw32_toggle_lock_key);
10147 defsubr (&Sw32_window_exists_p);
10148 defsubr (&Sw32_battery_status);
10149 defsubr (&Sw32__menu_bar_in_use);
10150 #if defined WINDOWSNT && !defined HAVE_DBUS
10151 defsubr (&Sw32_notification_notify);
10152 defsubr (&Sw32_notification_close);
10153 #endif
10155 #ifdef WINDOWSNT
10156 defsubr (&Sfile_system_info);
10157 defsubr (&Sdefault_printer_name);
10158 #endif
10160 defsubr (&Sset_message_beep);
10161 defsubr (&Sx_show_tip);
10162 defsubr (&Sx_hide_tip);
10163 tip_timer = Qnil;
10164 staticpro (&tip_timer);
10165 tip_frame = Qnil;
10166 staticpro (&tip_frame);
10168 last_show_tip_args = Qnil;
10169 staticpro (&last_show_tip_args);
10171 defsubr (&Sx_file_dialog);
10172 #ifdef WINDOWSNT
10173 defsubr (&Ssystem_move_file_to_trash);
10174 #endif
10179 /* Crashing and reporting backtrace. */
10181 #ifndef CYGWIN
10182 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
10183 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
10184 #endif
10185 static DWORD except_code;
10186 static PVOID except_addr;
10188 #ifndef CYGWIN
10190 /* Stack overflow recovery. */
10192 /* MinGW headers don't declare this (should be in malloc.h). Also,
10193 the function is not present pre-W2K, so make the call through
10194 a function pointer. */
10195 typedef int (__cdecl *_resetstkoflw_proc) (void);
10196 static _resetstkoflw_proc resetstkoflw;
10198 /* Re-establish the guard page at stack limit. This is needed because
10199 when a stack overflow is detected, Windows removes the guard bit
10200 from the guard page, so if we don't re-establish that protection,
10201 the next stack overflow will cause a crash. */
10202 void
10203 w32_reset_stack_overflow_guard (void)
10205 if (resetstkoflw == NULL)
10206 resetstkoflw =
10207 (_resetstkoflw_proc)GetProcAddress (GetModuleHandle ("msvcrt.dll"),
10208 "_resetstkoflw");
10209 /* We ignore the return value. If _resetstkoflw fails, the next
10210 stack overflow will crash the program. */
10211 if (resetstkoflw != NULL)
10212 (void)resetstkoflw ();
10215 static void
10216 stack_overflow_handler (void)
10218 /* Hard GC error may lead to stack overflow caused by
10219 too nested calls to mark_object. No way to survive. */
10220 if (gc_in_progress)
10221 terminate_due_to_signal (SIGSEGV, 40);
10222 #ifdef _WIN64
10223 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
10224 __builtin_longjmp (return_to_command_loop, 1);
10225 #else
10226 sys_longjmp (return_to_command_loop, 1);
10227 #endif
10230 /* This handler records the exception code and the address where it
10231 was triggered so that this info could be included in the backtrace.
10232 Without that, the backtrace in some cases has no information
10233 whatsoever about the offending code, and looks as if the top-level
10234 exception handler in the MinGW startup code was the one that
10235 crashed. We also recover from stack overflow, by calling our stack
10236 overflow handler that jumps back to top level. */
10237 static LONG CALLBACK
10238 my_exception_handler (EXCEPTION_POINTERS * exception_data)
10240 except_code = exception_data->ExceptionRecord->ExceptionCode;
10241 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
10243 /* If this is a stack overflow exception, attempt to recover. */
10244 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
10245 && exception_data->ExceptionRecord->NumberParameters == 2
10246 /* We can only longjmp to top level from the main thread. */
10247 && GetCurrentThreadId () == dwMainThreadId)
10249 /* Call stack_overflow_handler (). */
10250 #ifdef _WIN64
10251 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
10252 #else
10253 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
10254 #endif
10255 /* Zero this out, so the stale address of the stack overflow
10256 exception we handled is not displayed in some future
10257 unrelated crash. */
10258 except_addr = 0;
10259 return EXCEPTION_CONTINUE_EXECUTION;
10262 if (prev_exception_handler)
10263 return prev_exception_handler (exception_data);
10264 return EXCEPTION_EXECUTE_HANDLER;
10266 #endif
10268 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
10269 PULONG);
10271 #define BACKTRACE_LIMIT_MAX 62
10273 static int
10274 w32_backtrace (void **buffer, int limit)
10276 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
10277 HMODULE hm_kernel32 = NULL;
10279 if (!s_pfn_CaptureStackBackTrace)
10281 hm_kernel32 = LoadLibrary ("Kernel32.dll");
10282 s_pfn_CaptureStackBackTrace =
10283 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
10284 "RtlCaptureStackBackTrace");
10286 if (s_pfn_CaptureStackBackTrace)
10287 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
10288 buffer, NULL);
10289 return 0;
10292 void
10293 emacs_abort (void)
10295 int button;
10296 button = MessageBox (NULL,
10297 "A fatal error has occurred!\n\n"
10298 "Would you like to attach a debugger?\n\n"
10299 "Select:\n"
10300 "YES -- to debug Emacs, or\n"
10301 "NO -- to abort Emacs and produce a backtrace\n"
10302 " (emacs_backtrace.txt in current directory)."
10303 #if __GNUC__
10304 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
10305 "\"continue\" inside GDB before clicking YES.)"
10306 #endif
10307 , "Emacs Abort Dialog",
10308 MB_ICONEXCLAMATION | MB_TASKMODAL
10309 | MB_SETFOREGROUND | MB_YESNO);
10310 switch (button)
10312 case IDYES:
10313 DebugBreak ();
10314 exit (2); /* tell the compiler we will never return */
10315 case IDNO:
10316 default:
10318 void *stack[BACKTRACE_LIMIT_MAX + 1];
10319 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
10321 if (i)
10323 int errfile_fd = -1;
10324 int j;
10325 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
10326 /* The type below should really be 'void *', but
10327 INT_BUFSIZE_BOUND cannot handle that without
10328 triggering compiler warnings (under certain
10329 pedantic warning switches), it wants an
10330 integer type. */
10331 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
10332 #ifdef CYGWIN
10333 int stderr_fd = 2;
10334 #else
10335 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
10336 int stderr_fd = -1;
10338 if (errout && errout != INVALID_HANDLE_VALUE)
10339 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
10340 #endif
10342 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
10343 but not on Windows 7. addr2line doesn't mind a missing
10344 "0x", but will be confused by an extra one. */
10345 if (except_addr)
10346 sprintf (buf, "\r\nException 0x%x at this address:\r\n%p\r\n",
10347 (unsigned int) except_code, except_addr);
10348 if (stderr_fd >= 0)
10350 if (except_addr)
10351 write (stderr_fd, buf, strlen (buf));
10352 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
10354 #ifdef CYGWIN
10355 #define _open open
10356 #endif
10357 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
10358 if (errfile_fd >= 0)
10360 lseek (errfile_fd, 0L, SEEK_END);
10361 if (except_addr)
10362 write (errfile_fd, buf, strlen (buf));
10363 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
10366 for (j = 0; j < i; j++)
10368 /* stack[] gives the return addresses, whereas we want
10369 the address of the call, so decrease each address
10370 by approximate size of 1 CALL instruction. */
10371 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
10372 if (stderr_fd >= 0)
10373 write (stderr_fd, buf, strlen (buf));
10374 if (errfile_fd >= 0)
10375 write (errfile_fd, buf, strlen (buf));
10377 if (i == BACKTRACE_LIMIT_MAX)
10379 if (stderr_fd >= 0)
10380 write (stderr_fd, "...\r\n", 5);
10381 if (errfile_fd >= 0)
10382 write (errfile_fd, "...\r\n", 5);
10384 if (errfile_fd >= 0)
10385 close (errfile_fd);
10387 abort ();
10388 break;
10395 /* Initialization. */
10398 globals_of_w32fns is used to initialize those global variables that
10399 must always be initialized on startup even when the global variable
10400 initialized is non zero (see the function main in emacs.c).
10401 globals_of_w32fns is called from syms_of_w32fns when the global
10402 variable initialized is 0 and directly from main when initialized
10403 is non zero.
10405 void
10406 globals_of_w32fns (void)
10408 HMODULE user32_lib = GetModuleHandle ("user32.dll");
10410 TrackMouseEvent not available in all versions of Windows, so must load
10411 it dynamically. Do it once, here, instead of every time it is used.
10413 track_mouse_event_fn = (TrackMouseEvent_Proc)
10414 GetProcAddress (user32_lib, "TrackMouseEvent");
10416 monitor_from_point_fn = (MonitorFromPoint_Proc)
10417 GetProcAddress (user32_lib, "MonitorFromPoint");
10418 get_monitor_info_fn = (GetMonitorInfo_Proc)
10419 GetProcAddress (user32_lib, "GetMonitorInfoA");
10420 monitor_from_window_fn = (MonitorFromWindow_Proc)
10421 GetProcAddress (user32_lib, "MonitorFromWindow");
10422 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
10423 GetProcAddress (user32_lib, "EnumDisplayMonitors");
10424 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
10425 GetProcAddress (user32_lib, "GetTitleBarInfo");
10428 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
10429 get_composition_string_fn = (ImmGetCompositionString_Proc)
10430 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
10431 get_ime_context_fn = (ImmGetContext_Proc)
10432 GetProcAddress (imm32_lib, "ImmGetContext");
10433 release_ime_context_fn = (ImmReleaseContext_Proc)
10434 GetProcAddress (imm32_lib, "ImmReleaseContext");
10435 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
10436 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
10439 except_code = 0;
10440 except_addr = 0;
10441 #ifndef CYGWIN
10442 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
10443 resetstkoflw = NULL;
10444 #endif
10446 DEFVAR_INT ("w32-ansi-code-page",
10447 w32_ansi_code_page,
10448 doc: /* The ANSI code page used by the system. */);
10449 w32_ansi_code_page = GetACP ();
10451 if (os_subtype == OS_NT)
10452 w32_unicode_gui = 1;
10453 else
10454 w32_unicode_gui = 0;
10456 after_deadkey = -1;
10458 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
10459 InitCommonControls ();
10461 syms_of_w32uniscribe ();
10464 #ifdef NTGUI_UNICODE
10466 Lisp_Object
10467 ntgui_encode_system (Lisp_Object str)
10469 Lisp_Object encoded;
10470 to_unicode (str, &encoded);
10471 return encoded;
10474 #endif /* NTGUI_UNICODE */