Merge from origin/emacs-25
[emacs.git] / src / w32fns.c
blobdd16d74439f53c479031df72745e22c2ac7ec3a8
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 /* Allow time for Emacs to attempt an orderly shutdown. If we
4805 return, the process will be terminated immediately. FIXME:
4806 1000 seconds is too long to sleep if the shutdown attempt
4807 fails (see bug#25875). But if it fails, we want to find out
4808 about it, so let's leave 1000 for now. */
4809 sleep (1000);
4811 case WM_WINDOWPOSCHANGING:
4812 /* Don't restrict the sizing of any kind of frames. If the window
4813 manager doesn't, there's no reason to do it ourselves. */
4814 return 0;
4816 case WM_GETMINMAXINFO:
4817 /* Hack to allow resizing the Emacs frame above the screen size.
4818 Note that Windows 9x limits coordinates to 16-bits. */
4819 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
4820 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
4821 return 0;
4823 case WM_SETCURSOR:
4824 if (LOWORD (lParam) == HTCLIENT)
4826 f = x_window_to_frame (dpyinfo, hwnd);
4827 if (f)
4829 if (f->output_data.w32->hourglass_p
4830 && !menubar_in_use && !current_popup_menu)
4831 SetCursor (f->output_data.w32->hourglass_cursor);
4832 else if (f->pointer_invisible)
4833 SetCursor (NULL);
4834 else
4835 SetCursor (f->output_data.w32->current_cursor);
4838 return 0;
4840 goto dflt;
4842 case WM_EMACS_SETCURSOR:
4844 Cursor cursor = (Cursor) wParam;
4845 f = x_window_to_frame (dpyinfo, hwnd);
4846 if (f && cursor)
4848 f->output_data.w32->current_cursor = cursor;
4849 /* Don't change the cursor while menu-bar menu is in use. */
4850 if (!f->output_data.w32->menubar_active
4851 && !f->output_data.w32->hourglass_p)
4853 if (f->pointer_invisible)
4854 SetCursor (NULL);
4855 else
4856 SetCursor (cursor);
4859 return 0;
4862 case WM_EMACS_SHOWCURSOR:
4864 ShowCursor ((BOOL) wParam);
4866 return 0;
4869 case WM_EMACS_CREATEVSCROLLBAR:
4870 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
4871 (struct scroll_bar *) lParam);
4873 case WM_EMACS_CREATEHSCROLLBAR:
4874 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
4875 (struct scroll_bar *) lParam);
4877 case WM_EMACS_SHOWWINDOW:
4878 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4880 case WM_EMACS_BRINGTOTOP:
4881 case WM_EMACS_SETFOREGROUND:
4883 HWND foreground_window;
4884 DWORD foreground_thread, retval;
4886 /* On NT 5.0, and apparently Windows 98, it is necessary to
4887 attach to the thread that currently has focus in order to
4888 pull the focus away from it. */
4889 foreground_window = GetForegroundWindow ();
4890 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4891 if (!foreground_window
4892 || foreground_thread == GetCurrentThreadId ()
4893 || !AttachThreadInput (GetCurrentThreadId (),
4894 foreground_thread, TRUE))
4895 foreground_thread = 0;
4897 retval = SetForegroundWindow ((HWND) wParam);
4898 if (msg == WM_EMACS_BRINGTOTOP)
4899 retval = BringWindowToTop ((HWND) wParam);
4901 /* Detach from the previous foreground thread. */
4902 if (foreground_thread)
4903 AttachThreadInput (GetCurrentThreadId (),
4904 foreground_thread, FALSE);
4906 return retval;
4909 case WM_EMACS_SETWINDOWPOS:
4911 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4912 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4913 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4916 case WM_EMACS_DESTROYWINDOW:
4917 DragAcceptFiles ((HWND) wParam, FALSE);
4918 return DestroyWindow ((HWND) wParam);
4920 case WM_EMACS_HIDE_CARET:
4921 return HideCaret (hwnd);
4923 case WM_EMACS_SHOW_CARET:
4924 return ShowCaret (hwnd);
4926 case WM_EMACS_DESTROY_CARET:
4927 w32_system_caret_hwnd = NULL;
4928 w32_visible_system_caret_hwnd = NULL;
4929 return DestroyCaret ();
4931 case WM_EMACS_TRACK_CARET:
4932 /* If there is currently no system caret, create one. */
4933 if (w32_system_caret_hwnd == NULL)
4935 /* Use the default caret width, and avoid changing it
4936 unnecessarily, as it confuses screen reader software. */
4937 w32_system_caret_hwnd = hwnd;
4938 CreateCaret (hwnd, NULL, 0,
4939 w32_system_caret_height);
4942 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4943 return 0;
4944 /* Ensure visible caret gets turned on when requested. */
4945 else if (w32_use_visible_system_caret
4946 && w32_visible_system_caret_hwnd != hwnd)
4948 w32_visible_system_caret_hwnd = hwnd;
4949 return ShowCaret (hwnd);
4951 /* Ensure visible caret gets turned off when requested. */
4952 else if (!w32_use_visible_system_caret
4953 && w32_visible_system_caret_hwnd)
4955 w32_visible_system_caret_hwnd = NULL;
4956 return HideCaret (hwnd);
4958 else
4959 return 1;
4961 case WM_EMACS_TRACKPOPUPMENU:
4963 UINT flags;
4964 POINT *pos;
4965 int retval;
4966 pos = (POINT *)lParam;
4967 flags = TPM_CENTERALIGN;
4968 if (button_state & LMOUSE)
4969 flags |= TPM_LEFTBUTTON;
4970 else if (button_state & RMOUSE)
4971 flags |= TPM_RIGHTBUTTON;
4973 /* Remember we did a SetCapture on the initial mouse down event,
4974 so for safety, we make sure the capture is canceled now. */
4975 ReleaseCapture ();
4976 button_state = 0;
4978 /* Use menubar_active to indicate that WM_INITMENU is from
4979 TrackPopupMenu below, and should be ignored. */
4980 f = x_window_to_frame (dpyinfo, hwnd);
4981 if (f)
4982 f->output_data.w32->menubar_active = 1;
4984 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4985 0, hwnd, NULL))
4987 MSG amsg;
4988 /* Eat any mouse messages during popupmenu */
4989 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4990 PM_REMOVE));
4991 /* Get the menu selection, if any */
4992 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4994 retval = LOWORD (amsg.wParam);
4996 else
4998 retval = 0;
5001 else
5003 retval = -1;
5006 return retval;
5008 case WM_EMACS_FILENOTIFY:
5009 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5010 return 1;
5012 default:
5013 /* Check for messages registered at runtime. */
5014 if (msg == msh_mousewheel)
5016 wmsg.dwModifiers = w32_get_modifiers ();
5017 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
5018 signal_user_input ();
5019 return 0;
5022 dflt:
5023 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
5026 /* The most common default return code for handled messages is 0. */
5027 return 0;
5030 static void
5031 my_create_window (struct frame * f)
5033 MSG msg;
5034 static int coords[2];
5035 Lisp_Object left, top;
5036 struct w32_display_info *dpyinfo = &one_w32_display_info;
5038 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
5039 anything that is not a number and is not Qunbound. */
5040 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
5041 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
5042 if (EQ (left, Qunbound))
5043 coords[0] = CW_USEDEFAULT;
5044 else
5045 coords[0] = XINT (left);
5046 if (EQ (top, Qunbound))
5047 coords[1] = CW_USEDEFAULT;
5048 else
5049 coords[1] = XINT (top);
5051 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
5052 (WPARAM)f, (LPARAM)coords))
5053 emacs_abort ();
5054 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
5058 /* Create a tooltip window. Unlike my_create_window, we do not do this
5059 indirectly via the Window thread, as we do not need to process Window
5060 messages for the tooltip. Creating tooltips indirectly also creates
5061 deadlocks when tooltips are created for menu items. */
5062 static void
5063 my_create_tip_window (struct frame *f)
5065 RECT rect;
5067 rect.left = rect.top = 0;
5068 rect.right = FRAME_PIXEL_WIDTH (f);
5069 rect.bottom = FRAME_PIXEL_HEIGHT (f);
5071 AdjustWindowRect (&rect, f->output_data.w32->dwStyle, false);
5073 tip_window = FRAME_W32_WINDOW (f)
5074 = CreateWindow (EMACS_CLASS,
5075 f->namebuf,
5076 f->output_data.w32->dwStyle,
5077 f->left_pos,
5078 f->top_pos,
5079 rect.right - rect.left,
5080 rect.bottom - rect.top,
5081 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
5082 NULL,
5083 hinst,
5084 NULL);
5086 if (tip_window)
5088 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
5089 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
5090 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
5091 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
5093 /* Tip frames have no scrollbars. */
5094 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
5095 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
5097 /* Do this to discard the default setting specified by our parent. */
5098 ShowWindow (tip_window, SW_HIDE);
5103 /* Create and set up the w32 window for frame F. */
5105 static void
5106 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
5108 block_input ();
5110 /* Use the resource name as the top-level window name
5111 for looking up resources. Make a non-Lisp copy
5112 for the window manager, so GC relocation won't bother it.
5114 Elsewhere we specify the window name for the window manager. */
5115 f->namebuf = xlispstrdup (Vx_resource_name);
5117 my_create_window (f);
5119 validate_x_resource_name ();
5121 /* x_set_name normally ignores requests to set the name if the
5122 requested name is the same as the current name. This is the one
5123 place where that assumption isn't correct; f->name is set, but
5124 the server hasn't been told. */
5126 Lisp_Object name;
5127 int explicit = f->explicit_name;
5129 f->explicit_name = 0;
5130 name = f->name;
5131 fset_name (f, Qnil);
5132 x_set_name (f, name, explicit);
5135 unblock_input ();
5137 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
5138 initialize_frame_menubar (f);
5140 if (FRAME_W32_WINDOW (f) == 0)
5141 error ("Unable to create window");
5144 /* Handle the icon stuff for this window. Perhaps later we might
5145 want an x_set_icon_position which can be called interactively as
5146 well. */
5148 static void
5149 x_icon (struct frame *f, Lisp_Object parms)
5151 Lisp_Object icon_x, icon_y;
5152 struct w32_display_info *dpyinfo = &one_w32_display_info;
5154 /* Set the position of the icon. Note that Windows 95 groups all
5155 icons in the tray. */
5156 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
5157 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
5158 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
5160 CHECK_NUMBER (icon_x);
5161 CHECK_NUMBER (icon_y);
5163 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
5164 error ("Both left and top icon corners of icon must be specified");
5166 block_input ();
5168 #if 0 /* TODO */
5169 /* Start up iconic or window? */
5170 x_wm_set_window_state
5171 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
5172 ? IconicState
5173 : NormalState));
5175 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
5176 ? f->icon_name
5177 : f->name)));
5178 #endif
5180 unblock_input ();
5184 static void
5185 x_make_gc (struct frame *f)
5187 XGCValues gc_values;
5189 block_input ();
5191 /* Create the GC's of this frame.
5192 Note that many default values are used. */
5194 /* Normal video */
5195 gc_values.font = FRAME_FONT (f);
5197 /* Cursor has cursor-color background, background-color foreground. */
5198 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
5199 gc_values.background = f->output_data.w32->cursor_pixel;
5200 f->output_data.w32->cursor_gc
5201 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
5202 (GCFont | GCForeground | GCBackground),
5203 &gc_values);
5205 /* Reliefs. */
5206 f->output_data.w32->white_relief.gc = 0;
5207 f->output_data.w32->black_relief.gc = 0;
5209 unblock_input ();
5213 /* Handler for signals raised during x_create_frame and
5214 x_create_tip_frame. FRAME is the frame which is partially
5215 constructed. */
5217 static Lisp_Object
5218 unwind_create_frame (Lisp_Object frame)
5220 struct frame *f = XFRAME (frame);
5222 /* If frame is ``official'', nothing to do. */
5223 if (NILP (Fmemq (frame, Vframe_list)))
5225 #ifdef GLYPH_DEBUG
5226 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5228 /* If the frame's image cache refcount is still the same as our
5229 private shadow variable, it means we are unwinding a frame
5230 for which we didn't yet call init_frame_faces, where the
5231 refcount is incremented. Therefore, we increment it here, so
5232 that free_frame_faces, called in x_free_frame_resources
5233 below, will not mistakenly decrement the counter that was not
5234 incremented yet to account for this new frame. */
5235 if (FRAME_IMAGE_CACHE (f) != NULL
5236 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
5237 FRAME_IMAGE_CACHE (f)->refcount++;
5238 #endif
5240 x_free_frame_resources (f);
5241 free_glyphs (f);
5243 #ifdef GLYPH_DEBUG
5244 /* Check that reference counts are indeed correct. */
5245 eassert (dpyinfo->reference_count == dpyinfo_refcount);
5246 eassert ((dpyinfo->terminal->image_cache == NULL
5247 && image_cache_refcount == 0)
5248 || (dpyinfo->terminal->image_cache != NULL
5249 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
5250 #endif
5251 return Qt;
5254 return Qnil;
5257 static void
5258 do_unwind_create_frame (Lisp_Object frame)
5260 unwind_create_frame (frame);
5263 static void
5264 x_default_font_parameter (struct frame *f, Lisp_Object parms)
5266 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
5267 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
5268 RES_TYPE_STRING);
5269 Lisp_Object font;
5270 if (EQ (font_param, Qunbound))
5271 font_param = Qnil;
5272 font = !NILP (font_param) ? font_param
5273 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
5275 if (!STRINGP (font))
5277 int i;
5278 static const char *names[]
5279 = { "Courier New-10",
5280 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
5281 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
5282 "Fixedsys",
5283 NULL };
5285 for (i = 0; names[i]; i++)
5287 font = font_open_by_name (f, build_unibyte_string (names[i]));
5288 if (! NILP (font))
5289 break;
5291 if (NILP (font))
5292 error ("No suitable font was found");
5294 else if (!NILP (font_param))
5296 /* Remember the explicit font parameter, so we can re-apply it after
5297 we've applied the `default' face settings. */
5298 x_set_frame_parameters (f, Fcons (Fcons (Qfont_parameter, font_param),
5299 Qnil));
5301 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
5304 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
5305 1, 1, 0,
5306 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
5307 Return an Emacs frame object.
5308 PARAMETERS is an alist of frame parameters.
5309 If the parameters specify that the frame should not have a minibuffer,
5310 and do not specify a specific minibuffer window to use,
5311 then `default-minibuffer-frame' must be a frame whose minibuffer can
5312 be shared by the new frame.
5314 This function is an internal primitive--use `make-frame' instead. */)
5315 (Lisp_Object parameters)
5317 struct frame *f;
5318 Lisp_Object frame, tem;
5319 Lisp_Object name;
5320 bool minibuffer_only = false;
5321 long window_prompting = 0;
5322 ptrdiff_t count = SPECPDL_INDEX ();
5323 Lisp_Object display;
5324 struct w32_display_info *dpyinfo = NULL;
5325 Lisp_Object parent;
5326 struct kboard *kb;
5327 int x_width = 0, x_height = 0;
5329 if (!FRAME_W32_P (SELECTED_FRAME ())
5330 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
5331 error ("Cannot create a GUI frame in a -nw session");
5333 /* Make copy of frame parameters because the original is in pure
5334 storage now. */
5335 parameters = Fcopy_alist (parameters);
5337 /* Use this general default value to start with
5338 until we know if this frame has a specified name. */
5339 Vx_resource_name = Vinvocation_name;
5341 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
5342 if (EQ (display, Qunbound))
5343 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
5344 if (EQ (display, Qunbound))
5345 display = Qnil;
5346 dpyinfo = check_x_display_info (display);
5347 kb = dpyinfo->terminal->kboard;
5349 if (!dpyinfo->terminal->name)
5350 error ("Terminal is not live, can't create new frames on it");
5352 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
5353 if (!STRINGP (name)
5354 && ! EQ (name, Qunbound)
5355 && ! NILP (name))
5356 error ("Invalid frame name--not a string or nil");
5358 if (STRINGP (name))
5359 Vx_resource_name = name;
5361 /* See if parent window is specified. */
5362 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
5363 if (EQ (parent, Qunbound))
5364 parent = Qnil;
5365 if (! NILP (parent))
5366 CHECK_NUMBER (parent);
5368 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
5369 /* No need to protect DISPLAY because that's not used after passing
5370 it to make_frame_without_minibuffer. */
5371 frame = Qnil;
5372 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
5373 RES_TYPE_SYMBOL);
5374 if (EQ (tem, Qnone) || NILP (tem))
5375 f = make_frame_without_minibuffer (Qnil, kb, display);
5376 else if (EQ (tem, Qonly))
5378 f = make_minibuffer_frame ();
5379 minibuffer_only = true;
5381 else if (WINDOWP (tem))
5382 f = make_frame_without_minibuffer (tem, kb, display);
5383 else
5384 f = make_frame (true);
5386 XSETFRAME (frame, f);
5388 /* By default, make scrollbars the system standard width and height. */
5389 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
5390 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
5392 f->terminal = dpyinfo->terminal;
5394 f->output_method = output_w32;
5395 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5396 FRAME_FONTSET (f) = -1;
5398 fset_icon_name
5399 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
5400 RES_TYPE_STRING));
5401 if (! STRINGP (f->icon_name))
5402 fset_icon_name (f, Qnil);
5404 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
5406 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
5407 record_unwind_protect (do_unwind_create_frame, frame);
5409 #ifdef GLYPH_DEBUG
5410 image_cache_refcount =
5411 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5412 dpyinfo_refcount = dpyinfo->reference_count;
5413 #endif /* GLYPH_DEBUG */
5415 /* Specify the parent under which to make this window. */
5416 if (!NILP (parent))
5418 /* Cast to UINT_PTR shuts up compiler warnings about cast to
5419 pointer from integer of different size. */
5420 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
5421 f->output_data.w32->explicit_parent = true;
5423 else
5425 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5426 f->output_data.w32->explicit_parent = false;
5429 /* Set the name; the functions to which we pass f expect the name to
5430 be set. */
5431 if (EQ (name, Qunbound) || NILP (name))
5433 fset_name (f, build_string (dpyinfo->w32_id_name));
5434 f->explicit_name = false;
5436 else
5438 fset_name (f, name);
5439 f->explicit_name = true;
5440 /* Use the frame's title when getting resources for this frame. */
5441 specbind (Qx_resource_name, name);
5444 if (uniscribe_available)
5445 register_font_driver (&uniscribe_font_driver, f);
5446 register_font_driver (&w32font_driver, f);
5448 x_default_parameter (f, parameters, Qfont_backend, Qnil,
5449 "fontBackend", "FontBackend", RES_TYPE_STRING);
5451 /* Extract the window parameters from the supplied values
5452 that are needed to determine window geometry. */
5453 x_default_font_parameter (f, parameters);
5455 x_default_parameter (f, parameters, Qborder_width, make_number (2),
5456 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5458 /* We recognize either internalBorderWidth or internalBorder
5459 (which is what xterm calls it). */
5460 if (NILP (Fassq (Qinternal_border_width, parameters)))
5462 Lisp_Object value;
5464 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
5465 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
5466 if (! EQ (value, Qunbound))
5467 parameters = Fcons (Fcons (Qinternal_border_width, value),
5468 parameters);
5470 /* Default internalBorderWidth to 0 on Windows to match other programs. */
5471 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
5472 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
5473 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
5474 NULL, NULL, RES_TYPE_NUMBER);
5475 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
5476 NULL, NULL, RES_TYPE_NUMBER);
5477 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
5478 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5479 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
5480 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
5482 /* Also do the stuff which must be set before the window exists. */
5483 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
5484 "foreground", "Foreground", RES_TYPE_STRING);
5485 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
5486 "background", "Background", RES_TYPE_STRING);
5487 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
5488 "pointerColor", "Foreground", RES_TYPE_STRING);
5489 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
5490 "borderColor", "BorderColor", RES_TYPE_STRING);
5491 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
5492 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
5493 x_default_parameter (f, parameters, Qline_spacing, Qnil,
5494 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
5495 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
5496 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
5497 x_default_parameter (f, parameters, Qright_fringe, Qnil,
5498 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
5499 /* Process alpha here (Bug#16619). */
5500 x_default_parameter (f, parameters, Qalpha, Qnil,
5501 "alpha", "Alpha", RES_TYPE_NUMBER);
5503 /* Init faces first since we need the frame's column width/line
5504 height in various occasions. */
5505 init_frame_faces (f);
5507 /* The following call of change_frame_size is needed since otherwise
5508 x_set_tool_bar_lines will already work with the character sizes
5509 installed by init_frame_faces while the frame's pixel size is
5510 still calculated from a character size of 1 and we subsequently
5511 hit the (height >= 0) assertion in window_box_height.
5513 The non-pixelwise code apparently worked around this because it
5514 had one frame line vs one toolbar line which left us with a zero
5515 root window height which was obviously wrong as well ... */
5516 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
5517 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
5518 Qx_create_frame_1);
5520 /* The X resources controlling the menu-bar and tool-bar are
5521 processed specially at startup, and reflected in the mode
5522 variables; ignore them here. */
5523 x_default_parameter (f, parameters, Qmenu_bar_lines,
5524 NILP (Vmenu_bar_mode)
5525 ? make_number (0) : make_number (1),
5526 NULL, NULL, RES_TYPE_NUMBER);
5527 x_default_parameter (f, parameters, Qtool_bar_lines,
5528 NILP (Vtool_bar_mode)
5529 ? make_number (0) : make_number (1),
5530 NULL, NULL, RES_TYPE_NUMBER);
5532 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
5533 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
5534 x_default_parameter (f, parameters, Qtitle, Qnil,
5535 "title", "Title", RES_TYPE_STRING);
5537 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
5538 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5540 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
5541 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
5542 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
5543 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
5544 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
5545 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
5546 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
5548 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
5550 window_prompting = x_figure_window_size (f, parameters, true, &x_width, &x_height);
5552 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
5553 f->no_split = minibuffer_only || EQ (tem, Qt);
5555 w32_window (f, window_prompting, minibuffer_only);
5556 x_icon (f, parameters);
5558 x_make_gc (f);
5560 /* Now consider the frame official. */
5561 f->terminal->reference_count++;
5562 FRAME_DISPLAY_INFO (f)->reference_count++;
5563 Vframe_list = Fcons (frame, Vframe_list);
5565 /* We need to do this after creating the window, so that the
5566 icon-creation functions can say whose icon they're describing. */
5567 x_default_parameter (f, parameters, Qicon_type, Qnil,
5568 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
5570 x_default_parameter (f, parameters, Qauto_raise, Qnil,
5571 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5572 x_default_parameter (f, parameters, Qauto_lower, Qnil,
5573 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5574 x_default_parameter (f, parameters, Qcursor_type, Qbox,
5575 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5576 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
5577 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
5578 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
5579 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
5581 /* Allow x_set_window_size, now. */
5582 f->can_x_set_window_size = true;
5584 if (x_width > 0)
5585 SET_FRAME_WIDTH (f, x_width);
5586 if (x_height > 0)
5587 SET_FRAME_HEIGHT (f, x_height);
5589 /* Tell the server what size and position, etc, we want, and how
5590 badly we want them. This should be done after we have the menu
5591 bar so that its size can be taken into account. */
5592 block_input ();
5593 x_wm_set_size_hint (f, window_prompting, false);
5594 unblock_input ();
5596 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
5597 Qx_create_frame_2);
5599 /* Process fullscreen parameter here in the hope that normalizing a
5600 fullheight/fullwidth frame will produce the size set by the last
5601 adjust_frame_size call. */
5602 x_default_parameter (f, parameters, Qfullscreen, Qnil,
5603 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
5605 /* Make the window appear on the frame and enable display, unless
5606 the caller says not to. However, with explicit parent, Emacs
5607 cannot control visibility, so don't try. */
5608 if (! f->output_data.w32->explicit_parent)
5610 Lisp_Object visibility;
5612 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
5613 if (EQ (visibility, Qunbound))
5614 visibility = Qt;
5616 if (EQ (visibility, Qicon))
5617 x_iconify_frame (f);
5618 else if (! NILP (visibility))
5619 x_make_frame_visible (f);
5620 else
5622 /* Must have been Qnil. */
5627 /* Initialize `default-minibuffer-frame' in case this is the first
5628 frame on this terminal. */
5629 if (FRAME_HAS_MINIBUF_P (f)
5630 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
5631 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
5632 kset_default_minibuffer_frame (kb, frame);
5634 /* All remaining specified parameters, which have not been "used"
5635 by x_get_arg and friends, now go in the misc. alist of the frame. */
5636 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
5637 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
5638 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
5640 /* Make sure windows on this frame appear in calls to next-window
5641 and similar functions. */
5642 Vwindow_list = Qnil;
5644 return unbind_to (count, frame);
5647 /* FRAME is used only to get a handle on the X display. We don't pass the
5648 display info directly because we're called from frame.c, which doesn't
5649 know about that structure. */
5650 Lisp_Object
5651 x_get_focus_frame (struct frame *frame)
5653 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
5654 Lisp_Object xfocus;
5655 if (! dpyinfo->w32_focus_frame)
5656 return Qnil;
5658 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
5659 return xfocus;
5662 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
5663 doc: /* Internal function called by `color-defined-p', which see.
5664 \(Note that the Nextstep version of this function ignores FRAME.) */)
5665 (Lisp_Object color, Lisp_Object frame)
5667 XColor foo;
5668 struct frame *f = decode_window_system_frame (frame);
5670 CHECK_STRING (color);
5672 if (w32_defined_color (f, SSDATA (color), &foo, false))
5673 return Qt;
5674 else
5675 return Qnil;
5678 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
5679 doc: /* Internal function called by `color-values', which see. */)
5680 (Lisp_Object color, Lisp_Object frame)
5682 XColor foo;
5683 struct frame *f = decode_window_system_frame (frame);
5685 CHECK_STRING (color);
5687 if (w32_defined_color (f, SSDATA (color), &foo, false))
5688 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
5689 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
5690 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
5691 else
5692 return Qnil;
5695 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
5696 doc: /* Internal function called by `display-color-p', which see. */)
5697 (Lisp_Object display)
5699 struct w32_display_info *dpyinfo = check_x_display_info (display);
5701 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
5702 return Qnil;
5704 return Qt;
5707 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
5708 Sx_display_grayscale_p, 0, 1, 0,
5709 doc: /* Return t if DISPLAY supports shades of gray.
5710 Note that color displays do support shades of gray.
5711 The optional argument DISPLAY specifies which display to ask about.
5712 DISPLAY should be either a frame or a display name (a string).
5713 If omitted or nil, that stands for the selected frame's display. */)
5714 (Lisp_Object display)
5716 struct w32_display_info *dpyinfo = check_x_display_info (display);
5718 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
5719 return Qnil;
5721 return Qt;
5724 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
5725 Sx_display_pixel_width, 0, 1, 0,
5726 doc: /* Return the width in pixels of DISPLAY.
5727 The optional argument DISPLAY specifies which display to ask about.
5728 DISPLAY should be either a frame or a display name (a string).
5729 If omitted or nil, that stands for the selected frame's display.
5731 On \"multi-monitor\" setups this refers to the pixel width for all
5732 physical monitors associated with DISPLAY. To get information for
5733 each physical monitor, use `display-monitor-attributes-list'. */)
5734 (Lisp_Object display)
5736 struct w32_display_info *dpyinfo = check_x_display_info (display);
5738 return make_number (x_display_pixel_width (dpyinfo));
5741 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
5742 Sx_display_pixel_height, 0, 1, 0,
5743 doc: /* Return the height in pixels of DISPLAY.
5744 The optional argument DISPLAY specifies which display to ask about.
5745 DISPLAY should be either a frame or a display name (a string).
5746 If omitted or nil, that stands for the selected frame's display.
5748 On \"multi-monitor\" setups this refers to the pixel height for all
5749 physical monitors associated with DISPLAY. To get information for
5750 each physical monitor, use `display-monitor-attributes-list'. */)
5751 (Lisp_Object display)
5753 struct w32_display_info *dpyinfo = check_x_display_info (display);
5755 return make_number (x_display_pixel_height (dpyinfo));
5758 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
5759 0, 1, 0,
5760 doc: /* Return the number of bitplanes of DISPLAY.
5761 The optional argument DISPLAY specifies which display to ask about.
5762 DISPLAY should be either a frame or a display name (a string).
5763 If omitted or nil, that stands for the selected frame's display. */)
5764 (Lisp_Object display)
5766 struct w32_display_info *dpyinfo = check_x_display_info (display);
5768 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
5771 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
5772 0, 1, 0,
5773 doc: /* Return the number of color cells of DISPLAY.
5774 The optional argument DISPLAY specifies which display to ask about.
5775 DISPLAY should be either a frame or a display name (a string).
5776 If omitted or nil, that stands for the selected frame's display. */)
5777 (Lisp_Object display)
5779 struct w32_display_info *dpyinfo = check_x_display_info (display);
5780 int cap;
5782 /* Don't use NCOLORS: it returns incorrect results under remote
5783 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
5784 * overflow and because probably is more meaningful on Windows
5785 * anyway. */
5787 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
5788 return make_number (cap);
5791 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
5792 Sx_server_max_request_size,
5793 0, 1, 0,
5794 doc: /* Return the maximum request size of the server of DISPLAY.
5795 The optional argument DISPLAY specifies which display to ask about.
5796 DISPLAY should be either a frame or a display name (a string).
5797 If omitted or nil, that stands for the selected frame's display. */)
5798 (Lisp_Object display)
5800 return make_number (1);
5803 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
5804 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
5806 \(Labeling every distributor as a "vendor" embodies the false assumption
5807 that operating systems cannot be developed and distributed noncommercially.)
5809 For GNU and Unix systems, this queries the X server software; for
5810 MS-Windows, this queries the OS.
5812 The optional argument TERMINAL specifies which display to ask about.
5813 TERMINAL should be a terminal object, a frame or a display name (a string).
5814 If omitted or nil, that stands for the selected frame's display. */)
5815 (Lisp_Object terminal)
5817 return build_string ("Microsoft Corp.");
5820 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
5821 doc: /* Return the version numbers of the GUI software on TERMINAL.
5822 The value is a list of three integers specifying the version of the GUI
5823 software in use.
5825 For GNU and Unix system, the first 2 numbers are the version of the X
5826 Protocol used on TERMINAL and the 3rd number is the distributor-specific
5827 release number. For MS-Windows, the 3 numbers report the version and
5828 the build number of the OS.
5830 See also the function `x-server-vendor'.
5832 The optional argument TERMINAL specifies which display to ask about.
5833 TERMINAL should be a terminal object, a frame or a display name (a string).
5834 If omitted or nil, that stands for the selected frame's display. */)
5835 (Lisp_Object terminal)
5837 return list3i (w32_major_version, w32_minor_version, w32_build_number);
5840 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
5841 doc: /* Return the number of screens on the server of DISPLAY.
5842 The optional argument DISPLAY specifies which display to ask about.
5843 DISPLAY should be either a frame or a display name (a string).
5844 If omitted or nil, that stands for the selected frame's display. */)
5845 (Lisp_Object display)
5847 return make_number (1);
5850 DEFUN ("x-display-mm-height", Fx_display_mm_height,
5851 Sx_display_mm_height, 0, 1, 0,
5852 doc: /* Return the height in millimeters of DISPLAY.
5853 The optional argument DISPLAY specifies which display to ask about.
5854 DISPLAY should be either a frame or a display name (a string).
5855 If omitted or nil, that stands for the selected frame's display.
5857 On \"multi-monitor\" setups this refers to the height in millimeters for
5858 all physical monitors associated with DISPLAY. To get information
5859 for each physical monitor, use `display-monitor-attributes-list'. */)
5860 (Lisp_Object display)
5862 struct w32_display_info *dpyinfo = check_x_display_info (display);
5863 HDC hdc;
5864 double mm_per_pixel;
5866 hdc = GetDC (NULL);
5867 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5868 / GetDeviceCaps (hdc, VERTRES));
5869 ReleaseDC (NULL, hdc);
5871 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5874 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5875 doc: /* Return the width in millimeters of DISPLAY.
5876 The optional argument DISPLAY specifies which display to ask about.
5877 DISPLAY should be either a frame or a display name (a string).
5878 If omitted or nil, that stands for the selected frame's display.
5880 On \"multi-monitor\" setups this refers to the width in millimeters for
5881 all physical monitors associated with TERMINAL. To get information
5882 for each physical monitor, use `display-monitor-attributes-list'. */)
5883 (Lisp_Object display)
5885 struct w32_display_info *dpyinfo = check_x_display_info (display);
5886 HDC hdc;
5887 double mm_per_pixel;
5889 hdc = GetDC (NULL);
5890 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5891 / GetDeviceCaps (hdc, HORZRES));
5892 ReleaseDC (NULL, hdc);
5894 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5897 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5898 Sx_display_backing_store, 0, 1, 0,
5899 doc: /* Return an indication of whether DISPLAY does backing store.
5900 The value may be `always', `when-mapped', or `not-useful'.
5901 The optional argument DISPLAY specifies which display to ask about.
5902 DISPLAY should be either a frame or a display name (a string).
5903 If omitted or nil, that stands for the selected frame's display. */)
5904 (Lisp_Object display)
5906 return intern ("not-useful");
5909 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5910 Sx_display_visual_class, 0, 1, 0,
5911 doc: /* Return the visual class of DISPLAY.
5912 The value is one of the symbols `static-gray', `gray-scale',
5913 `static-color', `pseudo-color', `true-color', or `direct-color'.
5915 The optional argument DISPLAY specifies which display to ask about.
5916 DISPLAY should be either a frame or a display name (a string).
5917 If omitted or nil, that stands for the selected frame's display. */)
5918 (Lisp_Object display)
5920 struct w32_display_info *dpyinfo = check_x_display_info (display);
5921 Lisp_Object result = Qnil;
5923 if (dpyinfo->has_palette)
5924 result = intern ("pseudo-color");
5925 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5926 result = intern ("static-grey");
5927 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5928 result = intern ("static-color");
5929 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5930 result = intern ("true-color");
5932 return result;
5935 DEFUN ("x-display-save-under", Fx_display_save_under,
5936 Sx_display_save_under, 0, 1, 0,
5937 doc: /* Return t if DISPLAY supports the save-under feature.
5938 The optional argument DISPLAY specifies which display to ask about.
5939 DISPLAY should be either a frame or a display name (a string).
5940 If omitted or nil, that stands for the selected frame's display. */)
5941 (Lisp_Object display)
5943 return Qnil;
5946 static BOOL CALLBACK ALIGN_STACK
5947 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5949 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5951 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5953 return TRUE;
5956 static Lisp_Object
5957 w32_display_monitor_attributes_list (void)
5959 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5960 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5961 int i, n_monitors;
5962 HMONITOR *monitors;
5964 if (!(enum_display_monitors_fn && get_monitor_info_fn
5965 && monitor_from_window_fn))
5966 return Qnil;
5968 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5969 (LPARAM) &monitor_list)
5970 || NILP (monitor_list))
5971 return Qnil;
5973 n_monitors = 0;
5974 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5975 n_monitors++;
5977 monitors = xmalloc (n_monitors * sizeof (*monitors));
5978 for (i = 0; i < n_monitors; i++)
5980 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5981 monitor_list = XCDR (monitor_list);
5984 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5985 FOR_EACH_FRAME (rest, frame)
5987 struct frame *f = XFRAME (frame);
5989 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5991 HMONITOR monitor =
5992 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5993 MONITOR_DEFAULT_TO_NEAREST);
5995 for (i = 0; i < n_monitors; i++)
5996 if (monitors[i] == monitor)
5997 break;
5999 if (i < n_monitors)
6000 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
6004 for (i = 0; i < n_monitors; i++)
6006 Lisp_Object geometry, workarea, name, attributes = Qnil;
6007 HDC hdc;
6008 int width_mm, height_mm;
6009 struct MONITOR_INFO_EX mi;
6011 mi.cbSize = sizeof (mi);
6012 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
6013 continue;
6015 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
6016 if (hdc == NULL)
6017 continue;
6018 width_mm = GetDeviceCaps (hdc, HORZSIZE);
6019 height_mm = GetDeviceCaps (hdc, VERTSIZE);
6020 DeleteDC (hdc);
6022 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
6023 attributes);
6025 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
6027 attributes = Fcons (Fcons (Qname, name), attributes);
6029 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6030 attributes);
6032 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
6033 mi.rcWork.right - mi.rcWork.left,
6034 mi.rcWork.bottom - mi.rcWork.top);
6035 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6037 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
6038 mi.rcMonitor.right - mi.rcMonitor.left,
6039 mi.rcMonitor.bottom - mi.rcMonitor.top);
6040 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6042 if (mi.dwFlags & MONITORINFOF_PRIMARY)
6043 primary_monitor_attributes = attributes;
6044 else
6045 attributes_list = Fcons (attributes, attributes_list);
6048 if (!NILP (primary_monitor_attributes))
6049 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
6051 xfree (monitors);
6053 return attributes_list;
6056 static Lisp_Object
6057 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
6059 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
6060 HDC hdc;
6061 double mm_per_pixel;
6062 int pixel_width, pixel_height, width_mm, height_mm;
6063 RECT workarea_rect;
6065 /* Fallback: treat (possibly) multiple physical monitors as if they
6066 formed a single monitor as a whole. This should provide a
6067 consistent result at least on single monitor environments. */
6068 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
6069 attributes);
6071 frames = Qnil;
6072 FOR_EACH_FRAME (rest, frame)
6074 struct frame *f = XFRAME (frame);
6076 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
6077 frames = Fcons (frame, frames);
6079 attributes = Fcons (Fcons (Qframes, frames), attributes);
6081 pixel_width = x_display_pixel_width (dpyinfo);
6082 pixel_height = x_display_pixel_height (dpyinfo);
6084 hdc = GetDC (NULL);
6085 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
6086 / GetDeviceCaps (hdc, HORZRES));
6087 width_mm = pixel_width * mm_per_pixel + 0.5;
6088 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
6089 / GetDeviceCaps (hdc, VERTRES));
6090 height_mm = pixel_height * mm_per_pixel + 0.5;
6091 ReleaseDC (NULL, hdc);
6092 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
6093 attributes);
6095 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
6096 we don't care. */
6097 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
6098 GetSystemMetrics (SM_YVIRTUALSCREEN),
6099 pixel_width, pixel_height);
6100 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
6101 workarea = list4i (workarea_rect.left, workarea_rect.top,
6102 workarea_rect.right - workarea_rect.left,
6103 workarea_rect.bottom - workarea_rect.top);
6104 else
6105 workarea = geometry;
6106 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
6108 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
6110 return list1 (attributes);
6113 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
6114 Sw32_display_monitor_attributes_list,
6115 0, 1, 0,
6116 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
6118 The optional argument DISPLAY specifies which display to ask about.
6119 DISPLAY should be either a frame or a display name (a string).
6120 If omitted or nil, that stands for the selected frame's display.
6122 Internal use only, use `display-monitor-attributes-list' instead. */)
6123 (Lisp_Object display)
6125 struct w32_display_info *dpyinfo = check_x_display_info (display);
6126 Lisp_Object attributes_list;
6128 block_input ();
6129 attributes_list = w32_display_monitor_attributes_list ();
6130 if (NILP (attributes_list))
6131 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
6132 unblock_input ();
6134 return attributes_list;
6137 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
6138 doc: /* Set the sound generated when the bell is rung.
6139 SOUND is `asterisk', `exclamation', `hand', `question', `ok', or `silent'
6140 to use the corresponding system sound for the bell. The `silent' sound
6141 prevents Emacs from making any sound at all.
6142 SOUND is nil to use the normal beep. */)
6143 (Lisp_Object sound)
6145 CHECK_SYMBOL (sound);
6147 if (NILP (sound))
6148 sound_type = 0xFFFFFFFF;
6149 else if (EQ (sound, intern ("asterisk")))
6150 sound_type = MB_ICONASTERISK;
6151 else if (EQ (sound, intern ("exclamation")))
6152 sound_type = MB_ICONEXCLAMATION;
6153 else if (EQ (sound, intern ("hand")))
6154 sound_type = MB_ICONHAND;
6155 else if (EQ (sound, intern ("question")))
6156 sound_type = MB_ICONQUESTION;
6157 else if (EQ (sound, intern ("ok")))
6158 sound_type = MB_OK;
6159 else if (EQ (sound, intern ("silent")))
6160 sound_type = MB_EMACS_SILENT;
6161 else
6162 sound_type = 0xFFFFFFFF;
6164 return sound;
6167 #if 0 /* unused */
6169 x_screen_planes (register struct frame *f)
6171 return FRAME_DISPLAY_INFO (f)->n_planes;
6173 #endif
6175 /* Return the display structure for the display named NAME.
6176 Open a new connection if necessary. */
6178 struct w32_display_info *
6179 x_display_info_for_name (Lisp_Object name)
6181 struct w32_display_info *dpyinfo;
6183 CHECK_STRING (name);
6185 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
6186 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
6187 return dpyinfo;
6189 /* Use this general default value to start with. */
6190 Vx_resource_name = Vinvocation_name;
6192 validate_x_resource_name ();
6194 dpyinfo = w32_term_init (name, NULL, SSDATA (Vx_resource_name));
6196 if (dpyinfo == 0)
6197 error ("Cannot connect to server %s", SDATA (name));
6199 XSETFASTINT (Vwindow_system_version, w32_major_version);
6201 return dpyinfo;
6204 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
6205 1, 3, 0, doc: /* Open a connection to a display server.
6206 DISPLAY is the name of the display to connect to.
6207 Optional second arg XRM-STRING is a string of resources in xrdb format.
6208 If the optional third arg MUST-SUCCEED is non-nil,
6209 terminate Emacs if we can't open the connection.
6210 \(In the Nextstep version, the last two arguments are currently ignored.) */)
6211 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
6213 char *xrm_option;
6214 struct w32_display_info *dpyinfo;
6216 CHECK_STRING (display);
6218 /* Signal an error in order to encourage correct use from callers.
6219 * If we ever support multiple window systems in the same Emacs,
6220 * we'll need callers to be precise about what window system they
6221 * want. */
6223 if (strcmp (SSDATA (display), "w32") != 0)
6224 error ("The name of the display in this Emacs must be \"w32\"");
6226 /* If initialization has already been done, return now to avoid
6227 overwriting critical parts of one_w32_display_info. */
6228 if (window_system_available (NULL))
6229 return Qnil;
6231 if (! NILP (xrm_string))
6232 CHECK_STRING (xrm_string);
6234 /* Allow color mapping to be defined externally; first look in user's
6235 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
6237 Lisp_Object color_file;
6239 color_file = build_string ("~/rgb.txt");
6241 if (NILP (Ffile_readable_p (color_file)))
6242 color_file =
6243 Fexpand_file_name (build_string ("rgb.txt"),
6244 Fsymbol_value (intern ("data-directory")));
6246 Vw32_color_map = Fx_load_color_file (color_file);
6248 if (NILP (Vw32_color_map))
6249 Vw32_color_map = w32_default_color_map ();
6251 /* Merge in system logical colors. */
6252 add_system_logical_colors_to_map (&Vw32_color_map);
6254 if (! NILP (xrm_string))
6255 xrm_option = SSDATA (xrm_string);
6256 else
6257 xrm_option = NULL;
6259 /* Use this general default value to start with. */
6260 /* First remove .exe suffix from invocation-name - it looks ugly. */
6262 char basename[ MAX_PATH ], *str;
6264 lispstpcpy (basename, Vinvocation_name);
6265 str = strrchr (basename, '.');
6266 if (str) *str = 0;
6267 Vinvocation_name = build_string (basename);
6269 Vx_resource_name = Vinvocation_name;
6271 validate_x_resource_name ();
6273 /* This is what opens the connection and sets x_current_display.
6274 This also initializes many symbols, such as those used for input. */
6275 dpyinfo = w32_term_init (display, xrm_option, SSDATA (Vx_resource_name));
6277 if (dpyinfo == 0)
6279 if (!NILP (must_succeed))
6280 fatal ("Cannot connect to server %s.\n",
6281 SDATA (display));
6282 else
6283 error ("Cannot connect to server %s", SDATA (display));
6286 XSETFASTINT (Vwindow_system_version, w32_major_version);
6287 return Qnil;
6290 DEFUN ("x-close-connection", Fx_close_connection,
6291 Sx_close_connection, 1, 1, 0,
6292 doc: /* Close the connection to DISPLAY's server.
6293 For DISPLAY, specify either a frame or a display name (a string).
6294 If DISPLAY is nil, that stands for the selected frame's display. */)
6295 (Lisp_Object display)
6297 struct w32_display_info *dpyinfo = check_x_display_info (display);
6299 if (dpyinfo->reference_count > 0)
6300 error ("Display still has frames on it");
6302 block_input ();
6303 x_destroy_all_bitmaps (dpyinfo);
6305 x_delete_display (dpyinfo);
6306 unblock_input ();
6308 return Qnil;
6311 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
6312 doc: /* Return the list of display names that Emacs has connections to. */)
6313 (void)
6315 Lisp_Object result = Qnil;
6316 struct w32_display_info *wdi;
6318 for (wdi = x_display_list; wdi; wdi = wdi->next)
6319 result = Fcons (XCAR (wdi->name_list_element), result);
6321 return result;
6324 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
6325 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
6326 This function only has an effect on X Windows. With MS Windows, it is
6327 defined but does nothing.
6329 If ON is nil, allow buffering of requests.
6330 Turning on synchronization prohibits the Xlib routines from buffering
6331 requests and seriously degrades performance, but makes debugging much
6332 easier.
6333 The optional second argument TERMINAL specifies which display to act on.
6334 TERMINAL should be a terminal object, a frame or a display name (a string).
6335 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
6336 (Lisp_Object on, Lisp_Object display)
6338 return Qnil;
6343 /***********************************************************************
6344 Window properties
6345 ***********************************************************************/
6347 #if 0 /* TODO : port window properties to W32 */
6349 DEFUN ("x-change-window-property", Fx_change_window_property,
6350 Sx_change_window_property, 2, 6, 0,
6351 doc: /* Change window property PROP to VALUE on the X window of FRAME.
6352 PROP must be a string. VALUE may be a string or a list of conses,
6353 numbers and/or strings. If an element in the list is a string, it is
6354 converted to an atom and the value of the Atom is used. If an element
6355 is a cons, it is converted to a 32 bit number where the car is the 16
6356 top bits and the cdr is the lower 16 bits.
6358 FRAME nil or omitted means use the selected frame.
6359 If TYPE is given and non-nil, it is the name of the type of VALUE.
6360 If TYPE is not given or nil, the type is STRING.
6361 FORMAT gives the size in bits of each element if VALUE is a list.
6362 It must be one of 8, 16 or 32.
6363 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
6364 If OUTER-P is non-nil, the property is changed for the outer X window of
6365 FRAME. Default is to change on the edit X window. */)
6366 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
6367 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
6369 struct frame *f = decode_window_system_frame (frame);
6370 Atom prop_atom;
6372 CHECK_STRING (prop);
6373 CHECK_STRING (value);
6375 block_input ();
6376 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6377 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6378 prop_atom, XA_STRING, 8, PropModeReplace,
6379 SDATA (value), SCHARS (value));
6381 /* Make sure the property is set when we return. */
6382 XFlush (FRAME_W32_DISPLAY (f));
6383 unblock_input ();
6385 return value;
6389 DEFUN ("x-delete-window-property", Fx_delete_window_property,
6390 Sx_delete_window_property, 1, 2, 0,
6391 doc: /* Remove window property PROP from X window of FRAME.
6392 FRAME nil or omitted means use the selected frame. Value is PROP. */)
6393 (Lisp_Object prop, Lisp_Object frame)
6395 struct frame *f = decode_window_system_frame (frame);
6396 Atom prop_atom;
6398 CHECK_STRING (prop);
6399 block_input ();
6400 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6401 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
6403 /* Make sure the property is removed when we return. */
6404 XFlush (FRAME_W32_DISPLAY (f));
6405 unblock_input ();
6407 return prop;
6411 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
6412 1, 6, 0,
6413 doc: /* Value is the value of window property PROP on FRAME.
6414 If FRAME is nil or omitted, use the selected frame.
6416 On X Windows, the following optional arguments are also accepted:
6417 If TYPE is nil or omitted, get the property as a string.
6418 Otherwise TYPE is the name of the atom that denotes the type expected.
6419 If SOURCE is non-nil, get the property on that window instead of from
6420 FRAME. The number 0 denotes the root window.
6421 If DELETE-P is non-nil, delete the property after retrieving it.
6422 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
6424 On MS Windows, this function accepts but ignores those optional arguments.
6426 Value is nil if FRAME hasn't a property with name PROP or if PROP has
6427 no value of TYPE (always string in the MS Windows case). */)
6428 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
6429 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
6431 struct frame *f = decode_window_system_frame (frame);
6432 Atom prop_atom;
6433 int rc;
6434 Lisp_Object prop_value = Qnil;
6435 char *tmp_data = NULL;
6436 Atom actual_type;
6437 int actual_format;
6438 unsigned long actual_size, bytes_remaining;
6440 CHECK_STRING (prop);
6441 block_input ();
6442 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
6443 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6444 prop_atom, 0, 0, False, XA_STRING,
6445 &actual_type, &actual_format, &actual_size,
6446 &bytes_remaining, (unsigned char **) &tmp_data);
6447 if (rc == Success)
6449 int size = bytes_remaining;
6451 XFree (tmp_data);
6452 tmp_data = NULL;
6454 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
6455 prop_atom, 0, bytes_remaining,
6456 False, XA_STRING,
6457 &actual_type, &actual_format,
6458 &actual_size, &bytes_remaining,
6459 (unsigned char **) &tmp_data);
6460 if (rc == Success)
6461 prop_value = make_string (tmp_data, size);
6463 XFree (tmp_data);
6466 unblock_input ();
6468 return prop_value;
6470 return Qnil;
6473 #endif /* TODO */
6475 /***********************************************************************
6476 Tool tips
6477 ***********************************************************************/
6479 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
6480 Lisp_Object, int, int, int *, int *);
6482 /* The frame of a currently visible tooltip. */
6484 Lisp_Object tip_frame;
6486 /* If non-nil, a timer started that hides the last tooltip when it
6487 fires. */
6489 Lisp_Object tip_timer;
6490 Window tip_window;
6492 /* If non-nil, a vector of 3 elements containing the last args
6493 with which x-show-tip was called. See there. */
6495 Lisp_Object last_show_tip_args;
6498 static void
6499 unwind_create_tip_frame (Lisp_Object frame)
6501 Lisp_Object deleted;
6503 deleted = unwind_create_frame (frame);
6504 if (EQ (deleted, Qt))
6506 tip_window = NULL;
6507 tip_frame = Qnil;
6512 /* Create a frame for a tooltip on the display described by DPYINFO.
6513 PARMS is a list of frame parameters. Value is the frame.
6515 Note that functions called here, esp. x_default_parameter can
6516 signal errors, for instance when a specified color name is
6517 undefined. We have to make sure that we're in a consistent state
6518 when this happens. */
6520 static Lisp_Object
6521 x_create_tip_frame (struct w32_display_info *dpyinfo, Lisp_Object parms)
6523 struct frame *f;
6524 Lisp_Object frame;
6525 Lisp_Object name;
6526 int width, height;
6527 ptrdiff_t count = SPECPDL_INDEX ();
6528 struct kboard *kb;
6529 bool face_change_before = face_change;
6530 int x_width = 0, x_height = 0;
6532 /* Use this general default value to start with until we know if
6533 this frame has a specified name. */
6534 Vx_resource_name = Vinvocation_name;
6536 kb = dpyinfo->terminal->kboard;
6538 /* The calls to x_get_arg remove elements from PARMS, so copy it to
6539 avoid destructive changes behind our caller's back. */
6540 parms = Fcopy_alist (parms);
6542 /* Get the name of the frame to use for resource lookup. */
6543 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
6544 if (!STRINGP (name)
6545 && !EQ (name, Qunbound)
6546 && !NILP (name))
6547 error ("Invalid frame name--not a string or nil");
6548 Vx_resource_name = name;
6550 frame = Qnil;
6551 /* Make a frame without minibuffer nor mode-line. */
6552 f = make_frame (false);
6553 f->wants_modeline = false;
6554 XSETFRAME (frame, f);
6556 record_unwind_protect (unwind_create_tip_frame, frame);
6558 /* By setting the output method, we're essentially saying that
6559 the frame is live, as per FRAME_LIVE_P. If we get a signal
6560 from this point on, x_destroy_window might screw up reference
6561 counts etc. */
6562 f->terminal = dpyinfo->terminal;
6563 f->output_method = output_w32;
6564 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
6566 FRAME_FONTSET (f) = -1;
6567 fset_icon_name (f, Qnil);
6569 #ifdef GLYPH_DEBUG
6570 image_cache_refcount =
6571 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
6572 dpyinfo_refcount = dpyinfo->reference_count;
6573 #endif /* GLYPH_DEBUG */
6574 FRAME_KBOARD (f) = kb;
6575 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6576 f->output_data.w32->explicit_parent = false;
6578 /* Set the name; the functions to which we pass f expect the name to
6579 be set. */
6580 if (EQ (name, Qunbound) || NILP (name))
6582 fset_name (f, build_string (dpyinfo->w32_id_name));
6583 f->explicit_name = false;
6585 else
6587 fset_name (f, name);
6588 f->explicit_name = true;
6589 /* Use the frame's title when getting resources for this frame. */
6590 specbind (Qx_resource_name, name);
6593 if (uniscribe_available)
6594 register_font_driver (&uniscribe_font_driver, f);
6595 register_font_driver (&w32font_driver, f);
6597 x_default_parameter (f, parms, Qfont_backend, Qnil,
6598 "fontBackend", "FontBackend", RES_TYPE_STRING);
6600 /* Extract the window parameters from the supplied values
6601 that are needed to determine window geometry. */
6602 x_default_font_parameter (f, parms);
6604 x_default_parameter (f, parms, Qborder_width, make_number (2),
6605 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
6606 /* This defaults to 2 in order to match xterm. We recognize either
6607 internalBorderWidth or internalBorder (which is what xterm calls
6608 it). */
6609 if (NILP (Fassq (Qinternal_border_width, parms)))
6611 Lisp_Object value;
6613 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
6614 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
6615 if (! EQ (value, Qunbound))
6616 parms = Fcons (Fcons (Qinternal_border_width, value),
6617 parms);
6620 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
6621 "internalBorderWidth", "internalBorderWidth",
6622 RES_TYPE_NUMBER);
6623 /* Also do the stuff which must be set before the window exists. */
6624 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
6625 "foreground", "Foreground", RES_TYPE_STRING);
6626 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
6627 "background", "Background", RES_TYPE_STRING);
6628 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
6629 "pointerColor", "Foreground", RES_TYPE_STRING);
6630 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
6631 "cursorColor", "Foreground", RES_TYPE_STRING);
6632 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
6633 "borderColor", "BorderColor", RES_TYPE_STRING);
6635 /* Init faces before x_default_parameter is called for the
6636 scroll-bar-width parameter because otherwise we end up in
6637 init_iterator with a null face cache, which should not happen. */
6638 init_frame_faces (f);
6640 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
6641 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
6643 x_figure_window_size (f, parms, true, &x_width, &x_height);
6645 /* No fringes on tip frame. */
6646 f->fringe_cols = 0;
6647 f->left_fringe_width = 0;
6648 f->right_fringe_width = 0;
6649 /* No dividers on tip frame. */
6650 f->right_divider_width = 0;
6651 f->bottom_divider_width = 0;
6653 block_input ();
6654 my_create_tip_window (f);
6655 unblock_input ();
6657 x_make_gc (f);
6659 x_default_parameter (f, parms, Qauto_raise, Qnil,
6660 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6661 x_default_parameter (f, parms, Qauto_lower, Qnil,
6662 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
6663 x_default_parameter (f, parms, Qcursor_type, Qbox,
6664 "cursorType", "CursorType", RES_TYPE_SYMBOL);
6665 /* Process alpha here (Bug#17344). */
6666 x_default_parameter (f, parms, Qalpha, Qnil,
6667 "alpha", "Alpha", RES_TYPE_NUMBER);
6669 /* Dimensions, especially FRAME_LINES (f), must be done via
6670 change_frame_size. Change will not be effected unless different
6671 from the current FRAME_LINES (f). */
6672 width = FRAME_COLS (f);
6673 height = FRAME_LINES (f);
6674 SET_FRAME_COLS (f, 0);
6675 SET_FRAME_LINES (f, 0);
6676 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
6677 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
6678 /* Add `tooltip' frame parameter's default value. */
6679 if (NILP (Fframe_parameter (frame, Qtooltip)))
6680 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
6682 /* Set up faces after all frame parameters are known. This call
6683 also merges in face attributes specified for new frames.
6685 Frame parameters may be changed if .Xdefaults contains
6686 specifications for the default font. For example, if there is an
6687 `Emacs.default.attributeBackground: pink', the `background-color'
6688 attribute of the frame get's set, which let's the internal border
6689 of the tooltip frame appear in pink. Prevent this. */
6691 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
6692 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
6693 Lisp_Object colors = Qnil;
6695 call2 (Qface_set_after_frame_default, frame, Qnil);
6697 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
6698 colors = Fcons (Fcons (Qbackground_color, bg), colors);
6699 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
6700 colors = Fcons (Fcons (Qforeground_color, fg), colors);
6702 if (!NILP (colors))
6703 Fmodify_frame_parameters (frame, colors);
6706 f->no_split = true;
6708 /* Now that the frame is official, it counts as a reference to
6709 its display. */
6710 FRAME_DISPLAY_INFO (f)->reference_count++;
6711 f->terminal->reference_count++;
6713 /* It is now ok to make the frame official even if we get an error
6714 below. And the frame needs to be on Vframe_list or making it
6715 visible won't work. */
6716 Vframe_list = Fcons (frame, Vframe_list);
6717 f->can_x_set_window_size = true;
6719 /* Setting attributes of faces of the tooltip frame from resources
6720 and similar will set face_change, which leads to the
6721 clearing of all current matrices. Since this isn't necessary
6722 here, avoid it by resetting face_change to the value it
6723 had before we created the tip frame. */
6724 face_change = face_change_before;
6726 /* Discard the unwind_protect. */
6727 return unbind_to (count, frame);
6731 /* Compute where to display tip frame F. PARMS is the list of frame
6732 parameters for F. DX and DY are specified offsets from the current
6733 location of the mouse. WIDTH and HEIGHT are the width and height
6734 of the tooltip. Return coordinates relative to the root window of
6735 the display in *ROOT_X and *ROOT_Y. */
6737 static void
6738 compute_tip_xy (struct frame *f,
6739 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
6740 int width, int height, int *root_x, int *root_y)
6742 Lisp_Object left, top, right, bottom;
6743 int min_x, min_y, max_x, max_y;
6745 /* User-specified position? */
6746 left = Fcdr (Fassq (Qleft, parms));
6747 top = Fcdr (Fassq (Qtop, parms));
6748 right = Fcdr (Fassq (Qright, parms));
6749 bottom = Fcdr (Fassq (Qbottom, parms));
6751 /* Move the tooltip window where the mouse pointer is. Resize and
6752 show it. */
6753 if ((!INTEGERP (left) && !INTEGERP (right))
6754 || (!INTEGERP (top) && !INTEGERP (bottom)))
6756 POINT pt;
6758 /* Default min and max values. */
6759 min_x = 0;
6760 min_y = 0;
6761 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
6762 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
6764 block_input ();
6765 GetCursorPos (&pt);
6766 *root_x = pt.x;
6767 *root_y = pt.y;
6768 unblock_input ();
6770 /* If multiple monitor support is available, constrain the tip onto
6771 the current monitor. This improves the above by allowing negative
6772 co-ordinates if monitor positions are such that they are valid, and
6773 snaps a tooltip onto a single monitor if we are close to the edge
6774 where it would otherwise flow onto the other monitor (or into
6775 nothingness if there is a gap in the overlap). */
6776 if (monitor_from_point_fn && get_monitor_info_fn)
6778 struct MONITOR_INFO info;
6779 HMONITOR monitor
6780 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
6781 info.cbSize = sizeof (info);
6783 if (get_monitor_info_fn (monitor, &info))
6785 min_x = info.rcWork.left;
6786 min_y = info.rcWork.top;
6787 max_x = info.rcWork.right;
6788 max_y = info.rcWork.bottom;
6793 if (INTEGERP (top))
6794 *root_y = XINT (top);
6795 else if (INTEGERP (bottom))
6796 *root_y = XINT (bottom) - height;
6797 else if (*root_y + XINT (dy) <= min_y)
6798 *root_y = min_y; /* Can happen for negative dy */
6799 else if (*root_y + XINT (dy) + height <= max_y)
6800 /* It fits below the pointer */
6801 *root_y += XINT (dy);
6802 else if (height + XINT (dy) + min_y <= *root_y)
6803 /* It fits above the pointer. */
6804 *root_y -= height + XINT (dy);
6805 else
6806 /* Put it on the top. */
6807 *root_y = min_y;
6809 if (INTEGERP (left))
6810 *root_x = XINT (left);
6811 else if (INTEGERP (right))
6812 *root_x = XINT (right) - width;
6813 else if (*root_x + XINT (dx) <= min_x)
6814 *root_x = 0; /* Can happen for negative dx */
6815 else if (*root_x + XINT (dx) + width <= max_x)
6816 /* It fits to the right of the pointer. */
6817 *root_x += XINT (dx);
6818 else if (width + XINT (dx) + min_x <= *root_x)
6819 /* It fits to the left of the pointer. */
6820 *root_x -= width + XINT (dx);
6821 else
6822 /* Put it left justified on the screen -- it ought to fit that way. */
6823 *root_x = min_x;
6826 /* Hide tooltip. Delete its frame if DELETE is true. */
6827 static Lisp_Object
6828 x_hide_tip (bool delete)
6830 if (!NILP (tip_timer))
6832 call1 (Qcancel_timer, tip_timer);
6833 tip_timer = Qnil;
6836 if (NILP (tip_frame)
6837 || (!delete && FRAMEP (tip_frame)
6838 && !FRAME_VISIBLE_P (XFRAME (tip_frame))))
6839 return Qnil;
6840 else
6842 ptrdiff_t count;
6843 Lisp_Object was_open = Qnil;
6845 count = SPECPDL_INDEX ();
6846 specbind (Qinhibit_redisplay, Qt);
6847 specbind (Qinhibit_quit, Qt);
6849 if (FRAMEP (tip_frame))
6851 if (delete)
6853 delete_frame (tip_frame, Qnil);
6854 tip_frame = Qnil;
6856 else
6857 x_make_frame_invisible (XFRAME (tip_frame));
6859 was_open = Qt;
6861 else
6862 tip_frame = Qnil;
6864 return unbind_to (count, was_open);
6869 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
6870 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
6871 A tooltip window is a small window displaying a string.
6873 This is an internal function; Lisp code should call `tooltip-show'.
6875 FRAME nil or omitted means use the selected frame.
6877 PARMS is an optional list of frame parameters which can be
6878 used to change the tooltip's appearance.
6880 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6881 means use the default timeout of 5 seconds.
6883 If the list of frame parameters PARMS contains a `left' parameter,
6884 display the tooltip at that x-position. If the list of frame parameters
6885 PARMS contains no `left' but a `right' parameter, display the tooltip
6886 right-adjusted at that x-position. Otherwise display it at the
6887 x-position of the mouse, with offset DX added (default is 5 if DX isn't
6888 specified).
6890 Likewise for the y-position: If a `top' frame parameter is specified, it
6891 determines the position of the upper edge of the tooltip window. If a
6892 `bottom' parameter but no `top' frame parameter is specified, it
6893 determines the position of the lower edge of the tooltip window.
6894 Otherwise display the tooltip window at the y-position of the mouse,
6895 with offset DY added (default is -10).
6897 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6898 Text larger than the specified size is clipped. */)
6899 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6901 struct frame *tip_f;
6902 struct window *w;
6903 int root_x, root_y;
6904 struct buffer *old_buffer;
6905 struct text_pos pos;
6906 int width, height;
6907 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6908 ptrdiff_t count = SPECPDL_INDEX ();
6909 ptrdiff_t count_1;
6910 Lisp_Object window, size;
6911 AUTO_STRING (tip, " *tip*");
6913 specbind (Qinhibit_redisplay, Qt);
6915 CHECK_STRING (string);
6916 decode_window_system_frame (frame);
6917 if (NILP (timeout))
6918 timeout = make_number (5);
6919 else
6920 CHECK_NATNUM (timeout);
6922 if (NILP (dx))
6923 dx = make_number (5);
6924 else
6925 CHECK_NUMBER (dx);
6927 if (NILP (dy))
6928 dy = make_number (-10);
6929 else
6930 CHECK_NUMBER (dy);
6932 if (NILP (last_show_tip_args))
6933 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6935 if (FRAMEP (tip_frame) && FRAME_LIVE_P (XFRAME (tip_frame)))
6937 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6938 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6939 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6941 if (FRAME_VISIBLE_P (XFRAME (tip_frame))
6942 && EQ (frame, last_frame)
6943 && !NILP (Fequal_including_properties (last_string, string))
6944 && !NILP (Fequal (last_parms, parms)))
6946 /* Only DX and DY have changed. */
6947 tip_f = XFRAME (tip_frame);
6948 if (!NILP (tip_timer))
6950 Lisp_Object timer = tip_timer;
6952 tip_timer = Qnil;
6953 call1 (Qcancel_timer, timer);
6956 block_input ();
6957 compute_tip_xy (tip_f, parms, dx, dy, FRAME_PIXEL_WIDTH (tip_f),
6958 FRAME_PIXEL_HEIGHT (tip_f), &root_x, &root_y);
6960 /* Put tooltip in topmost group and in position. */
6961 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
6962 root_x, root_y, 0, 0,
6963 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6965 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6966 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
6967 0, 0, 0, 0,
6968 SWP_NOMOVE | SWP_NOSIZE
6969 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6971 /* Let redisplay know that we have made the frame visible already. */
6972 SET_FRAME_VISIBLE (tip_f, 1);
6973 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
6974 unblock_input ();
6976 goto start_timer;
6978 else if (tooltip_reuse_hidden_frame && EQ (frame, last_frame))
6980 bool delete = false;
6981 Lisp_Object tail, elt, parm, last;
6983 /* Check if every parameter in PARMS has the same value in
6984 last_parms. This may destruct last_parms which, however,
6985 will be recreated below. */
6986 for (tail = parms; CONSP (tail); tail = XCDR (tail))
6988 elt = XCAR (tail);
6989 parm = Fcar (elt);
6990 /* The left, top, right and bottom parameters are handled
6991 by compute_tip_xy so they can be ignored here. */
6992 if (!EQ (parm, Qleft) && !EQ (parm, Qtop)
6993 && !EQ (parm, Qright) && !EQ (parm, Qbottom))
6995 last = Fassq (parm, last_parms);
6996 if (NILP (Fequal (Fcdr (elt), Fcdr (last))))
6998 /* We lost, delete the old tooltip. */
6999 delete = true;
7000 break;
7002 else
7003 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7005 else
7006 last_parms = call2 (Qassq_delete_all, parm, last_parms);
7009 /* Now check if there's a parameter left in last_parms with a
7010 non-nil value. */
7011 for (tail = last_parms; CONSP (tail); tail = XCDR (tail))
7013 elt = XCAR (tail);
7014 parm = Fcar (elt);
7015 if (!EQ (parm, Qleft) && !EQ (parm, Qtop) && !EQ (parm, Qright)
7016 && !EQ (parm, Qbottom) && !NILP (Fcdr (elt)))
7018 /* We lost, delete the old tooltip. */
7019 delete = true;
7020 break;
7024 x_hide_tip (delete);
7026 else
7027 x_hide_tip (true);
7029 else
7030 x_hide_tip (true);
7032 ASET (last_show_tip_args, 0, string);
7033 ASET (last_show_tip_args, 1, frame);
7034 ASET (last_show_tip_args, 2, parms);
7036 /* Block input until the tip has been fully drawn, to avoid crashes
7037 when drawing tips in menus. */
7038 block_input ();
7040 if (!FRAMEP (tip_frame) || !FRAME_LIVE_P (XFRAME (tip_frame)))
7042 /* Add default values to frame parameters. */
7043 if (NILP (Fassq (Qname, parms)))
7044 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
7045 if (NILP (Fassq (Qinternal_border_width, parms)))
7046 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
7047 if (NILP (Fassq (Qborder_width, parms)))
7048 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
7049 if (NILP (Fassq (Qborder_color, parms)))
7050 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
7051 if (NILP (Fassq (Qbackground_color, parms)))
7052 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
7053 parms);
7055 /* Create a frame for the tooltip, and record it in the global
7056 variable tip_frame. */
7057 struct frame *f; /* The value is unused. */
7058 if (NILP (tip_frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms)))
7060 /* Creating the tip frame failed. */
7061 unblock_input ();
7062 return unbind_to (count, Qnil);
7066 tip_f = XFRAME (tip_frame);
7067 window = FRAME_ROOT_WINDOW (tip_f);
7068 set_window_buffer (window, Fget_buffer_create (tip), false, false);
7069 w = XWINDOW (window);
7070 w->pseudo_window_p = true;
7072 /* Set up the frame's root window. Note: The following code does not
7073 try to size the window or its frame correctly. Its only purpose is
7074 to make the subsequent text size calculations work. The right
7075 sizes should get installed when the toolkit gets back to us. */
7076 w->left_col = 0;
7077 w->top_line = 0;
7078 w->pixel_left = 0;
7079 w->pixel_top = 0;
7081 if (CONSP (Vx_max_tooltip_size)
7082 && RANGED_INTEGERP (1, XCAR (Vx_max_tooltip_size), INT_MAX)
7083 && RANGED_INTEGERP (1, XCDR (Vx_max_tooltip_size), INT_MAX))
7085 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
7086 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
7088 else
7090 w->total_cols = 80;
7091 w->total_lines = 40;
7094 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (tip_f);
7095 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (tip_f);
7096 FRAME_TOTAL_COLS (tip_f) = WINDOW_TOTAL_COLS (w);
7097 adjust_frame_glyphs (tip_f);
7099 /* Insert STRING into the root window's buffer and fit the frame to
7100 the buffer. */
7101 count_1 = SPECPDL_INDEX ();
7102 old_buffer = current_buffer;
7103 set_buffer_internal_1 (XBUFFER (w->contents));
7104 bset_truncate_lines (current_buffer, Qnil);
7105 specbind (Qinhibit_read_only, Qt);
7106 specbind (Qinhibit_modification_hooks, Qt);
7107 specbind (Qinhibit_point_motion_hooks, Qt);
7108 Ferase_buffer ();
7109 Finsert (1, &string);
7110 clear_glyph_matrix (w->desired_matrix);
7111 clear_glyph_matrix (w->current_matrix);
7112 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
7113 try_window (window, pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
7114 /* Calculate size of tooltip window. */
7115 size = Fwindow_text_pixel_size (window, Qnil, Qnil, Qnil,
7116 make_number (w->pixel_height), Qnil);
7117 /* Add the frame's internal border to calculated size. */
7118 width = XINT (Fcar (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7119 height = XINT (Fcdr (size)) + 2 * FRAME_INTERNAL_BORDER_WIDTH (tip_f);
7120 /* Calculate position of tooltip frame. */
7121 compute_tip_xy (tip_f, parms, dx, dy, width, height, &root_x, &root_y);
7123 /* Show tooltip frame. */
7125 RECT rect;
7126 int pad = (NUMBERP (Vw32_tooltip_extra_pixels)
7127 ? max (0, XINT (Vw32_tooltip_extra_pixels))
7128 : FRAME_COLUMN_WIDTH (tip_f));
7130 rect.left = rect.top = 0;
7131 rect.right = width;
7132 rect.bottom = height;
7133 AdjustWindowRect (&rect, tip_f->output_data.w32->dwStyle,
7134 FRAME_EXTERNAL_MENU_BAR (tip_f));
7136 /* Position and size tooltip and put it in the topmost group. */
7137 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOPMOST,
7138 root_x, root_y,
7139 rect.right - rect.left + pad,
7140 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7142 /* Ensure tooltip is on top of other topmost windows (eg menus). */
7143 SetWindowPos (FRAME_W32_WINDOW (tip_f), HWND_TOP,
7144 0, 0, 0, 0,
7145 SWP_NOMOVE | SWP_NOSIZE
7146 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
7148 /* Let redisplay know that we have made the frame visible already. */
7149 SET_FRAME_VISIBLE (tip_f, 1);
7151 ShowWindow (FRAME_W32_WINDOW (tip_f), SW_SHOWNOACTIVATE);
7154 w->must_be_updated_p = true;
7155 update_single_window (w);
7156 set_buffer_internal_1 (old_buffer);
7157 unbind_to (count_1, Qnil);
7158 unblock_input ();
7159 windows_or_buffers_changed = old_windows_or_buffers_changed;
7161 start_timer:
7162 /* Let the tip disappear after timeout seconds. */
7163 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
7164 intern ("x-hide-tip"));
7166 return unbind_to (count, Qnil);
7170 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
7171 doc: /* Hide the current tooltip window, if there is any.
7172 Value is t if tooltip was open, nil otherwise. */)
7173 (void)
7175 return x_hide_tip (!tooltip_reuse_hidden_frame);
7178 /***********************************************************************
7179 File selection dialog
7180 ***********************************************************************/
7182 #define FILE_NAME_TEXT_FIELD edt1
7183 #define FILE_NAME_COMBO_BOX cmb13
7184 #define FILE_NAME_LIST lst1
7186 /* Callback for altering the behavior of the Open File dialog.
7187 Makes the Filename text field contain "Current Directory" and be
7188 read-only when "Directories" is selected in the filter. This
7189 allows us to work around the fact that the standard Open File
7190 dialog does not support directories. */
7191 static UINT_PTR CALLBACK
7192 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
7194 if (msg == WM_NOTIFY)
7196 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
7197 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
7198 int dropdown_changed;
7199 int dir_index;
7200 #ifdef NTGUI_UNICODE
7201 const int use_unicode = 1;
7202 #else /* !NTGUI_UNICODE */
7203 int use_unicode = w32_unicode_filenames;
7204 #endif /* NTGUI_UNICODE */
7206 /* Detect when the Filter dropdown is changed. */
7207 if (use_unicode)
7208 dropdown_changed =
7209 notify_w->hdr.code == CDN_TYPECHANGE
7210 || notify_w->hdr.code == CDN_INITDONE;
7211 else
7212 dropdown_changed =
7213 notify_a->hdr.code == CDN_TYPECHANGE
7214 || notify_a->hdr.code == CDN_INITDONE;
7215 if (dropdown_changed)
7217 HWND dialog = GetParent (hwnd);
7218 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
7219 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
7220 int hdr_code;
7222 /* At least on Windows 7, the above attempt to get the window handle
7223 to the File Name Text Field fails. The following code does the
7224 job though. Note that this code is based on my examination of the
7225 window hierarchy using Microsoft Spy++. bk */
7226 if (edit_control == NULL)
7228 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
7229 if (tmp)
7231 tmp = GetWindow (tmp, GW_CHILD);
7232 if (tmp)
7233 edit_control = GetWindow (tmp, GW_CHILD);
7237 /* Directories is in index 2. */
7238 if (use_unicode)
7240 dir_index = notify_w->lpOFN->nFilterIndex;
7241 hdr_code = notify_w->hdr.code;
7243 else
7245 dir_index = notify_a->lpOFN->nFilterIndex;
7246 hdr_code = notify_a->hdr.code;
7248 if (dir_index == 2)
7250 if (use_unicode)
7251 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7252 (LPARAM)L"Current Directory");
7253 else
7254 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
7255 (LPARAM)"Current Directory");
7256 EnableWindow (edit_control, FALSE);
7257 /* Note that at least on Windows 7, the above call to EnableWindow
7258 disables the window that would ordinarily have focus. If we
7259 do not set focus to some other window here, focus will land in
7260 no man's land and the user will be unable to tab through the
7261 dialog box (pressing tab will only result in a beep).
7262 Avoid that problem by setting focus to the list here. */
7263 if (hdr_code == CDN_INITDONE)
7264 SetFocus (list);
7266 else
7268 /* Don't override default filename on init done. */
7269 if (hdr_code == CDN_TYPECHANGE)
7271 if (use_unicode)
7272 SendMessageW (dialog, CDM_SETCONTROLTEXT,
7273 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
7274 else
7275 SendMessageA (dialog, CDM_SETCONTROLTEXT,
7276 FILE_NAME_TEXT_FIELD, (LPARAM)"");
7278 EnableWindow (edit_control, TRUE);
7282 return 0;
7285 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
7286 doc: /* Read file name, prompting with PROMPT in directory DIR.
7287 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
7288 selection box, if specified. If MUSTMATCH is non-nil, the returned file
7289 or directory must exist.
7291 This function is only defined on NS, MS Windows, and X Windows with the
7292 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
7293 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
7294 On Windows 7 and later, the file selection dialog "remembers" the last
7295 directory where the user selected a file, and will open that directory
7296 instead of DIR on subsequent invocations of this function with the same
7297 value of DIR as in previous invocations; this is standard Windows behavior. */)
7298 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
7300 /* Filter index: 1: All Files, 2: Directories only */
7301 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
7302 #ifndef NTGUI_UNICODE
7303 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
7304 #endif
7306 Lisp_Object filename = default_filename;
7307 struct frame *f = SELECTED_FRAME ();
7308 BOOL file_opened = FALSE;
7309 Lisp_Object orig_dir = dir;
7310 Lisp_Object orig_prompt = prompt;
7312 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
7313 compatibility) we end up with the old file dialogs. Define a big
7314 enough struct for the new dialog to trick GetOpenFileName into
7315 giving us the new dialogs on newer versions of Windows. */
7316 struct {
7317 OPENFILENAMEW details;
7318 #if _WIN32_WINNT < 0x500 /* < win2k */
7319 PVOID pvReserved;
7320 DWORD dwReserved;
7321 DWORD FlagsEx;
7322 #endif /* < win2k */
7323 } new_file_details_w;
7325 #ifdef NTGUI_UNICODE
7326 wchar_t filename_buf_w[32*1024 + 1]; /* NT kernel maximum */
7327 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7328 const int use_unicode = 1;
7329 #else /* not NTGUI_UNICODE */
7330 struct {
7331 OPENFILENAMEA details;
7332 #if _WIN32_WINNT < 0x500 /* < win2k */
7333 PVOID pvReserved;
7334 DWORD dwReserved;
7335 DWORD FlagsEx;
7336 #endif /* < win2k */
7337 } new_file_details_a;
7338 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
7339 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
7340 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
7341 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
7342 int use_unicode = w32_unicode_filenames;
7343 wchar_t *prompt_w;
7344 char *prompt_a;
7345 int len;
7346 char fname_ret[MAX_UTF8_PATH];
7347 #endif /* NTGUI_UNICODE */
7350 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
7351 system file encoding expected by the platform APIs (e.g. Cygwin's
7352 POSIX implementation) may not be the same as the encoding expected
7353 by the Windows "ANSI" APIs! */
7355 CHECK_STRING (prompt);
7356 CHECK_STRING (dir);
7358 dir = Fexpand_file_name (dir, Qnil);
7360 if (STRINGP (filename))
7361 filename = Ffile_name_nondirectory (filename);
7362 else
7363 filename = empty_unibyte_string;
7365 #ifdef CYGWIN
7366 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
7367 if (SCHARS (filename) > 0)
7368 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
7369 #endif
7371 CHECK_STRING (dir);
7372 CHECK_STRING (filename);
7374 /* The code in file_dialog_callback that attempts to set the text
7375 of the file name edit window when handling the CDN_INITDONE
7376 WM_NOTIFY message does not work. Setting filename to "Current
7377 Directory" in the only_dir_p case here does work however. */
7378 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
7379 filename = build_string ("Current Directory");
7381 /* Convert the values we've computed so far to system form. */
7382 #ifdef NTGUI_UNICODE
7383 to_unicode (prompt, &prompt);
7384 to_unicode (dir, &dir);
7385 to_unicode (filename, &filename);
7386 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
7387 report_file_error ("filename too long", default_filename);
7389 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
7390 #else /* !NTGUI_UNICODE */
7391 prompt = ENCODE_FILE (prompt);
7392 dir = ENCODE_FILE (dir);
7393 filename = ENCODE_FILE (filename);
7395 /* We modify these in-place, so make copies for safety. */
7396 dir = Fcopy_sequence (dir);
7397 unixtodos_filename (SSDATA (dir));
7398 filename = Fcopy_sequence (filename);
7399 unixtodos_filename (SSDATA (filename));
7400 if (SBYTES (filename) >= MAX_UTF8_PATH)
7401 report_file_error ("filename too long", default_filename);
7402 if (w32_unicode_filenames)
7404 filename_to_utf16 (SSDATA (dir), dir_w);
7405 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
7407 /* filename_to_utf16 sets errno to ENOENT when the file
7408 name is too long or cannot be converted to UTF-16. */
7409 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
7410 report_file_error ("filename too long", default_filename);
7412 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7413 SSDATA (prompt), -1, NULL, 0);
7414 if (len > 32768)
7415 len = 32768;
7416 prompt_w = alloca (len * sizeof (wchar_t));
7417 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7418 SSDATA (prompt), -1, prompt_w, len);
7420 else
7422 filename_to_ansi (SSDATA (dir), dir_a);
7423 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
7425 /* filename_to_ansi sets errno to ENOENT when the file
7426 name is too long or cannot be converted to UTF-16. */
7427 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
7428 report_file_error ("filename too long", default_filename);
7430 len = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7431 SSDATA (prompt), -1, NULL, 0);
7432 if (len > 32768)
7433 len = 32768;
7434 prompt_w = alloca (len * sizeof (wchar_t));
7435 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7436 SSDATA (prompt), -1, prompt_w, len);
7437 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
7438 if (len > 32768)
7439 len = 32768;
7440 prompt_a = alloca (len);
7441 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
7443 #endif /* NTGUI_UNICODE */
7445 /* Fill in the structure for the call to GetOpenFileName below.
7446 For NTGUI_UNICODE builds (which run only on NT), we just use
7447 the actual size of the structure. For non-NTGUI_UNICODE
7448 builds, we tell the OS we're using an old version of the
7449 structure if the OS isn't new enough to support the newer
7450 version. */
7451 if (use_unicode)
7453 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
7454 if (w32_major_version > 4 && w32_major_version < 95)
7455 file_details_w->lStructSize = sizeof (new_file_details_w);
7456 else
7457 file_details_w->lStructSize = sizeof (*file_details_w);
7458 /* Set up the inout parameter for the selected file name. */
7459 file_details_w->lpstrFile = filename_buf_w;
7460 file_details_w->nMaxFile =
7461 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
7462 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
7463 /* Undocumented Bug in Common File Dialog:
7464 If a filter is not specified, shell links are not resolved. */
7465 file_details_w->lpstrFilter = filter_w;
7466 #ifdef NTGUI_UNICODE
7467 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
7468 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
7469 #else
7470 file_details_w->lpstrInitialDir = dir_w;
7471 file_details_w->lpstrTitle = prompt_w;
7472 #endif
7473 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7474 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7475 | OFN_EXPLORER | OFN_ENABLEHOOK);
7476 if (!NILP (mustmatch))
7478 /* Require that the path to the parent directory exists. */
7479 file_details_w->Flags |= OFN_PATHMUSTEXIST;
7480 /* If we are looking for a file, require that it exists. */
7481 if (NILP (only_dir_p))
7482 file_details_w->Flags |= OFN_FILEMUSTEXIST;
7485 #ifndef NTGUI_UNICODE
7486 else
7488 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
7489 if (w32_major_version > 4 && w32_major_version < 95)
7490 file_details_a->lStructSize = sizeof (new_file_details_a);
7491 else
7492 file_details_a->lStructSize = sizeof (*file_details_a);
7493 file_details_a->lpstrFile = filename_buf_a;
7494 file_details_a->nMaxFile =
7495 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
7496 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
7497 file_details_a->lpstrFilter = filter_a;
7498 file_details_a->lpstrInitialDir = dir_a;
7499 file_details_a->lpstrTitle = prompt_a;
7500 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
7501 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
7502 | OFN_EXPLORER | OFN_ENABLEHOOK);
7503 if (!NILP (mustmatch))
7505 /* Require that the path to the parent directory exists. */
7506 file_details_a->Flags |= OFN_PATHMUSTEXIST;
7507 /* If we are looking for a file, require that it exists. */
7508 if (NILP (only_dir_p))
7509 file_details_a->Flags |= OFN_FILEMUSTEXIST;
7512 #endif /* !NTGUI_UNICODE */
7515 int count = SPECPDL_INDEX ();
7516 /* Prevent redisplay. */
7517 specbind (Qinhibit_redisplay, Qt);
7518 block_input ();
7519 if (use_unicode)
7521 file_details_w->lpfnHook = file_dialog_callback;
7523 file_opened = GetOpenFileNameW (file_details_w);
7525 #ifndef NTGUI_UNICODE
7526 else
7528 file_details_a->lpfnHook = file_dialog_callback;
7530 file_opened = GetOpenFileNameA (file_details_a);
7532 #endif /* !NTGUI_UNICODE */
7533 unblock_input ();
7534 unbind_to (count, Qnil);
7537 if (file_opened)
7539 /* Get an Emacs string from the value Windows gave us. */
7540 #ifdef NTGUI_UNICODE
7541 filename = from_unicode_buffer (filename_buf_w);
7542 #else /* !NTGUI_UNICODE */
7543 if (use_unicode)
7544 filename_from_utf16 (filename_buf_w, fname_ret);
7545 else
7546 filename_from_ansi (filename_buf_a, fname_ret);
7547 dostounix_filename (fname_ret);
7548 filename = DECODE_FILE (build_unibyte_string (fname_ret));
7549 #endif /* NTGUI_UNICODE */
7551 #ifdef CYGWIN
7552 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
7553 #endif /* CYGWIN */
7555 /* Strip the dummy filename off the end of the string if we
7556 added it to select a directory. */
7557 if ((use_unicode && file_details_w->nFilterIndex == 2)
7558 #ifndef NTGUI_UNICODE
7559 || (!use_unicode && file_details_a->nFilterIndex == 2)
7560 #endif
7562 filename = Ffile_name_directory (filename);
7564 /* User canceled the dialog without making a selection. */
7565 else if (!CommDlgExtendedError ())
7566 filename = Qnil;
7567 /* An error occurred, fallback on reading from the mini-buffer. */
7568 else
7569 filename = Fcompleting_read (
7570 orig_prompt,
7571 intern ("read-file-name-internal"),
7572 orig_dir,
7573 mustmatch,
7574 orig_dir,
7575 Qfile_name_history,
7576 default_filename,
7577 Qnil);
7580 /* Make "Cancel" equivalent to C-g. */
7581 if (NILP (filename))
7582 quit ();
7584 return filename;
7588 #ifdef WINDOWSNT
7589 /* Moving files to the system recycle bin.
7590 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
7591 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
7592 Ssystem_move_file_to_trash, 1, 1, 0,
7593 doc: /* Move file or directory named FILENAME to the recycle bin. */)
7594 (Lisp_Object filename)
7596 Lisp_Object handler;
7597 Lisp_Object encoded_file;
7598 Lisp_Object operation;
7600 operation = Qdelete_file;
7601 if (!NILP (Ffile_directory_p (filename))
7602 && NILP (Ffile_symlink_p (filename)))
7604 operation = intern ("delete-directory");
7605 filename = Fdirectory_file_name (filename);
7608 /* Must have fully qualified file names for moving files to Recycle
7609 Bin. */
7610 filename = Fexpand_file_name (filename, Qnil);
7612 handler = Ffind_file_name_handler (filename, operation);
7613 if (!NILP (handler))
7614 return call2 (handler, operation, filename);
7615 else
7617 const char * path;
7618 int result;
7620 encoded_file = ENCODE_FILE (filename);
7622 path = map_w32_filename (SSDATA (encoded_file), NULL);
7624 /* The Unicode version of SHFileOperation is not supported on
7625 Windows 9X. */
7626 if (w32_unicode_filenames && os_subtype != OS_9X)
7628 SHFILEOPSTRUCTW file_op_w;
7629 /* We need one more element beyond MAX_PATH because this is
7630 a list of file names, with the last element double-null
7631 terminated. */
7632 wchar_t tmp_path_w[MAX_PATH + 1];
7634 memset (tmp_path_w, 0, sizeof (tmp_path_w));
7635 filename_to_utf16 (path, tmp_path_w);
7637 /* On Windows, write permission is required to delete/move files. */
7638 _wchmod (tmp_path_w, 0666);
7640 memset (&file_op_w, 0, sizeof (file_op_w));
7641 file_op_w.hwnd = HWND_DESKTOP;
7642 file_op_w.wFunc = FO_DELETE;
7643 file_op_w.pFrom = tmp_path_w;
7644 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7645 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7646 file_op_w.fAnyOperationsAborted = FALSE;
7648 result = SHFileOperationW (&file_op_w);
7650 else
7652 SHFILEOPSTRUCTA file_op_a;
7653 char tmp_path_a[MAX_PATH + 1];
7655 memset (tmp_path_a, 0, sizeof (tmp_path_a));
7656 filename_to_ansi (path, tmp_path_a);
7658 /* If a file cannot be represented in ANSI codepage, don't
7659 let them inadvertently delete other files because some
7660 characters are interpreted as a wildcards. */
7661 if (_mbspbrk ((unsigned char *)tmp_path_a,
7662 (const unsigned char *)"?*"))
7663 result = ERROR_FILE_NOT_FOUND;
7664 else
7666 _chmod (tmp_path_a, 0666);
7668 memset (&file_op_a, 0, sizeof (file_op_a));
7669 file_op_a.hwnd = HWND_DESKTOP;
7670 file_op_a.wFunc = FO_DELETE;
7671 file_op_a.pFrom = tmp_path_a;
7672 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
7673 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
7674 file_op_a.fAnyOperationsAborted = FALSE;
7676 result = SHFileOperationA (&file_op_a);
7679 if (result != 0)
7680 report_file_error ("Removing old name", list1 (filename));
7682 return Qnil;
7685 #endif /* WINDOWSNT */
7688 /***********************************************************************
7689 w32 specialized functions
7690 ***********************************************************************/
7692 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
7693 Sw32_send_sys_command, 1, 2, 0,
7694 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
7695 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
7696 to minimize), #xf120 to restore frame to original size, and #xf100
7697 to activate the menubar for keyboard access. #xf140 activates the
7698 screen saver if defined.
7700 If optional parameter FRAME is not specified, use selected frame. */)
7701 (Lisp_Object command, Lisp_Object frame)
7703 struct frame *f = decode_window_system_frame (frame);
7705 CHECK_NUMBER (command);
7707 if (FRAME_W32_P (f))
7708 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
7710 return Qnil;
7713 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
7714 doc: /* Get Windows to perform OPERATION on DOCUMENT.
7715 This is a wrapper around the ShellExecute system function, which
7716 invokes the application registered to handle OPERATION for DOCUMENT.
7718 OPERATION is either nil or a string that names a supported operation.
7719 What operations can be used depends on the particular DOCUMENT and its
7720 handler application, but typically it is one of the following common
7721 operations:
7723 \"open\" - open DOCUMENT, which could be a file, a directory, or an
7724 executable program (application). If it is an application,
7725 that application is launched in the current buffer's default
7726 directory. Otherwise, the application associated with
7727 DOCUMENT is launched in the buffer's default directory.
7728 \"opennew\" - like \"open\", but instruct the application to open
7729 DOCUMENT in a new window.
7730 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
7731 \"print\" - print DOCUMENT, which must be a file.
7732 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
7733 The printer should be provided in PARAMETERS, see below.
7734 \"explore\" - start the Windows Explorer on DOCUMENT.
7735 \"edit\" - launch an editor and open DOCUMENT for editing; which
7736 editor is launched depends on the association for the
7737 specified DOCUMENT.
7738 \"find\" - initiate search starting from DOCUMENT, which must specify
7739 a directory.
7740 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
7741 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
7742 the clipboard.
7743 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
7744 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
7745 which must be a directory.
7746 \"pastelink\"
7747 - create a shortcut in DOCUMENT (which must be a directory)
7748 the file or directory whose name is in the clipboard.
7749 \"runas\" - run DOCUMENT, which must be an excutable file, with
7750 elevated privileges (a.k.a. \"as Administrator\").
7751 \"properties\"
7752 - open the property sheet dialog for DOCUMENT.
7753 nil - invoke the default OPERATION, or \"open\" if default is
7754 not defined or unavailable.
7756 DOCUMENT is typically the name of a document file or a URL, but can
7757 also be an executable program to run, or a directory to open in the
7758 Windows Explorer. If it is a file or a directory, it must be a local
7759 one; this function does not support remote file names.
7761 If DOCUMENT is an executable program, the optional third arg PARAMETERS
7762 can be a string containing command line parameters, separated by blanks,
7763 that will be passed to the program. Some values of OPERATION also require
7764 parameters (e.g., \"printto\" requires the printer address). Otherwise,
7765 PARAMETERS should be nil or unspecified. Note that double quote characters
7766 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
7768 Optional fourth argument SHOW-FLAG can be used to control how the
7769 application will be displayed when it is invoked. If SHOW-FLAG is nil
7770 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
7771 specified, otherwise it is an integer between 0 and 11 representing
7772 a ShowWindow flag:
7774 0 - start hidden
7775 1 - start as normal-size window
7776 3 - start in a maximized window
7777 6 - start in a minimized window
7778 10 - start as the application itself specifies; this is the default. */)
7779 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
7781 char *errstr;
7782 Lisp_Object current_dir = BVAR (current_buffer, directory);;
7783 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
7784 #ifdef CYGWIN
7785 intptr_t result;
7786 #else
7787 int use_unicode = w32_unicode_filenames;
7788 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
7789 Lisp_Object absdoc, handler;
7790 BOOL success;
7791 #endif
7793 CHECK_STRING (document);
7795 #ifdef CYGWIN
7796 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
7797 document = Fcygwin_convert_file_name_to_windows (document, Qt);
7799 /* Encode filename, current directory and parameters. */
7800 current_dir = GUI_ENCODE_FILE (current_dir);
7801 document = GUI_ENCODE_FILE (document);
7802 doc_w = GUI_SDATA (document);
7803 if (STRINGP (parameters))
7805 parameters = GUI_ENCODE_SYSTEM (parameters);
7806 params_w = GUI_SDATA (parameters);
7808 if (STRINGP (operation))
7810 operation = GUI_ENCODE_SYSTEM (operation);
7811 ops_w = GUI_SDATA (operation);
7813 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7814 GUI_SDATA (current_dir),
7815 (INTEGERP (show_flag)
7816 ? XINT (show_flag) : SW_SHOWDEFAULT));
7818 if (result > 32)
7819 return Qt;
7821 switch (result)
7823 case SE_ERR_ACCESSDENIED:
7824 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7825 break;
7826 case SE_ERR_ASSOCINCOMPLETE:
7827 case SE_ERR_NOASSOC:
7828 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7829 break;
7830 case SE_ERR_DDEBUSY:
7831 case SE_ERR_DDEFAIL:
7832 errstr = w32_strerror (ERROR_DDE_FAIL);
7833 break;
7834 case SE_ERR_DDETIMEOUT:
7835 errstr = w32_strerror (ERROR_TIMEOUT);
7836 break;
7837 case SE_ERR_DLLNOTFOUND:
7838 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7839 break;
7840 case SE_ERR_FNF:
7841 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7842 break;
7843 case SE_ERR_OOM:
7844 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7845 break;
7846 case SE_ERR_PNF:
7847 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7848 break;
7849 case SE_ERR_SHARE:
7850 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7851 break;
7852 default:
7853 errstr = w32_strerror (0);
7854 break;
7857 #else /* !CYGWIN */
7859 const char file_url_str[] = "file:///";
7860 const int file_url_len = sizeof (file_url_str) - 1;
7861 int doclen;
7863 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
7865 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
7866 start a thread in some rare system configurations, for
7867 unknown reasons. That thread is started in the context of
7868 the Emacs process, but out of control of our code, and seems
7869 to never exit afterwards. Each such thread reserves 8MB of
7870 stack space (because that's the value recorded in the Emacs
7871 executable at link time: Emacs needs a large stack). So a
7872 large enough number of invocations of w32-shell-execute can
7873 potentially cause the Emacs process to run out of available
7874 address space, which is nasty. To work around this, we
7875 convert such URLs to local file names, which seems to prevent
7876 those threads from starting. See bug #20220. */
7877 char *p = SSDATA (document) + file_url_len;
7879 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
7880 document = Fsubstring_no_properties (document,
7881 make_number (file_url_len), Qnil);
7883 /* We have a situation here. If DOCUMENT is a relative file name,
7884 but its name includes leading directories, i.e. it lives not in
7885 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7886 will fail to find it. So we need to make the file name is
7887 absolute. But DOCUMENT does not have to be a file, it can be a
7888 URL, for example. So we make it absolute only if it is an
7889 existing file; if it is a file that does not exist, tough. */
7890 absdoc = Fexpand_file_name (document, Qnil);
7891 /* Don't call file handlers for file-exists-p, since they might
7892 attempt to access the file, which could fail or produce undesired
7893 consequences, see bug#16558 for an example. */
7894 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7895 if (NILP (handler))
7897 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7899 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7901 /* ShellExecute fails if DOCUMENT is a UNC with forward
7902 slashes (expand-file-name above converts all backslashes
7903 to forward slashes). Now that we know DOCUMENT is a
7904 file, we can mirror all forward slashes into backslashes. */
7905 unixtodos_filename (SSDATA (absdoc_encoded));
7906 document = absdoc_encoded;
7908 else
7909 document = ENCODE_FILE (document);
7911 else
7912 document = ENCODE_FILE (document);
7914 current_dir = ENCODE_FILE (current_dir);
7915 /* Cannot use filename_to_utf16/ansi with DOCUMENT, since it could
7916 be a URL that is not limited to MAX_PATH chararcters. */
7917 doclen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7918 SSDATA (document), -1, NULL, 0);
7919 doc_w = xmalloc (doclen * sizeof (wchar_t));
7920 pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
7921 SSDATA (document), -1, doc_w, doclen);
7922 if (use_unicode)
7924 wchar_t current_dir_w[MAX_PATH];
7925 SHELLEXECUTEINFOW shexinfo_w;
7927 /* Encode the current directory and parameters, and convert
7928 operation to UTF-16. */
7929 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7930 if (STRINGP (parameters))
7932 int len;
7934 parameters = ENCODE_SYSTEM (parameters);
7935 len = pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
7936 SSDATA (parameters), -1, NULL, 0);
7937 if (len > 32768)
7938 len = 32768;
7939 params_w = alloca (len * sizeof (wchar_t));
7940 pMultiByteToWideChar (CP_ACP, multiByteToWideCharFlags,
7941 SSDATA (parameters), -1, params_w, len);
7942 params_w[len - 1] = 0;
7944 if (STRINGP (operation))
7946 /* Assume OPERATION is pure ASCII. */
7947 const char *s = SSDATA (operation);
7948 wchar_t *d;
7949 int len = SBYTES (operation) + 1;
7951 if (len > 32768)
7952 len = 32768;
7953 d = ops_w = alloca (len * sizeof (wchar_t));
7954 while (d < ops_w + len - 1)
7955 *d++ = *s++;
7956 *d = 0;
7959 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7960 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7961 able to invoke verbs from shortcut menu extensions, not just
7962 static verbs listed in the Registry. */
7963 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7964 shexinfo_w.cbSize = sizeof (shexinfo_w);
7965 shexinfo_w.fMask =
7966 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7967 shexinfo_w.hwnd = NULL;
7968 shexinfo_w.lpVerb = ops_w;
7969 shexinfo_w.lpFile = doc_w;
7970 shexinfo_w.lpParameters = params_w;
7971 shexinfo_w.lpDirectory = current_dir_w;
7972 shexinfo_w.nShow =
7973 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7974 success = ShellExecuteExW (&shexinfo_w);
7975 xfree (doc_w);
7977 else
7979 char current_dir_a[MAX_PATH];
7980 SHELLEXECUTEINFOA shexinfo_a;
7981 int codepage = codepage_for_filenames (NULL);
7982 int ldoc_a = pWideCharToMultiByte (codepage, 0, doc_w, -1, NULL, 0,
7983 NULL, NULL);
7985 doc_a = xmalloc (ldoc_a);
7986 pWideCharToMultiByte (codepage, 0, doc_w, -1, doc_a, ldoc_a, NULL, NULL);
7987 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7988 if (STRINGP (parameters))
7990 parameters = ENCODE_SYSTEM (parameters);
7991 params_a = SSDATA (parameters);
7993 if (STRINGP (operation))
7995 /* Assume OPERATION is pure ASCII. */
7996 ops_a = SSDATA (operation);
7998 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7999 shexinfo_a.cbSize = sizeof (shexinfo_a);
8000 shexinfo_a.fMask =
8001 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
8002 shexinfo_a.hwnd = NULL;
8003 shexinfo_a.lpVerb = ops_a;
8004 shexinfo_a.lpFile = doc_a;
8005 shexinfo_a.lpParameters = params_a;
8006 shexinfo_a.lpDirectory = current_dir_a;
8007 shexinfo_a.nShow =
8008 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
8009 success = ShellExecuteExA (&shexinfo_a);
8010 xfree (doc_w);
8011 xfree (doc_a);
8014 if (success)
8015 return Qt;
8017 errstr = w32_strerror (0);
8019 #endif /* !CYGWIN */
8021 /* The error string might be encoded in the locale's encoding. */
8022 if (!NILP (Vlocale_coding_system))
8024 Lisp_Object decoded =
8025 code_convert_string_norecord (build_unibyte_string (errstr),
8026 Vlocale_coding_system, 0);
8027 errstr = SSDATA (decoded);
8029 error ("ShellExecute failed: %s", errstr);
8032 /* Lookup virtual keycode from string representing the name of a
8033 non-ascii keystroke into the corresponding virtual key, using
8034 lispy_function_keys. */
8035 static int
8036 lookup_vk_code (char *key)
8038 int i;
8040 for (i = 0; i < 256; i++)
8041 if (lispy_function_keys[i]
8042 && strcmp (lispy_function_keys[i], key) == 0)
8043 return i;
8045 if (w32_kbdhook_active)
8047 /* Alphanumerics map to themselves. */
8048 if (key[1] == 0)
8050 if ((key[0] >= 'A' && key[0] <= 'Z')
8051 || (key[0] >= '0' && key[0] <= '9'))
8052 return key[0];
8053 if (key[0] >= 'a' && key[0] <= 'z')
8054 return toupper(key[0]);
8058 return -1;
8061 /* Convert a one-element vector style key sequence to a hot key
8062 definition. */
8063 static Lisp_Object
8064 w32_parse_and_hook_hot_key (Lisp_Object key, int hook)
8066 /* Copied from Fdefine_key and store_in_keymap. */
8067 register Lisp_Object c;
8068 int vk_code;
8069 int lisp_modifiers;
8070 int w32_modifiers;
8071 Lisp_Object res = Qnil;
8072 char* vkname;
8074 CHECK_VECTOR (key);
8076 if (ASIZE (key) != 1)
8077 return Qnil;
8079 c = AREF (key, 0);
8081 if (CONSP (c) && lucid_event_type_list_p (c))
8082 c = Fevent_convert_list (c);
8084 if (! INTEGERP (c) && ! SYMBOLP (c))
8085 error ("Key definition is invalid");
8087 /* Work out the base key and the modifiers. */
8088 if (SYMBOLP (c))
8090 c = parse_modifiers (c);
8091 lisp_modifiers = XINT (Fcar (Fcdr (c)));
8092 c = Fcar (c);
8093 if (!SYMBOLP (c))
8094 emacs_abort ();
8095 vkname = SSDATA (SYMBOL_NAME (c));
8096 /* [s-], [M-], [h-]: Register all keys for this modifier */
8097 if (w32_kbdhook_active && vkname[0] == 0)
8098 vk_code = VK_ANY;
8099 else
8100 vk_code = lookup_vk_code (vkname);
8102 else if (INTEGERP (c))
8104 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
8105 /* Many ascii characters are their own virtual key code. */
8106 vk_code = XINT (c) & CHARACTERBITS;
8109 if (vk_code < 0 || vk_code > 255)
8110 return Qnil;
8112 if ((lisp_modifiers & meta_modifier) != 0
8113 && !NILP (Vw32_alt_is_meta))
8114 lisp_modifiers |= alt_modifier;
8116 /* Supply defs missing from mingw32. */
8117 #ifndef MOD_ALT
8118 #define MOD_ALT 0x0001
8119 #define MOD_CONTROL 0x0002
8120 #define MOD_SHIFT 0x0004
8121 #define MOD_WIN 0x0008
8122 #endif
8124 if (w32_kbdhook_active)
8126 /* Register Alt-x combinations. */
8127 if (lisp_modifiers & alt_modifier)
8129 hook_w32_key (hook, VK_MENU, vk_code);
8130 res = Qt;
8132 /* Register Win-x combinations based on modifier mappings. */
8133 if (((lisp_modifiers & hyper_modifier)
8134 && EQ (Vw32_lwindow_modifier, Qhyper))
8135 || ((lisp_modifiers & super_modifier)
8136 && EQ (Vw32_lwindow_modifier, Qsuper)))
8138 hook_w32_key (hook, VK_LWIN, vk_code);
8139 res = Qt;
8141 if (((lisp_modifiers & hyper_modifier)
8142 && EQ (Vw32_rwindow_modifier, Qhyper))
8143 || ((lisp_modifiers & super_modifier)
8144 && EQ (Vw32_rwindow_modifier, Qsuper)))
8146 hook_w32_key (hook, VK_RWIN, vk_code);
8147 res = Qt;
8149 return res;
8151 else
8153 /* Convert lisp modifiers to Windows hot-key form. */
8154 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
8155 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
8156 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
8157 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
8159 return HOTKEY (vk_code, w32_modifiers);
8163 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
8164 Sw32_register_hot_key, 1, 1, 0,
8165 doc: /* Register KEY as a hot-key combination.
8166 Certain key combinations like Alt-Tab and Win-R are reserved for
8167 system use on Windows, and therefore are normally intercepted by the
8168 system. These key combinations can be received by registering them
8169 as hot-keys, except for Win-L which always locks the computer.
8171 On Windows 98 and ME, KEY must be a one element key definition in
8172 vector form that would be acceptable to `define-key' (e.g. [A-tab] for
8173 Alt-Tab). The meta modifier is interpreted as Alt if
8174 `w32-alt-is-meta' is t, and hyper is always interpreted as the Windows
8175 modifier keys. The return value is the hotkey-id if registered, otherwise nil.
8177 On Windows versions since NT, KEY can also be specified as [M-], [s-] or
8178 [h-] to indicate that all combinations of that key should be processed
8179 by Emacs instead of the operating system. The super and hyper
8180 modifiers are interpreted according to the current values of
8181 `w32-lwindow-modifier' and `w32-rwindow-modifier'. For instance,
8182 setting `w32-lwindow-modifier' to `super' and then calling
8183 `(register-hot-key [s-])' grabs all combinations of the left Windows
8184 key to Emacs, but leaves the right Windows key free for the operating
8185 system keyboard shortcuts. The return value is t if the call affected
8186 any key combinations, otherwise nil. */)
8187 (Lisp_Object key)
8189 key = w32_parse_and_hook_hot_key (key, 1);
8191 if (!w32_kbdhook_active
8192 && !NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
8194 /* Reuse an empty slot if possible. */
8195 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
8197 /* Safe to add new key to list, even if we have focus. */
8198 if (NILP (item))
8199 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
8200 else
8201 XSETCAR (item, key);
8203 /* Notify input thread about new hot-key definition, so that it
8204 takes effect without needing to switch focus. */
8205 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
8206 (WPARAM) XINT (key), 0);
8209 return key;
8212 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
8213 Sw32_unregister_hot_key, 1, 1, 0,
8214 doc: /* Unregister KEY as a hot-key combination. */)
8215 (Lisp_Object key)
8217 Lisp_Object item;
8219 if (!INTEGERP (key))
8220 key = w32_parse_and_hook_hot_key (key, 0);
8222 if (w32_kbdhook_active)
8223 return key;
8225 item = Fmemq (key, w32_grabbed_keys);
8227 if (!NILP (item))
8229 LPARAM lparam;
8231 eassert (CONSP (item));
8232 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
8233 so that it works in a --with-wide-int build as well. */
8234 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
8236 /* Notify input thread about hot-key definition being removed, so
8237 that it takes effect without needing focus switch. */
8238 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
8239 (WPARAM) XINT (XCAR (item)), lparam))
8241 MSG msg;
8242 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8244 return Qt;
8246 return Qnil;
8249 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
8250 Sw32_registered_hot_keys, 0, 0, 0,
8251 doc: /* Return list of registered hot-key IDs. */)
8252 (void)
8254 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
8257 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
8258 Sw32_reconstruct_hot_key, 1, 1, 0,
8259 doc: /* Convert hot-key ID to a lisp key combination.
8260 usage: (w32-reconstruct-hot-key ID) */)
8261 (Lisp_Object hotkeyid)
8263 int vk_code, w32_modifiers;
8264 Lisp_Object key;
8266 CHECK_NUMBER (hotkeyid);
8268 vk_code = HOTKEY_VK_CODE (hotkeyid);
8269 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
8271 if (vk_code < 256 && lispy_function_keys[vk_code])
8272 key = intern (lispy_function_keys[vk_code]);
8273 else
8274 key = make_number (vk_code);
8276 key = Fcons (key, Qnil);
8277 if (w32_modifiers & MOD_SHIFT)
8278 key = Fcons (Qshift, key);
8279 if (w32_modifiers & MOD_CONTROL)
8280 key = Fcons (Qctrl, key);
8281 if (w32_modifiers & MOD_ALT)
8282 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
8283 if (w32_modifiers & MOD_WIN)
8284 key = Fcons (Qhyper, key);
8286 return key;
8289 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
8290 Sw32_toggle_lock_key, 1, 2, 0,
8291 doc: /* Toggle the state of the lock key KEY.
8292 KEY can be `capslock', `kp-numlock', or `scroll'.
8293 If the optional parameter NEW-STATE is a number, then the state of KEY
8294 is set to off if the low bit of NEW-STATE is zero, otherwise on.
8295 If NEW-STATE is omitted or nil, the function toggles the state,
8297 Value is the new state of the key, or nil if the function failed
8298 to change the state. */)
8299 (Lisp_Object key, Lisp_Object new_state)
8301 int vk_code;
8302 LPARAM lparam;
8304 if (EQ (key, intern ("capslock")))
8305 vk_code = VK_CAPITAL;
8306 else if (EQ (key, intern ("kp-numlock")))
8307 vk_code = VK_NUMLOCK;
8308 else if (EQ (key, intern ("scroll")))
8309 vk_code = VK_SCROLL;
8310 else
8311 return Qnil;
8313 if (!dwWindowsThreadId)
8314 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
8316 if (NILP (new_state))
8317 lparam = -1;
8318 else
8319 lparam = (XUINT (new_state)) & 1;
8320 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
8321 (WPARAM) vk_code, lparam))
8323 MSG msg;
8324 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
8325 return make_number (msg.wParam);
8327 return Qnil;
8330 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
8331 2, 2, 0,
8332 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
8334 This is a direct interface to the Windows API FindWindow function. */)
8335 (Lisp_Object class, Lisp_Object name)
8337 HWND hnd;
8339 if (!NILP (class))
8340 CHECK_STRING (class);
8341 if (!NILP (name))
8342 CHECK_STRING (name);
8344 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
8345 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
8346 if (!hnd)
8347 return Qnil;
8348 return Qt;
8351 DEFUN ("w32-frame-geometry", Fw32_frame_geometry, Sw32_frame_geometry, 0, 1, 0,
8352 doc: /* Return geometric attributes of FRAME.
8353 FRAME must be a live frame and defaults to the selected one. The return
8354 value is an association list of the attributes listed below. All height
8355 and width values are in pixels.
8357 `outer-position' is a cons of the outer left and top edges of FRAME
8358 relative to the origin - the position (0, 0) - of FRAME's display.
8360 `outer-size' is a cons of the outer width and height of FRAME. The
8361 outer size includes the title bar and the external borders as well as
8362 any menu and/or tool bar of frame.
8364 `external-border-size' is a cons of the horizontal and vertical width of
8365 FRAME's external borders as supplied by the window manager.
8367 `title-bar-size' is a cons of the width and height of the title bar of
8368 FRAME as supplied by the window manager. If both of them are zero,
8369 FRAME has no title bar. If only the width is zero, Emacs was not
8370 able to retrieve the width information.
8372 `menu-bar-external', if non-nil, means the menu bar is external (never
8373 included in the inner edges of FRAME).
8375 `menu-bar-size' is a cons of the width and height of the menu bar of
8376 FRAME.
8378 `tool-bar-external', if non-nil, means the tool bar is external (never
8379 included in the inner edges of FRAME).
8381 `tool-bar-position' tells on which side the tool bar on FRAME is and can
8382 be one of `left', `top', `right' or `bottom'. If this is nil, FRAME
8383 has no tool bar.
8385 `tool-bar-size' is a cons of the width and height of the tool bar of
8386 FRAME.
8388 `internal-border-width' is the width of the internal border of
8389 FRAME. */)
8390 (Lisp_Object frame)
8392 struct frame *f = decode_live_frame (frame);
8394 MENUBARINFO menu_bar;
8395 WINDOWINFO window;
8396 int left, top, right, bottom;
8397 unsigned int external_border_width, external_border_height;
8398 int title_bar_width = 0, title_bar_height = 0;
8399 int single_menu_bar_height, wrapped_menu_bar_height, menu_bar_height;
8400 int tool_bar_height = FRAME_TOOL_BAR_HEIGHT (f);
8401 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8403 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8404 return Qnil;
8406 block_input ();
8407 /* Outer rectangle and borders. */
8408 window.cbSize = sizeof (window);
8409 GetWindowInfo (FRAME_W32_WINDOW (f), &window);
8410 external_border_width = window.cxWindowBorders;
8411 external_border_height = window.cyWindowBorders;
8412 /* Title bar. */
8413 if (get_title_bar_info_fn)
8415 TITLEBAR_INFO title_bar;
8417 title_bar.cbSize = sizeof (title_bar);
8418 title_bar.rcTitleBar.left = title_bar.rcTitleBar.right = 0;
8419 title_bar.rcTitleBar.top = title_bar.rcTitleBar.bottom = 0;
8420 for (int i = 0; i < 6; i++)
8421 title_bar.rgstate[i] = 0;
8422 if (get_title_bar_info_fn (FRAME_W32_WINDOW (f), &title_bar)
8423 && !(title_bar.rgstate[0] & 0x00008001))
8425 title_bar_width
8426 = title_bar.rcTitleBar.right - title_bar.rcTitleBar.left;
8427 title_bar_height
8428 = title_bar.rcTitleBar.bottom - title_bar.rcTitleBar.top;
8431 else if ((window.dwStyle & WS_CAPTION) == WS_CAPTION)
8432 title_bar_height = GetSystemMetrics (SM_CYCAPTION);
8433 /* Menu bar. */
8434 menu_bar.cbSize = sizeof (menu_bar);
8435 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
8436 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
8437 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
8438 single_menu_bar_height = GetSystemMetrics (SM_CYMENU);
8439 wrapped_menu_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
8440 unblock_input ();
8442 left = window.rcWindow.left;
8443 top = window.rcWindow.top;
8444 right = window.rcWindow.right;
8445 bottom = window.rcWindow.bottom;
8447 /* Menu bar. */
8448 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
8449 /* Fix menu bar height reported by GetMenuBarInfo. */
8450 if (menu_bar_height > single_menu_bar_height)
8451 /* A wrapped menu bar. */
8452 menu_bar_height += single_menu_bar_height - wrapped_menu_bar_height;
8453 else if (menu_bar_height > 0)
8454 /* A single line menu bar. */
8455 menu_bar_height = single_menu_bar_height;
8457 return listn (CONSTYPE_HEAP, 10,
8458 Fcons (Qouter_position,
8459 Fcons (make_number (left), make_number (top))),
8460 Fcons (Qouter_size,
8461 Fcons (make_number (right - left),
8462 make_number (bottom - top))),
8463 Fcons (Qexternal_border_size,
8464 Fcons (make_number (external_border_width),
8465 make_number (external_border_height))),
8466 Fcons (Qtitle_bar_size,
8467 Fcons (make_number (title_bar_width),
8468 make_number (title_bar_height))),
8469 Fcons (Qmenu_bar_external, Qt),
8470 Fcons (Qmenu_bar_size,
8471 Fcons (make_number
8472 (menu_bar.rcBar.right - menu_bar.rcBar.left),
8473 make_number (menu_bar_height))),
8474 Fcons (Qtool_bar_external, Qnil),
8475 Fcons (Qtool_bar_position, tool_bar_height ? Qtop : Qnil),
8476 Fcons (Qtool_bar_size,
8477 Fcons (make_number
8478 (tool_bar_height
8479 ? (right - left - 2 * external_border_width
8480 - 2 * internal_border_width)
8481 : 0),
8482 make_number (tool_bar_height))),
8483 Fcons (Qinternal_border_width,
8484 make_number (internal_border_width)));
8487 DEFUN ("w32-frame-edges", Fw32_frame_edges, Sw32_frame_edges, 0, 2, 0,
8488 doc: /* Return edge coordinates of FRAME.
8489 FRAME must be a live frame and defaults to the selected one. The return
8490 value is a list of the form (LEFT, TOP, RIGHT, BOTTOM). All values are
8491 in pixels relative to the origin - the position (0, 0) - of FRAME's
8492 display.
8494 If optional argument TYPE is the symbol `outer-edges', return the outer
8495 edges of FRAME. The outer edges comprise the decorations of the window
8496 manager (like the title bar or external borders) as well as any external
8497 menu or tool bar of FRAME. If optional argument TYPE is the symbol
8498 `native-edges' or nil, return the native edges of FRAME. The native
8499 edges exclude the decorations of the window manager and any external
8500 menu or tool bar of FRAME. If TYPE is the symbol `inner-edges', return
8501 the inner edges of FRAME. These edges exclude title bar, any borders,
8502 menu bar or tool bar of FRAME. */)
8503 (Lisp_Object frame, Lisp_Object type)
8505 struct frame *f = decode_live_frame (frame);
8507 if (FRAME_INITIAL_P (f) || !FRAME_W32_P (f))
8508 return Qnil;
8510 if (EQ (type, Qouter_edges))
8512 RECT rectangle;
8514 block_input ();
8515 /* Outer frame rectangle, including outer borders and title bar. */
8516 GetWindowRect (FRAME_W32_WINDOW (f), &rectangle);
8517 unblock_input ();
8519 return list4 (make_number (rectangle.left),
8520 make_number (rectangle.top),
8521 make_number (rectangle.right),
8522 make_number (rectangle.bottom));
8524 else
8526 RECT rectangle;
8527 POINT pt;
8528 int left, top, right, bottom;
8530 block_input ();
8531 /* Inner frame rectangle, excluding borders and title bar. */
8532 GetClientRect (FRAME_W32_WINDOW (f), &rectangle);
8533 /* Get top-left corner of native rectangle in screen
8534 coordinates. */
8535 pt.x = 0;
8536 pt.y = 0;
8537 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
8538 unblock_input ();
8540 left = pt.x;
8541 top = pt.y;
8542 right = left + rectangle.right;
8543 bottom = top + rectangle.bottom;
8545 if (EQ (type, Qinner_edges))
8547 int internal_border_width = FRAME_INTERNAL_BORDER_WIDTH (f);
8549 return list4 (make_number (left + internal_border_width),
8550 make_number (top
8551 + FRAME_TOOL_BAR_HEIGHT (f)
8552 + internal_border_width),
8553 make_number (right - internal_border_width),
8554 make_number (bottom - internal_border_width));
8556 else
8557 return list4 (make_number (left), make_number (top),
8558 make_number (right), make_number (bottom));
8562 DEFUN ("w32-mouse-absolute-pixel-position", Fw32_mouse_absolute_pixel_position,
8563 Sw32_mouse_absolute_pixel_position, 0, 0, 0,
8564 doc: /* Return absolute position of mouse cursor in pixels.
8565 The position is returned as a cons cell (X . Y) of the coordinates of
8566 the mouse cursor position in pixels relative to a position (0, 0) of the
8567 selected frame's display. */)
8568 (void)
8570 POINT pt;
8572 block_input ();
8573 GetCursorPos (&pt);
8574 unblock_input ();
8576 return Fcons (make_number (pt.x), make_number (pt.y));
8579 DEFUN ("w32-set-mouse-absolute-pixel-position", Fw32_set_mouse_absolute_pixel_position,
8580 Sw32_set_mouse_absolute_pixel_position, 2, 2, 0,
8581 doc: /* Move mouse pointer to absolute pixel position (X, Y).
8582 The coordinates X and Y are interpreted in pixels relative to a position
8583 \(0, 0) of the selected frame's display. */)
8584 (Lisp_Object x, Lisp_Object y)
8586 UINT trail_num = 0;
8587 BOOL ret = false;
8589 CHECK_TYPE_RANGED_INTEGER (int, x);
8590 CHECK_TYPE_RANGED_INTEGER (int, y);
8592 block_input ();
8593 /* When "mouse trails" are in effect, moving the mouse cursor
8594 sometimes leaves behind an annoying "ghost" of the pointer.
8595 Avoid that by momentarily switching off mouse trails. */
8596 if (os_subtype == OS_NT
8597 && w32_major_version + w32_minor_version >= 6)
8598 ret = SystemParametersInfo (SPI_GETMOUSETRAILS, 0, &trail_num, 0);
8599 SetCursorPos (XINT (x), XINT (y));
8600 if (ret)
8601 SystemParametersInfo (SPI_SETMOUSETRAILS, trail_num, NULL, 0);
8602 unblock_input ();
8604 return Qnil;
8607 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
8608 doc: /* Get power status information from Windows system.
8610 The following %-sequences are provided:
8611 %L AC line status (verbose)
8612 %B Battery status (verbose)
8613 %b Battery status, empty means high, `-' means low,
8614 `!' means critical, and `+' means charging
8615 %p Battery load percentage
8616 %s Remaining time (to charge or discharge) in seconds
8617 %m Remaining time (to charge or discharge) in minutes
8618 %h Remaining time (to charge or discharge) in hours
8619 %t Remaining time (to charge or discharge) in the form `h:min' */)
8620 (void)
8622 Lisp_Object status = Qnil;
8624 SYSTEM_POWER_STATUS system_status;
8625 if (GetSystemPowerStatus (&system_status))
8627 Lisp_Object line_status, battery_status, battery_status_symbol;
8628 Lisp_Object load_percentage, seconds, minutes, hours, remain;
8630 long seconds_left = (long) system_status.BatteryLifeTime;
8632 if (system_status.ACLineStatus == 0)
8633 line_status = build_string ("off-line");
8634 else if (system_status.ACLineStatus == 1)
8635 line_status = build_string ("on-line");
8636 else
8637 line_status = build_string ("N/A");
8639 if (system_status.BatteryFlag & 128)
8641 battery_status = build_string ("N/A");
8642 battery_status_symbol = empty_unibyte_string;
8644 else if (system_status.BatteryFlag & 8)
8646 battery_status = build_string ("charging");
8647 battery_status_symbol = build_string ("+");
8648 if (system_status.BatteryFullLifeTime != -1L)
8649 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
8651 else if (system_status.BatteryFlag & 4)
8653 battery_status = build_string ("critical");
8654 battery_status_symbol = build_string ("!");
8656 else if (system_status.BatteryFlag & 2)
8658 battery_status = build_string ("low");
8659 battery_status_symbol = build_string ("-");
8661 else if (system_status.BatteryFlag & 1)
8663 battery_status = build_string ("high");
8664 battery_status_symbol = empty_unibyte_string;
8666 else
8668 battery_status = build_string ("medium");
8669 battery_status_symbol = empty_unibyte_string;
8672 if (system_status.BatteryLifePercent > 100)
8673 load_percentage = build_string ("N/A");
8674 else
8676 char buffer[16];
8677 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
8678 load_percentage = build_string (buffer);
8681 if (seconds_left < 0)
8682 seconds = minutes = hours = remain = build_string ("N/A");
8683 else
8685 long m;
8686 double h;
8687 char buffer[16];
8688 snprintf (buffer, 16, "%ld", seconds_left);
8689 seconds = build_string (buffer);
8691 m = seconds_left / 60;
8692 snprintf (buffer, 16, "%ld", m);
8693 minutes = build_string (buffer);
8695 h = seconds_left / 3600.0;
8696 snprintf (buffer, 16, "%3.1f", h);
8697 hours = build_string (buffer);
8699 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
8700 remain = build_string (buffer);
8703 status = listn (CONSTYPE_HEAP, 8,
8704 Fcons (make_number ('L'), line_status),
8705 Fcons (make_number ('B'), battery_status),
8706 Fcons (make_number ('b'), battery_status_symbol),
8707 Fcons (make_number ('p'), load_percentage),
8708 Fcons (make_number ('s'), seconds),
8709 Fcons (make_number ('m'), minutes),
8710 Fcons (make_number ('h'), hours),
8711 Fcons (make_number ('t'), remain));
8713 return status;
8717 #ifdef WINDOWSNT
8718 typedef BOOL (WINAPI *GetDiskFreeSpaceExW_Proc)
8719 (LPCWSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8720 typedef BOOL (WINAPI *GetDiskFreeSpaceExA_Proc)
8721 (LPCSTR, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER);
8723 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
8724 doc: /* Return storage information about the file system FILENAME is on.
8725 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
8726 storage of the file system, FREE is the free storage, and AVAIL is the
8727 storage available to a non-superuser. All 3 numbers are in bytes.
8728 If the underlying system call fails, value is nil. */)
8729 (Lisp_Object filename)
8731 Lisp_Object encoded, value;
8733 CHECK_STRING (filename);
8734 filename = Fexpand_file_name (filename, Qnil);
8735 encoded = ENCODE_FILE (filename);
8737 value = Qnil;
8739 /* Determining the required information on Windows turns out, sadly,
8740 to be more involved than one would hope. The original Windows API
8741 call for this will return bogus information on some systems, but we
8742 must dynamically probe for the replacement api, since that was
8743 added rather late on. */
8745 HMODULE hKernel = GetModuleHandle ("kernel32");
8746 GetDiskFreeSpaceExW_Proc pfn_GetDiskFreeSpaceExW =
8747 (GetDiskFreeSpaceExW_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
8748 GetDiskFreeSpaceExA_Proc pfn_GetDiskFreeSpaceExA =
8749 (GetDiskFreeSpaceExA_Proc) GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
8750 bool have_pfn_GetDiskFreeSpaceEx =
8751 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
8752 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
8754 /* On Windows, we may need to specify the root directory of the
8755 volume holding FILENAME. */
8756 char rootname[MAX_UTF8_PATH];
8757 wchar_t rootname_w[MAX_PATH];
8758 char rootname_a[MAX_PATH];
8759 char *name = SSDATA (encoded);
8760 BOOL result;
8762 /* find the root name of the volume if given */
8763 if (isalpha (name[0]) && name[1] == ':')
8765 rootname[0] = name[0];
8766 rootname[1] = name[1];
8767 rootname[2] = '\\';
8768 rootname[3] = 0;
8770 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
8772 char *str = rootname;
8773 int slashes = 4;
8776 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
8777 break;
8778 *str++ = *name++;
8780 while ( *name );
8782 *str++ = '\\';
8783 *str = 0;
8786 if (w32_unicode_filenames)
8787 filename_to_utf16 (rootname, rootname_w);
8788 else
8789 filename_to_ansi (rootname, rootname_a);
8791 if (have_pfn_GetDiskFreeSpaceEx)
8793 /* Unsigned large integers cannot be cast to double, so
8794 use signed ones instead. */
8795 LARGE_INTEGER availbytes;
8796 LARGE_INTEGER freebytes;
8797 LARGE_INTEGER totalbytes;
8799 if (w32_unicode_filenames)
8800 result = pfn_GetDiskFreeSpaceExW (rootname_w,
8801 (ULARGE_INTEGER *)&availbytes,
8802 (ULARGE_INTEGER *)&totalbytes,
8803 (ULARGE_INTEGER *)&freebytes);
8804 else
8805 result = pfn_GetDiskFreeSpaceExA (rootname_a,
8806 (ULARGE_INTEGER *)&availbytes,
8807 (ULARGE_INTEGER *)&totalbytes,
8808 (ULARGE_INTEGER *)&freebytes);
8809 if (result)
8810 value = list3 (make_float ((double) totalbytes.QuadPart),
8811 make_float ((double) freebytes.QuadPart),
8812 make_float ((double) availbytes.QuadPart));
8814 else
8816 DWORD sectors_per_cluster;
8817 DWORD bytes_per_sector;
8818 DWORD free_clusters;
8819 DWORD total_clusters;
8821 if (w32_unicode_filenames)
8822 result = GetDiskFreeSpaceW (rootname_w,
8823 &sectors_per_cluster,
8824 &bytes_per_sector,
8825 &free_clusters,
8826 &total_clusters);
8827 else
8828 result = GetDiskFreeSpaceA (rootname_a,
8829 &sectors_per_cluster,
8830 &bytes_per_sector,
8831 &free_clusters,
8832 &total_clusters);
8833 if (result)
8834 value = list3 (make_float ((double) total_clusters
8835 * sectors_per_cluster * bytes_per_sector),
8836 make_float ((double) free_clusters
8837 * sectors_per_cluster * bytes_per_sector),
8838 make_float ((double) free_clusters
8839 * sectors_per_cluster * bytes_per_sector));
8843 return value;
8845 #endif /* WINDOWSNT */
8848 #ifdef WINDOWSNT
8849 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
8850 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
8851 (void)
8853 static char pname_buf[256];
8854 int err;
8855 HANDLE hPrn;
8856 PRINTER_INFO_2W *ppi2w = NULL;
8857 PRINTER_INFO_2A *ppi2a = NULL;
8858 DWORD dwNeeded = 0, dwReturned = 0;
8859 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
8860 char port_name[MAX_UTF8_PATH];
8862 /* Retrieve the default string from Win.ini (the registry).
8863 * String will be in form "printername,drivername,portname".
8864 * This is the most portable way to get the default printer. */
8865 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
8866 return Qnil;
8867 /* printername precedes first "," character */
8868 strtok (pname_buf, ",");
8869 /* We want to know more than the printer name */
8870 if (!OpenPrinter (pname_buf, &hPrn, NULL))
8871 return Qnil;
8872 /* GetPrinterW is not supported by unicows.dll. */
8873 if (w32_unicode_filenames && os_subtype != OS_9X)
8874 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
8875 else
8876 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
8877 if (dwNeeded == 0)
8879 ClosePrinter (hPrn);
8880 return Qnil;
8882 /* Call GetPrinter again with big enough memory block. */
8883 if (w32_unicode_filenames && os_subtype != OS_9X)
8885 /* Allocate memory for the PRINTER_INFO_2 struct. */
8886 ppi2w = xmalloc (dwNeeded);
8887 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
8888 ClosePrinter (hPrn);
8889 if (!err)
8891 xfree (ppi2w);
8892 return Qnil;
8895 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
8896 && ppi2w->pServerName)
8898 filename_from_utf16 (ppi2w->pServerName, server_name);
8899 filename_from_utf16 (ppi2w->pShareName, share_name);
8901 else
8903 server_name[0] = '\0';
8904 filename_from_utf16 (ppi2w->pPortName, port_name);
8907 else
8909 ppi2a = xmalloc (dwNeeded);
8910 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
8911 ClosePrinter (hPrn);
8912 if (!err)
8914 xfree (ppi2a);
8915 return Qnil;
8918 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
8919 && ppi2a->pServerName)
8921 filename_from_ansi (ppi2a->pServerName, server_name);
8922 filename_from_ansi (ppi2a->pShareName, share_name);
8924 else
8926 server_name[0] = '\0';
8927 filename_from_ansi (ppi2a->pPortName, port_name);
8931 if (server_name[0])
8933 /* a remote printer */
8934 if (server_name[0] == '\\')
8935 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
8936 share_name);
8937 else
8938 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
8939 share_name);
8940 pname_buf[sizeof (pname_buf) - 1] = '\0';
8942 else
8944 /* a local printer */
8945 strncpy (pname_buf, port_name, sizeof (pname_buf));
8946 pname_buf[sizeof (pname_buf) - 1] = '\0';
8947 /* `pPortName' can include several ports, delimited by ','.
8948 * we only use the first one. */
8949 strtok (pname_buf, ",");
8952 return DECODE_FILE (build_unibyte_string (pname_buf));
8954 #endif /* WINDOWSNT */
8957 /* Equivalent of strerror for W32 error codes. */
8958 char *
8959 w32_strerror (int error_no)
8961 static char buf[500];
8962 DWORD ret;
8964 if (error_no == 0)
8965 error_no = GetLastError ();
8967 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
8968 FORMAT_MESSAGE_IGNORE_INSERTS,
8969 NULL,
8970 error_no,
8971 0, /* choose most suitable language */
8972 buf, sizeof (buf), NULL);
8974 while (ret > 0 && (buf[ret - 1] == '\n' ||
8975 buf[ret - 1] == '\r' ))
8976 --ret;
8977 buf[ret] = '\0';
8978 if (!ret)
8979 sprintf (buf, "w32 error %d", error_no);
8981 return buf;
8984 /* For convenience when debugging. (You cannot call GetLastError
8985 directly from GDB: it will crash, because it uses the __stdcall
8986 calling convention, not the _cdecl convention assumed by GDB.) */
8987 DWORD w32_last_error (void);
8989 DWORD
8990 w32_last_error (void)
8992 return GetLastError ();
8995 /* Cache information describing the NT system for later use. */
8996 void
8997 cache_system_info (void)
8999 union
9001 struct info
9003 char major;
9004 char minor;
9005 short platform;
9006 } info;
9007 DWORD data;
9008 } version;
9010 /* Cache the module handle of Emacs itself. */
9011 hinst = GetModuleHandle (NULL);
9013 /* Cache the version of the operating system. */
9014 version.data = GetVersion ();
9015 w32_major_version = version.info.major;
9016 w32_minor_version = version.info.minor;
9018 if (version.info.platform & 0x8000)
9019 os_subtype = OS_9X;
9020 else
9021 os_subtype = OS_NT;
9023 /* Cache page size, allocation unit, processor type, etc. */
9024 GetSystemInfo (&sysinfo_cache);
9025 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
9027 /* Cache os info. */
9028 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
9029 GetVersionEx (&osinfo_cache);
9031 w32_build_number = osinfo_cache.dwBuildNumber;
9032 if (os_subtype == OS_9X)
9033 w32_build_number &= 0xffff;
9035 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
9038 #ifdef EMACSDEBUG
9039 void
9040 _DebPrint (const char *fmt, ...)
9042 char buf[1024];
9043 va_list args;
9045 va_start (args, fmt);
9046 vsprintf (buf, fmt, args);
9047 va_end (args);
9048 #if CYGWIN
9049 fprintf (stderr, "%s", buf);
9050 #endif
9051 OutputDebugString (buf);
9053 #endif
9056 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
9058 int cur_state = (GetKeyState (vk_code) & 1);
9060 if (NILP (new_state)
9061 || (NUMBERP (new_state)
9062 && ((XUINT (new_state)) & 1) != cur_state))
9064 #ifdef WINDOWSNT
9065 faked_key = vk_code;
9066 #endif /* WINDOWSNT */
9068 keybd_event ((BYTE) vk_code,
9069 (BYTE) MapVirtualKey (vk_code, 0),
9070 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9071 keybd_event ((BYTE) vk_code,
9072 (BYTE) MapVirtualKey (vk_code, 0),
9073 KEYEVENTF_EXTENDEDKEY | 0, 0);
9074 keybd_event ((BYTE) vk_code,
9075 (BYTE) MapVirtualKey (vk_code, 0),
9076 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
9077 cur_state = !cur_state;
9080 return cur_state;
9083 /* Translate console modifiers to emacs modifiers.
9084 German keyboard support (Kai Morgan Zeise 2/18/95). */
9086 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
9088 int retval = 0;
9090 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
9091 pressed, first remove those modifiers. */
9092 if (!NILP (Vw32_recognize_altgr)
9093 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9094 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
9095 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
9097 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
9098 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
9100 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9102 retval |= ctrl_modifier;
9103 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9104 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
9105 retval |= meta_modifier;
9108 if (mods & LEFT_WIN_PRESSED)
9109 retval |= w32_key_to_modifier (VK_LWIN);
9110 if (mods & RIGHT_WIN_PRESSED)
9111 retval |= w32_key_to_modifier (VK_RWIN);
9112 if (mods & APPS_PRESSED)
9113 retval |= w32_key_to_modifier (VK_APPS);
9114 if (mods & SCROLLLOCK_ON)
9115 retval |= w32_key_to_modifier (VK_SCROLL);
9117 /* Just in case someone wanted the original behavior, make it
9118 optional by setting w32-capslock-is-shiftlock to t. */
9119 if (NILP (Vw32_capslock_is_shiftlock)
9120 /* Keys that should _not_ be affected by CapsLock. */
9121 && ( (key == VK_BACK)
9122 || (key == VK_TAB)
9123 || (key == VK_CLEAR)
9124 || (key == VK_RETURN)
9125 || (key == VK_ESCAPE)
9126 || ((key >= VK_SPACE) && (key <= VK_HELP))
9127 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
9128 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
9131 /* Only consider shift state. */
9132 if ((mods & SHIFT_PRESSED) != 0)
9133 retval |= shift_modifier;
9135 else
9137 /* Ignore CapsLock state if not enabled. */
9138 if (NILP (Vw32_enable_caps_lock))
9139 mods &= ~CAPSLOCK_ON;
9140 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
9141 retval |= shift_modifier;
9144 return retval;
9147 /* The return code indicates key code size. cpID is the codepage to
9148 use for translation to Unicode; -1 means use the current console
9149 input codepage. */
9151 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
9153 unsigned int key_code = event->wVirtualKeyCode;
9154 unsigned int mods = event->dwControlKeyState;
9155 BYTE keystate[256];
9156 static BYTE ansi_code[4];
9157 static int isdead = 0;
9159 if (isdead == 2)
9161 event->uChar.AsciiChar = ansi_code[2];
9162 isdead = 0;
9163 return 1;
9165 if (event->uChar.AsciiChar != 0)
9166 return 1;
9168 memset (keystate, 0, sizeof (keystate));
9169 keystate[key_code] = 0x80;
9170 if (mods & SHIFT_PRESSED)
9171 keystate[VK_SHIFT] = 0x80;
9172 if (mods & CAPSLOCK_ON)
9173 keystate[VK_CAPITAL] = 1;
9174 /* If we recognize right-alt and left-ctrl as AltGr, set the key
9175 states accordingly before invoking ToAscii. */
9176 if (!NILP (Vw32_recognize_altgr)
9177 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
9179 keystate[VK_CONTROL] = 0x80;
9180 keystate[VK_LCONTROL] = 0x80;
9181 keystate[VK_MENU] = 0x80;
9182 keystate[VK_RMENU] = 0x80;
9185 #if 0
9186 /* Because of an OS bug, ToAscii corrupts the stack when called to
9187 convert a dead key in console mode on NT4. Unfortunately, trying
9188 to check for dead keys using MapVirtualKey doesn't work either -
9189 these functions apparently use internal information about keyboard
9190 layout which doesn't get properly updated in console programs when
9191 changing layout (though apparently it gets partly updated,
9192 otherwise ToAscii wouldn't crash). */
9193 if (is_dead_key (event->wVirtualKeyCode))
9194 return 0;
9195 #endif
9197 /* On NT, call ToUnicode instead and then convert to the current
9198 console input codepage. */
9199 if (os_subtype == OS_NT)
9201 WCHAR buf[128];
9203 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
9204 keystate, buf, 128, 0);
9205 if (isdead > 0)
9207 /* When we are called from the GUI message processing code,
9208 we are passed the current keyboard codepage, a positive
9209 number, to use below. */
9210 if (cpId == -1)
9211 cpId = GetConsoleCP ();
9213 event->uChar.UnicodeChar = buf[isdead - 1];
9214 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
9215 (LPSTR)ansi_code, 4, NULL, NULL);
9217 else
9218 isdead = 0;
9220 else
9222 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
9223 keystate, (LPWORD) ansi_code, 0);
9226 if (isdead == 0)
9227 return 0;
9228 event->uChar.AsciiChar = ansi_code[0];
9229 return isdead;
9233 void
9234 w32_sys_ring_bell (struct frame *f)
9236 if (sound_type == 0xFFFFFFFF)
9238 Beep (666, 100);
9240 else if (sound_type == MB_EMACS_SILENT)
9242 /* Do nothing. */
9244 else
9245 MessageBeep (sound_type);
9248 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
9249 0, 0, 0,
9250 doc: /* Return non-nil when a menu-bar menu is being used.
9251 Internal use only. */)
9252 (void)
9254 return menubar_in_use ? Qt : Qnil;
9257 #if defined WINDOWSNT && !defined HAVE_DBUS
9259 /***********************************************************************
9260 Tray notifications
9261 ***********************************************************************/
9262 /* A private struct declaration to avoid compile-time limits. */
9263 typedef struct MY_NOTIFYICONDATAW {
9264 DWORD cbSize;
9265 HWND hWnd;
9266 UINT uID;
9267 UINT uFlags;
9268 UINT uCallbackMessage;
9269 HICON hIcon;
9270 WCHAR szTip[128];
9271 DWORD dwState;
9272 DWORD dwStateMask;
9273 WCHAR szInfo[256];
9274 _ANONYMOUS_UNION union {
9275 UINT uTimeout;
9276 UINT uVersion;
9277 } DUMMYUNIONNAME;
9278 WCHAR szInfoTitle[64];
9279 DWORD dwInfoFlags;
9280 GUID guidItem;
9281 HICON hBalloonIcon;
9282 } MY_NOTIFYICONDATAW;
9284 #define MYNOTIFYICONDATAW_V1_SIZE offsetof (MY_NOTIFYICONDATAW, szTip[64])
9285 #define MYNOTIFYICONDATAW_V2_SIZE offsetof (MY_NOTIFYICONDATAW, guidItem)
9286 #define MYNOTIFYICONDATAW_V3_SIZE offsetof (MY_NOTIFYICONDATAW, hBalloonIcon)
9287 #ifndef NIF_INFO
9288 # define NIF_INFO 0x00000010
9289 #endif
9290 #ifndef NIIF_NONE
9291 # define NIIF_NONE 0x00000000
9292 #endif
9293 #ifndef NIIF_INFO
9294 # define NIIF_INFO 0x00000001
9295 #endif
9296 #ifndef NIIF_WARNING
9297 # define NIIF_WARNING 0x00000002
9298 #endif
9299 #ifndef NIIF_ERROR
9300 # define NIIF_ERROR 0x00000003
9301 #endif
9304 #define EMACS_TRAY_NOTIFICATION_ID 42 /* arbitrary */
9305 #define EMACS_NOTIFICATION_MSG (WM_APP + 1)
9307 enum NI_Severity {
9308 Ni_None,
9309 Ni_Info,
9310 Ni_Warn,
9311 Ni_Err
9314 /* Report the version of a DLL given by its name. The return value is
9315 constructed using MAKEDLLVERULL. */
9316 static ULONGLONG
9317 get_dll_version (const char *dll_name)
9319 ULONGLONG version = 0;
9320 HINSTANCE hdll = LoadLibrary (dll_name);
9322 if (hdll)
9324 DLLGETVERSIONPROC pDllGetVersion
9325 = (DLLGETVERSIONPROC) GetProcAddress (hdll, "DllGetVersion");
9327 if (pDllGetVersion)
9329 DLLVERSIONINFO dvi;
9330 HRESULT result;
9332 memset (&dvi, 0, sizeof(dvi));
9333 dvi.cbSize = sizeof(dvi);
9334 result = pDllGetVersion (&dvi);
9335 if (SUCCEEDED (result))
9336 version = MAKEDLLVERULL (dvi.dwMajorVersion, dvi.dwMinorVersion,
9337 0, 0);
9339 FreeLibrary (hdll);
9342 return version;
9345 /* Return the number of bytes in UTF-8 encoded string STR that
9346 corresponds to at most LIM characters. If STR ends before LIM
9347 characters, return the number of bytes in STR including the
9348 terminating null byte. */
9349 static int
9350 utf8_mbslen_lim (const char *str, int lim)
9352 const char *p = str;
9353 int mblen = 0, nchars = 0;
9355 while (*p && nchars < lim)
9357 int nbytes = CHAR_BYTES (*p);
9359 mblen += nbytes;
9360 nchars++;
9361 p += nbytes;
9364 if (!*p && nchars < lim)
9365 mblen++;
9367 return mblen;
9370 /* Low-level subroutine to show tray notifications. All strings are
9371 supposed to be unibyte UTF-8 encoded by the caller. */
9372 static EMACS_INT
9373 add_tray_notification (struct frame *f, const char *icon, const char *tip,
9374 enum NI_Severity severity, unsigned timeout,
9375 const char *title, const char *msg)
9377 EMACS_INT retval = EMACS_TRAY_NOTIFICATION_ID;
9379 if (FRAME_W32_P (f))
9381 MY_NOTIFYICONDATAW nidw;
9382 ULONGLONG shell_dll_version = get_dll_version ("Shell32.dll");
9383 wchar_t tipw[128], msgw[256], titlew[64];
9384 int tiplen;
9386 memset (&nidw, 0, sizeof(nidw));
9388 /* MSDN says the full struct is supported since Vista, whose
9389 Shell32.dll version is said to be 6.0.6. But DllGetVersion
9390 cannot report the 3rd field value, it reports "build number"
9391 instead, which is something else. So we use the Windows 7's
9392 version 6.1 as cutoff, and Vista loses. (Actually, the loss
9393 is not a real one, since we don't expose the hBalloonIcon
9394 member of the struct to Lisp.) */
9395 if (shell_dll_version >= MAKEDLLVERULL (6, 1, 0, 0)) /* >= Windows 7 */
9396 nidw.cbSize = sizeof (nidw);
9397 else if (shell_dll_version >= MAKEDLLVERULL (6, 0, 0, 0)) /* XP */
9398 nidw.cbSize = MYNOTIFYICONDATAW_V3_SIZE;
9399 else if (shell_dll_version >= MAKEDLLVERULL (5, 0, 0, 0)) /* W2K */
9400 nidw.cbSize = MYNOTIFYICONDATAW_V2_SIZE;
9401 else
9402 nidw.cbSize = MYNOTIFYICONDATAW_V1_SIZE; /* < W2K */
9403 nidw.hWnd = FRAME_W32_WINDOW (f);
9404 nidw.uID = EMACS_TRAY_NOTIFICATION_ID;
9405 nidw.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_INFO;
9406 nidw.uCallbackMessage = EMACS_NOTIFICATION_MSG;
9407 if (!*icon)
9408 nidw.hIcon = LoadIcon (hinst, EMACS_CLASS);
9409 else
9411 if (w32_unicode_filenames)
9413 wchar_t icon_w[MAX_PATH];
9415 if (filename_to_utf16 (icon, icon_w) != 0)
9417 errno = ENOENT;
9418 return -1;
9420 nidw.hIcon = LoadImageW (NULL, icon_w, IMAGE_ICON, 0, 0,
9421 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9423 else
9425 char icon_a[MAX_PATH];
9427 if (filename_to_ansi (icon, icon_a) != 0)
9429 errno = ENOENT;
9430 return -1;
9432 nidw.hIcon = LoadImageA (NULL, icon_a, IMAGE_ICON, 0, 0,
9433 LR_DEFAULTSIZE | LR_LOADFROMFILE);
9436 if (!nidw.hIcon)
9438 switch (GetLastError ())
9440 case ERROR_FILE_NOT_FOUND:
9441 errno = ENOENT;
9442 break;
9443 default:
9444 errno = ENOMEM;
9445 break;
9447 return -1;
9450 /* Windows 9X and NT4 support only 64 characters in the Tip,
9451 later versions support up to 128. */
9452 if (nidw.cbSize == MYNOTIFYICONDATAW_V1_SIZE)
9454 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9455 tip, utf8_mbslen_lim (tip, 63),
9456 tipw, 64);
9457 if (tiplen >= 63)
9458 tipw[63] = 0;
9460 else
9462 tiplen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9463 tip, utf8_mbslen_lim (tip, 127),
9464 tipw, 128);
9465 if (tiplen >= 127)
9466 tipw[127] = 0;
9468 if (tiplen == 0)
9470 errno = EINVAL;
9471 retval = -1;
9472 goto done;
9474 wcscpy (nidw.szTip, tipw);
9476 /* The rest of the structure is only supported since Windows 2000. */
9477 if (nidw.cbSize > MYNOTIFYICONDATAW_V1_SIZE)
9479 int slen;
9481 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9482 msg, utf8_mbslen_lim (msg, 255),
9483 msgw, 256);
9484 if (slen >= 255)
9485 msgw[255] = 0;
9486 else if (slen == 0)
9488 errno = EINVAL;
9489 retval = -1;
9490 goto done;
9492 wcscpy (nidw.szInfo, msgw);
9493 nidw.uTimeout = timeout;
9494 slen = pMultiByteToWideChar (CP_UTF8, multiByteToWideCharFlags,
9495 title, utf8_mbslen_lim (title, 63),
9496 titlew, 64);
9497 if (slen >= 63)
9498 titlew[63] = 0;
9499 else if (slen == 0)
9501 errno = EINVAL;
9502 retval = -1;
9503 goto done;
9505 wcscpy (nidw.szInfoTitle, titlew);
9507 switch (severity)
9509 case Ni_None:
9510 nidw.dwInfoFlags = NIIF_NONE;
9511 break;
9512 case Ni_Info:
9513 default:
9514 nidw.dwInfoFlags = NIIF_INFO;
9515 break;
9516 case Ni_Warn:
9517 nidw.dwInfoFlags = NIIF_WARNING;
9518 break;
9519 case Ni_Err:
9520 nidw.dwInfoFlags = NIIF_ERROR;
9521 break;
9525 if (!Shell_NotifyIconW (NIM_ADD, (PNOTIFYICONDATAW)&nidw))
9527 /* GetLastError returns meaningless results when
9528 Shell_NotifyIcon fails. */
9529 DebPrint (("Shell_NotifyIcon ADD failed (err=%d)\n",
9530 GetLastError ()));
9531 errno = EINVAL;
9532 retval = -1;
9534 done:
9535 if (*icon && !DestroyIcon (nidw.hIcon))
9536 DebPrint (("DestroyIcon failed (err=%d)\n", GetLastError ()));
9538 return retval;
9541 /* Low-level subroutine to remove a tray notification. Note: we only
9542 pass the minimum data about the notification: its ID and the handle
9543 of the window to which it sends messages. MSDN doesn't say this is
9544 enough, but it works in practice. This allows us to avoid keeping
9545 the notification data around after we show the notification. */
9546 static void
9547 delete_tray_notification (struct frame *f, int id)
9549 if (FRAME_W32_P (f))
9551 MY_NOTIFYICONDATAW nidw;
9553 memset (&nidw, 0, sizeof(nidw));
9554 nidw.hWnd = FRAME_W32_WINDOW (f);
9555 nidw.uID = id;
9557 if (!Shell_NotifyIconW (NIM_DELETE, (PNOTIFYICONDATAW)&nidw))
9559 /* GetLastError returns meaningless results when
9560 Shell_NotifyIcon fails. */
9561 DebPrint (("Shell_NotifyIcon DELETE failed\n"));
9562 errno = EINVAL;
9563 return;
9566 return;
9569 DEFUN ("w32-notification-notify",
9570 Fw32_notification_notify, Sw32_notification_notify,
9571 0, MANY, 0,
9572 doc: /* Display an MS-Windows tray notification as specified by PARAMS.
9574 Value is the integer unique ID of the notification that can be used
9575 to remove the notification using `w32-notification-close', which see.
9576 If the function fails, the return value is nil.
9578 Tray notifications, a.k.a. \"taskbar messages\", are messages that
9579 inform the user about events unrelated to the current user activity,
9580 such as a significant system event, by briefly displaying informative
9581 text in a balloon from an icon in the notification area of the taskbar.
9583 Parameters in PARAMS are specified as keyword/value pairs. All the
9584 parameters are optional, but if no parameters are specified, the
9585 function will do nothing and return nil.
9587 The following parameters are supported:
9589 :icon ICON -- Display ICON in the system tray. If ICON is a string,
9590 it should specify a file name from which to load the
9591 icon; the specified file should be a .ico Windows icon
9592 file. If ICON is not a string, or if this parameter
9593 is not specified, the standard Emacs icon will be used.
9595 :tip TIP -- Use TIP as the tooltip for the notification. If TIP
9596 is a string, this is the text of a tooltip that will
9597 be shown when the mouse pointer hovers over the tray
9598 icon added by the notification. If TIP is not a
9599 string, or if this parameter is not specified, the
9600 default tooltip text is \"Emacs notification\". The
9601 tooltip text can be up to 127 characters long (63
9602 on Windows versions before W2K). Longer strings
9603 will be truncated.
9605 :level LEVEL -- Notification severity level, one of `info',
9606 `warning', or `error'. If given, the value
9607 determines the icon displayed to the left of the
9608 notification title, but only if the `:title'
9609 parameter (see below) is also specified and is a
9610 string.
9612 :title TITLE -- The title of the notification. If TITLE is a string,
9613 it is displayed in a larger font immediately above
9614 the body text. The title text can be up to 63
9615 characters long; longer text will be truncated.
9617 :body BODY -- The body of the notification. If BODY is a string,
9618 it specifies the text of the notification message.
9619 Use embedded newlines to control how the text is
9620 broken into lines. The body text can be up to 255
9621 characters long, and will be truncated if it's longer.
9623 Note that versions of Windows before W2K support only `:icon' and `:tip'.
9624 You can pass the other parameters, but they will be ignored on those
9625 old systems.
9627 There can be at most one active notification at any given time. An
9628 active notification must be removed by calling `w32-notification-close'
9629 before a new one can be shown.
9631 usage: (w32-notification-notify &rest PARAMS) */)
9632 (ptrdiff_t nargs, Lisp_Object *args)
9634 struct frame *f = SELECTED_FRAME ();
9635 Lisp_Object arg_plist, lres;
9636 EMACS_INT retval;
9637 char *icon, *tip, *title, *msg;
9638 enum NI_Severity severity;
9639 unsigned timeout = 0;
9641 if (nargs == 0)
9642 return Qnil;
9644 arg_plist = Flist (nargs, args);
9646 /* Icon. */
9647 lres = Fplist_get (arg_plist, QCicon);
9648 if (STRINGP (lres))
9649 icon = SSDATA (ENCODE_FILE (Fexpand_file_name (lres, Qnil)));
9650 else
9651 icon = (char *)"";
9653 /* Tip. */
9654 lres = Fplist_get (arg_plist, QCtip);
9655 if (STRINGP (lres))
9656 tip = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9657 else
9658 tip = (char *)"Emacs notification";
9660 /* Severity. */
9661 lres = Fplist_get (arg_plist, QClevel);
9662 if (NILP (lres))
9663 severity = Ni_None;
9664 else if (EQ (lres, Qinfo))
9665 severity = Ni_Info;
9666 else if (EQ (lres, Qwarning))
9667 severity = Ni_Warn;
9668 else if (EQ (lres, Qerror))
9669 severity = Ni_Err;
9670 else
9671 severity = Ni_Info;
9673 /* Title. */
9674 lres = Fplist_get (arg_plist, QCtitle);
9675 if (STRINGP (lres))
9676 title = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9677 else
9678 title = (char *)"";
9680 /* Notification body text. */
9681 lres = Fplist_get (arg_plist, QCbody);
9682 if (STRINGP (lres))
9683 msg = SSDATA (code_convert_string_norecord (lres, Qutf_8, 1));
9684 else
9685 msg = (char *)"";
9687 /* Do it! */
9688 retval = add_tray_notification (f, icon, tip, severity, timeout, title, msg);
9689 return (retval < 0 ? Qnil : make_number (retval));
9692 DEFUN ("w32-notification-close",
9693 Fw32_notification_close, Sw32_notification_close,
9694 1, 1, 0,
9695 doc: /* Remove the MS-Windows tray notification specified by its ID. */)
9696 (Lisp_Object id)
9698 struct frame *f = SELECTED_FRAME ();
9700 if (INTEGERP (id))
9701 delete_tray_notification (f, XINT (id));
9703 return Qnil;
9706 #endif /* WINDOWSNT && !HAVE_DBUS */
9709 /***********************************************************************
9710 Initialization
9711 ***********************************************************************/
9713 /* Keep this list in the same order as frame_parms in frame.c.
9714 Use 0 for unsupported frame parameters. */
9716 frame_parm_handler w32_frame_parm_handlers[] =
9718 x_set_autoraise,
9719 x_set_autolower,
9720 x_set_background_color,
9721 x_set_border_color,
9722 x_set_border_width,
9723 x_set_cursor_color,
9724 x_set_cursor_type,
9725 x_set_font,
9726 x_set_foreground_color,
9727 x_set_icon_name,
9728 x_set_icon_type,
9729 x_set_internal_border_width,
9730 x_set_right_divider_width,
9731 x_set_bottom_divider_width,
9732 x_set_menu_bar_lines,
9733 x_set_mouse_color,
9734 x_explicitly_set_name,
9735 x_set_scroll_bar_width,
9736 x_set_scroll_bar_height,
9737 x_set_title,
9738 x_set_unsplittable,
9739 x_set_vertical_scroll_bars,
9740 x_set_horizontal_scroll_bars,
9741 x_set_visibility,
9742 x_set_tool_bar_lines,
9743 0, /* x_set_scroll_bar_foreground, */
9744 0, /* x_set_scroll_bar_background, */
9745 x_set_screen_gamma,
9746 x_set_line_spacing,
9747 x_set_left_fringe,
9748 x_set_right_fringe,
9749 0, /* x_set_wait_for_wm, */
9750 x_set_fullscreen,
9751 x_set_font_backend,
9752 x_set_alpha,
9753 0, /* x_set_sticky */
9754 0, /* x_set_tool_bar_position */
9755 0, /* x_set_inhibit_double_buffering */
9758 void
9759 syms_of_w32fns (void)
9761 globals_of_w32fns ();
9762 track_mouse_window = NULL;
9764 w32_visible_system_caret_hwnd = NULL;
9766 DEFSYM (Qundefined_color, "undefined-color");
9767 DEFSYM (Qcancel_timer, "cancel-timer");
9768 DEFSYM (Qhyper, "hyper");
9769 DEFSYM (Qsuper, "super");
9770 DEFSYM (Qmeta, "meta");
9771 DEFSYM (Qalt, "alt");
9772 DEFSYM (Qctrl, "ctrl");
9773 DEFSYM (Qcontrol, "control");
9774 DEFSYM (Qshift, "shift");
9775 DEFSYM (Qfont_parameter, "font-parameter");
9776 DEFSYM (Qgeometry, "geometry");
9777 DEFSYM (Qworkarea, "workarea");
9778 DEFSYM (Qmm_size, "mm-size");
9779 DEFSYM (Qframes, "frames");
9780 DEFSYM (Qtip_frame, "tip-frame");
9781 DEFSYM (Qassq_delete_all, "assq-delete-all");
9782 DEFSYM (Qunicode_sip, "unicode-sip");
9783 #if defined WINDOWSNT && !defined HAVE_DBUS
9784 DEFSYM (QCicon, ":icon");
9785 DEFSYM (QCtip, ":tip");
9786 DEFSYM (QClevel, ":level");
9787 DEFSYM (Qinfo, "info");
9788 DEFSYM (Qwarning, "warning");
9789 DEFSYM (QCtitle, ":title");
9790 DEFSYM (QCbody, ":body");
9791 #endif
9793 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
9794 DEFSYM (Qgnutls, "gnutls");
9795 DEFSYM (Qlibxml2, "libxml2");
9796 DEFSYM (Qserif, "serif");
9797 DEFSYM (Qzlib, "zlib");
9799 Fput (Qundefined_color, Qerror_conditions,
9800 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
9801 Fput (Qundefined_color, Qerror_message,
9802 build_pure_c_string ("Undefined color"));
9804 staticpro (&w32_grabbed_keys);
9805 w32_grabbed_keys = Qnil;
9807 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
9808 doc: /* An array of color name mappings for Windows. */);
9809 Vw32_color_map = Qnil;
9811 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
9812 doc: /* Non-nil if Alt key presses are passed on to Windows.
9813 When non-nil, for example, Alt pressed and released and then space will
9814 open the System menu. When nil, Emacs processes the Alt key events, and
9815 then silently swallows them. */);
9816 Vw32_pass_alt_to_system = Qnil;
9818 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
9819 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
9820 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
9821 Vw32_alt_is_meta = Qt;
9823 DEFVAR_INT ("w32-quit-key", w32_quit_key,
9824 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
9825 w32_quit_key = 0;
9827 DEFVAR_LISP ("w32-pass-lwindow-to-system",
9828 Vw32_pass_lwindow_to_system,
9829 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
9831 When non-nil, the Start menu is opened by tapping the key.
9832 If you set this to nil, the left \"Windows\" key is processed by Emacs
9833 according to the value of `w32-lwindow-modifier', which see.
9835 Note that some combinations of the left \"Windows\" key with other
9836 keys are caught by Windows at low level. For example, <lwindow>-r
9837 pops up the Windows Run dialog, <lwindow>-<Pause> pops up the "System
9838 Properties" dialog, etc. On Windows 10, no \"Windows\" key
9839 combinations are normally handed to applications. To enable Emacs to
9840 process \"Windows\" key combinations, use the function
9841 `w32-register-hot-key`.
9843 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
9844 Vw32_pass_lwindow_to_system = Qt;
9846 DEFVAR_LISP ("w32-pass-rwindow-to-system",
9847 Vw32_pass_rwindow_to_system,
9848 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
9850 When non-nil, the Start menu is opened by tapping the key.
9851 If you set this to nil, the right \"Windows\" key is processed by Emacs
9852 according to the value of `w32-rwindow-modifier', which see.
9854 Note that some combinations of the right \"Windows\" key with other
9855 keys are caught by Windows at low level. For example, <rwindow>-r
9856 pops up the Windows Run dialog, <rwindow>-<Pause> pops up the "System
9857 Properties" dialog, etc. On Windows 10, no \"Windows\" key
9858 combinations are normally handed to applications. To enable Emacs to
9859 process \"Windows\" key combinations, use the function
9860 `w32-register-hot-key`.
9862 For Windows 98/ME, see the doc string of `w32-phantom-key-code'. */);
9863 Vw32_pass_rwindow_to_system = Qt;
9865 DEFVAR_LISP ("w32-phantom-key-code",
9866 Vw32_phantom_key_code,
9867 doc: /* Virtual key code used to generate \"phantom\" key presses.
9868 Value is a number between 0 and 255.
9870 Phantom key presses are generated in order to stop the system from
9871 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
9872 `w32-pass-rwindow-to-system' is nil.
9874 This variable is only used on Windows 98 and ME. For other Windows
9875 versions, see the documentation of the `w32-register-hot-key`
9876 function. */);
9877 /* Although 255 is technically not a valid key code, it works and
9878 means that this hack won't interfere with any real key code. */
9879 XSETINT (Vw32_phantom_key_code, 255);
9881 DEFVAR_LISP ("w32-enable-num-lock",
9882 Vw32_enable_num_lock,
9883 doc: /* If non-nil, the Num Lock key acts normally.
9884 Set to nil to handle Num Lock as the `kp-numlock' key. */);
9885 Vw32_enable_num_lock = Qt;
9887 DEFVAR_LISP ("w32-enable-caps-lock",
9888 Vw32_enable_caps_lock,
9889 doc: /* If non-nil, the Caps Lock key acts normally.
9890 Set to nil to handle Caps Lock as the `capslock' key. */);
9891 Vw32_enable_caps_lock = Qt;
9893 DEFVAR_LISP ("w32-scroll-lock-modifier",
9894 Vw32_scroll_lock_modifier,
9895 doc: /* Modifier to use for the Scroll Lock ON state.
9896 The value can be hyper, super, meta, alt, control or shift for the
9897 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
9898 Any other value will cause the Scroll Lock key to be ignored by Emacs,
9899 and it will have the same effect as in other applications. */);
9900 Vw32_scroll_lock_modifier = Qnil;
9902 DEFVAR_LISP ("w32-lwindow-modifier",
9903 Vw32_lwindow_modifier,
9904 doc: /* Modifier to use for the left \"Windows\" key.
9905 The value can be hyper, super, meta, alt, control or shift for the
9906 respective modifier, or nil to appear as the `lwindow' key.
9907 Any other value will cause the key to be ignored.
9909 Also see the documentation of the `w32-register-hot-key` function. */);
9910 Vw32_lwindow_modifier = Qnil;
9912 DEFVAR_LISP ("w32-rwindow-modifier",
9913 Vw32_rwindow_modifier,
9914 doc: /* Modifier to use for the right \"Windows\" key.
9915 The value can be hyper, super, meta, alt, control or shift for the
9916 respective modifier, or nil to appear as the `rwindow' key.
9917 Any other value will cause the key to be ignored.
9919 Also see the documentation of the `w32-register-hot-key` function. */);
9920 Vw32_rwindow_modifier = Qnil;
9922 DEFVAR_LISP ("w32-apps-modifier",
9923 Vw32_apps_modifier,
9924 doc: /* Modifier to use for the \"Apps\" key.
9925 The value can be hyper, super, meta, alt, control or shift for the
9926 respective modifier, or nil to appear as the `apps' key.
9927 Any other value will cause the key to be ignored. */);
9928 Vw32_apps_modifier = Qnil;
9930 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
9931 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
9932 w32_enable_synthesized_fonts = 0;
9934 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
9935 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
9936 Vw32_enable_palette = Qt;
9938 DEFVAR_INT ("w32-mouse-button-tolerance",
9939 w32_mouse_button_tolerance,
9940 doc: /* Analogue of double click interval for faking middle mouse events.
9941 The value is the minimum time in milliseconds that must elapse between
9942 left and right button down events before they are considered distinct events.
9943 If both mouse buttons are depressed within this interval, a middle mouse
9944 button down event is generated instead. */);
9945 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
9947 DEFVAR_INT ("w32-mouse-move-interval",
9948 w32_mouse_move_interval,
9949 doc: /* Minimum interval between mouse move events.
9950 The value is the minimum time in milliseconds that must elapse between
9951 successive mouse move (or scroll bar drag) events before they are
9952 reported as lisp events. */);
9953 w32_mouse_move_interval = 0;
9955 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
9956 w32_pass_extra_mouse_buttons_to_system,
9957 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
9958 Recent versions of Windows support mice with up to five buttons.
9959 Since most applications don't support these extra buttons, most mouse
9960 drivers will allow you to map them to functions at the system level.
9961 If this variable is non-nil, Emacs will pass them on, allowing the
9962 system to handle them. */);
9963 w32_pass_extra_mouse_buttons_to_system = 0;
9965 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
9966 w32_pass_multimedia_buttons_to_system,
9967 doc: /* If non-nil, media buttons are passed to Windows.
9968 Some modern keyboards contain buttons for controlling media players, web
9969 browsers and other applications. Generally these buttons are handled on a
9970 system wide basis, but by setting this to nil they are made available
9971 to Emacs for binding. Depending on your keyboard, additional keys that
9972 may be available are:
9974 browser-back, browser-forward, browser-refresh, browser-stop,
9975 browser-search, browser-favorites, browser-home,
9976 mail, mail-reply, mail-forward, mail-send,
9977 app-1, app-2,
9978 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
9979 spell-check, correction-list, toggle-dictate-command,
9980 media-next, media-previous, media-stop, media-play-pause, media-select,
9981 media-play, media-pause, media-record, media-fast-forward, media-rewind,
9982 media-channel-up, media-channel-down,
9983 volume-mute, volume-up, volume-down,
9984 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
9985 bass-down, bass-boost, bass-up, treble-down, treble-up */);
9986 w32_pass_multimedia_buttons_to_system = 1;
9988 #if 0 /* TODO: Mouse cursor customization. */
9989 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
9990 doc: /* The shape of the pointer when over text.
9991 Changing the value does not affect existing frames
9992 unless you set the mouse color. */);
9993 Vx_pointer_shape = Qnil;
9995 Vx_nontext_pointer_shape = Qnil;
9997 Vx_mode_pointer_shape = Qnil;
9999 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
10000 doc: /* The shape of the pointer when Emacs is busy.
10001 This variable takes effect when you create a new frame
10002 or when you set the mouse color. */);
10003 Vx_hourglass_pointer_shape = Qnil;
10005 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
10006 Vx_sensitive_text_pointer_shape,
10007 doc: /* The shape of the pointer when over mouse-sensitive text.
10008 This variable takes effect when you create a new frame
10009 or when you set the mouse color. */);
10010 Vx_sensitive_text_pointer_shape = Qnil;
10012 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
10013 Vx_window_horizontal_drag_shape,
10014 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
10015 This variable takes effect when you create a new frame
10016 or when you set the mouse color. */);
10017 Vx_window_horizontal_drag_shape = Qnil;
10019 DEFVAR_LISP ("x-window-vertical-drag-cursor",
10020 Vx_window_vertical_drag_shape,
10021 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
10022 This variable takes effect when you create a new frame
10023 or when you set the mouse color. */);
10024 Vx_window_vertical_drag_shape = Qnil;
10025 #endif
10027 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
10028 doc: /* A string indicating the foreground color of the cursor box. */);
10029 Vx_cursor_fore_pixel = Qnil;
10031 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
10032 doc: /* Maximum size for tooltips.
10033 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
10034 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
10036 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
10037 doc: /* Non-nil if no window manager is in use.
10038 Emacs doesn't try to figure this out; this is always nil
10039 unless you set it to something else. */);
10040 /* We don't have any way to find this out, so set it to nil
10041 and maybe the user would like to set it to t. */
10042 Vx_no_window_manager = Qnil;
10044 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
10045 Vx_pixel_size_width_font_regexp,
10046 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
10048 Since Emacs gets width of a font matching with this regexp from
10049 PIXEL_SIZE field of the name, font finding mechanism gets faster for
10050 such a font. This is especially effective for such large fonts as
10051 Chinese, Japanese, and Korean. */);
10052 Vx_pixel_size_width_font_regexp = Qnil;
10054 DEFVAR_LISP ("w32-bdf-filename-alist",
10055 Vw32_bdf_filename_alist,
10056 doc: /* List of bdf fonts and their corresponding filenames. */);
10057 Vw32_bdf_filename_alist = Qnil;
10059 DEFVAR_BOOL ("w32-strict-fontnames",
10060 w32_strict_fontnames,
10061 doc: /* Non-nil means only use fonts that are exact matches for those requested.
10062 Default is nil, which allows old fontnames that are not XLFD compliant,
10063 and allows third-party CJK display to work by specifying false charset
10064 fields to trick Emacs into translating to Big5, SJIS etc.
10065 Setting this to t will prevent wrong fonts being selected when
10066 fontsets are automatically created. */);
10067 w32_strict_fontnames = 0;
10069 DEFVAR_BOOL ("w32-strict-painting",
10070 w32_strict_painting,
10071 doc: /* Non-nil means use strict rules for repainting frames.
10072 Set this to nil to get the old behavior for repainting; this should
10073 only be necessary if the default setting causes problems. */);
10074 w32_strict_painting = 1;
10076 DEFVAR_BOOL ("w32-use-fallback-wm-chars-method",
10077 w32_use_fallback_wm_chars_method,
10078 doc: /* Non-nil means use old method of processing character keys.
10079 This is intended only for debugging of the new processing method.
10080 Default is nil.
10082 This variable has effect only on NT family of systems, not on Windows 9X. */);
10083 w32_use_fallback_wm_chars_method = 0;
10085 DEFVAR_BOOL ("w32-disable-new-uniscribe-apis",
10086 w32_disable_new_uniscribe_apis,
10087 doc: /* Non-nil means don't use new Uniscribe APIs.
10088 The new APIs are used to access OTF features supported by fonts.
10089 This is intended only for debugging of the new Uniscribe-related code.
10090 Default is nil.
10092 This variable has effect only on Windows Vista and later. */);
10093 w32_disable_new_uniscribe_apis = 0;
10095 DEFVAR_LISP ("w32-tooltip-extra-pixels",
10096 Vw32_tooltip_extra_pixels,
10097 doc: /* Number of pixels added after tooltip text.
10098 On Windows some fonts may cause the last character of a tooltip be
10099 truncated or wrapped around to the next line. Adding some extra space
10100 at the end of the toooltip works around this problem.
10102 This variable specifies the number of pixels that shall be added. The
10103 default value t means to add the width of one canonical character of the
10104 tip frame. */);
10105 Vw32_tooltip_extra_pixels = Qt;
10107 #if 0 /* TODO: Port to W32 */
10108 defsubr (&Sx_change_window_property);
10109 defsubr (&Sx_delete_window_property);
10110 defsubr (&Sx_window_property);
10111 #endif
10112 defsubr (&Sxw_display_color_p);
10113 defsubr (&Sx_display_grayscale_p);
10114 defsubr (&Sxw_color_defined_p);
10115 defsubr (&Sxw_color_values);
10116 defsubr (&Sx_server_max_request_size);
10117 defsubr (&Sx_server_vendor);
10118 defsubr (&Sx_server_version);
10119 defsubr (&Sx_display_pixel_width);
10120 defsubr (&Sx_display_pixel_height);
10121 defsubr (&Sx_display_mm_width);
10122 defsubr (&Sx_display_mm_height);
10123 defsubr (&Sx_display_screens);
10124 defsubr (&Sx_display_planes);
10125 defsubr (&Sx_display_color_cells);
10126 defsubr (&Sx_display_visual_class);
10127 defsubr (&Sx_display_backing_store);
10128 defsubr (&Sx_display_save_under);
10129 defsubr (&Sx_create_frame);
10130 defsubr (&Sx_open_connection);
10131 defsubr (&Sx_close_connection);
10132 defsubr (&Sx_display_list);
10133 defsubr (&Sw32_frame_geometry);
10134 defsubr (&Sw32_frame_edges);
10135 defsubr (&Sw32_mouse_absolute_pixel_position);
10136 defsubr (&Sw32_set_mouse_absolute_pixel_position);
10137 defsubr (&Sx_synchronize);
10139 /* W32 specific functions */
10141 defsubr (&Sw32_define_rgb_color);
10142 defsubr (&Sw32_default_color_map);
10143 defsubr (&Sw32_display_monitor_attributes_list);
10144 defsubr (&Sw32_send_sys_command);
10145 defsubr (&Sw32_shell_execute);
10146 defsubr (&Sw32_register_hot_key);
10147 defsubr (&Sw32_unregister_hot_key);
10148 defsubr (&Sw32_registered_hot_keys);
10149 defsubr (&Sw32_reconstruct_hot_key);
10150 defsubr (&Sw32_toggle_lock_key);
10151 defsubr (&Sw32_window_exists_p);
10152 defsubr (&Sw32_battery_status);
10153 defsubr (&Sw32__menu_bar_in_use);
10154 #if defined WINDOWSNT && !defined HAVE_DBUS
10155 defsubr (&Sw32_notification_notify);
10156 defsubr (&Sw32_notification_close);
10157 #endif
10159 #ifdef WINDOWSNT
10160 defsubr (&Sfile_system_info);
10161 defsubr (&Sdefault_printer_name);
10162 #endif
10164 defsubr (&Sset_message_beep);
10165 defsubr (&Sx_show_tip);
10166 defsubr (&Sx_hide_tip);
10167 tip_timer = Qnil;
10168 staticpro (&tip_timer);
10169 tip_frame = Qnil;
10170 staticpro (&tip_frame);
10172 last_show_tip_args = Qnil;
10173 staticpro (&last_show_tip_args);
10175 defsubr (&Sx_file_dialog);
10176 #ifdef WINDOWSNT
10177 defsubr (&Ssystem_move_file_to_trash);
10178 #endif
10183 /* Crashing and reporting backtrace. */
10185 #ifndef CYGWIN
10186 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
10187 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
10188 #endif
10189 static DWORD except_code;
10190 static PVOID except_addr;
10192 #ifndef CYGWIN
10194 /* Stack overflow recovery. */
10196 /* MinGW headers don't declare this (should be in malloc.h). Also,
10197 the function is not present pre-W2K, so make the call through
10198 a function pointer. */
10199 typedef int (__cdecl *_resetstkoflw_proc) (void);
10200 static _resetstkoflw_proc resetstkoflw;
10202 /* Re-establish the guard page at stack limit. This is needed because
10203 when a stack overflow is detected, Windows removes the guard bit
10204 from the guard page, so if we don't re-establish that protection,
10205 the next stack overflow will cause a crash. */
10206 void
10207 w32_reset_stack_overflow_guard (void)
10209 if (resetstkoflw == NULL)
10210 resetstkoflw =
10211 (_resetstkoflw_proc)GetProcAddress (GetModuleHandle ("msvcrt.dll"),
10212 "_resetstkoflw");
10213 /* We ignore the return value. If _resetstkoflw fails, the next
10214 stack overflow will crash the program. */
10215 if (resetstkoflw != NULL)
10216 (void)resetstkoflw ();
10219 static void
10220 stack_overflow_handler (void)
10222 /* Hard GC error may lead to stack overflow caused by
10223 too nested calls to mark_object. No way to survive. */
10224 if (gc_in_progress)
10225 terminate_due_to_signal (SIGSEGV, 40);
10226 #ifdef _WIN64
10227 /* See ms-w32.h: MinGW64's longjmp crashes if invoked in this context. */
10228 __builtin_longjmp (return_to_command_loop, 1);
10229 #else
10230 sys_longjmp (return_to_command_loop, 1);
10231 #endif
10234 /* This handler records the exception code and the address where it
10235 was triggered so that this info could be included in the backtrace.
10236 Without that, the backtrace in some cases has no information
10237 whatsoever about the offending code, and looks as if the top-level
10238 exception handler in the MinGW startup code was the one that
10239 crashed. We also recover from stack overflow, by calling our stack
10240 overflow handler that jumps back to top level. */
10241 static LONG CALLBACK
10242 my_exception_handler (EXCEPTION_POINTERS * exception_data)
10244 except_code = exception_data->ExceptionRecord->ExceptionCode;
10245 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
10247 /* If this is a stack overflow exception, attempt to recover. */
10248 if (exception_data->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW
10249 && exception_data->ExceptionRecord->NumberParameters == 2
10250 /* We can only longjmp to top level from the main thread. */
10251 && GetCurrentThreadId () == dwMainThreadId)
10253 /* Call stack_overflow_handler (). */
10254 #ifdef _WIN64
10255 exception_data->ContextRecord->Rip = (DWORD_PTR) &stack_overflow_handler;
10256 #else
10257 exception_data->ContextRecord->Eip = (DWORD_PTR) &stack_overflow_handler;
10258 #endif
10259 /* Zero this out, so the stale address of the stack overflow
10260 exception we handled is not displayed in some future
10261 unrelated crash. */
10262 except_addr = 0;
10263 return EXCEPTION_CONTINUE_EXECUTION;
10266 if (prev_exception_handler)
10267 return prev_exception_handler (exception_data);
10268 return EXCEPTION_EXECUTE_HANDLER;
10270 #endif
10272 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
10273 PULONG);
10275 #define BACKTRACE_LIMIT_MAX 62
10277 static int
10278 w32_backtrace (void **buffer, int limit)
10280 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
10281 HMODULE hm_kernel32 = NULL;
10283 if (!s_pfn_CaptureStackBackTrace)
10285 hm_kernel32 = LoadLibrary ("Kernel32.dll");
10286 s_pfn_CaptureStackBackTrace =
10287 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
10288 "RtlCaptureStackBackTrace");
10290 if (s_pfn_CaptureStackBackTrace)
10291 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
10292 buffer, NULL);
10293 return 0;
10296 void
10297 emacs_abort (void)
10299 int button;
10300 button = MessageBox (NULL,
10301 "A fatal error has occurred!\n\n"
10302 "Would you like to attach a debugger?\n\n"
10303 "Select:\n"
10304 "YES -- to debug Emacs, or\n"
10305 "NO -- to abort Emacs and produce a backtrace\n"
10306 " (emacs_backtrace.txt in current directory)."
10307 #if __GNUC__
10308 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
10309 "\"continue\" inside GDB before clicking YES.)"
10310 #endif
10311 , "Emacs Abort Dialog",
10312 MB_ICONEXCLAMATION | MB_TASKMODAL
10313 | MB_SETFOREGROUND | MB_YESNO);
10314 switch (button)
10316 case IDYES:
10317 DebugBreak ();
10318 exit (2); /* tell the compiler we will never return */
10319 case IDNO:
10320 default:
10322 void *stack[BACKTRACE_LIMIT_MAX + 1];
10323 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
10325 if (i)
10327 int errfile_fd = -1;
10328 int j;
10329 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
10330 /* The type below should really be 'void *', but
10331 INT_BUFSIZE_BOUND cannot handle that without
10332 triggering compiler warnings (under certain
10333 pedantic warning switches), it wants an
10334 integer type. */
10335 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
10336 #ifdef CYGWIN
10337 int stderr_fd = 2;
10338 #else
10339 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
10340 int stderr_fd = -1;
10342 if (errout && errout != INVALID_HANDLE_VALUE)
10343 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
10344 #endif
10346 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
10347 but not on Windows 7. addr2line doesn't mind a missing
10348 "0x", but will be confused by an extra one. */
10349 if (except_addr)
10350 sprintf (buf, "\r\nException 0x%x at this address:\r\n%p\r\n",
10351 (unsigned int) except_code, except_addr);
10352 if (stderr_fd >= 0)
10354 if (except_addr)
10355 write (stderr_fd, buf, strlen (buf));
10356 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
10358 #ifdef CYGWIN
10359 #define _open open
10360 #endif
10361 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
10362 if (errfile_fd >= 0)
10364 lseek (errfile_fd, 0L, SEEK_END);
10365 if (except_addr)
10366 write (errfile_fd, buf, strlen (buf));
10367 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
10370 for (j = 0; j < i; j++)
10372 /* stack[] gives the return addresses, whereas we want
10373 the address of the call, so decrease each address
10374 by approximate size of 1 CALL instruction. */
10375 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
10376 if (stderr_fd >= 0)
10377 write (stderr_fd, buf, strlen (buf));
10378 if (errfile_fd >= 0)
10379 write (errfile_fd, buf, strlen (buf));
10381 if (i == BACKTRACE_LIMIT_MAX)
10383 if (stderr_fd >= 0)
10384 write (stderr_fd, "...\r\n", 5);
10385 if (errfile_fd >= 0)
10386 write (errfile_fd, "...\r\n", 5);
10388 if (errfile_fd >= 0)
10389 close (errfile_fd);
10391 abort ();
10392 break;
10399 /* Initialization. */
10402 globals_of_w32fns is used to initialize those global variables that
10403 must always be initialized on startup even when the global variable
10404 initialized is non zero (see the function main in emacs.c).
10405 globals_of_w32fns is called from syms_of_w32fns when the global
10406 variable initialized is 0 and directly from main when initialized
10407 is non zero.
10409 void
10410 globals_of_w32fns (void)
10412 HMODULE user32_lib = GetModuleHandle ("user32.dll");
10414 TrackMouseEvent not available in all versions of Windows, so must load
10415 it dynamically. Do it once, here, instead of every time it is used.
10417 track_mouse_event_fn = (TrackMouseEvent_Proc)
10418 GetProcAddress (user32_lib, "TrackMouseEvent");
10420 monitor_from_point_fn = (MonitorFromPoint_Proc)
10421 GetProcAddress (user32_lib, "MonitorFromPoint");
10422 get_monitor_info_fn = (GetMonitorInfo_Proc)
10423 GetProcAddress (user32_lib, "GetMonitorInfoA");
10424 monitor_from_window_fn = (MonitorFromWindow_Proc)
10425 GetProcAddress (user32_lib, "MonitorFromWindow");
10426 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
10427 GetProcAddress (user32_lib, "EnumDisplayMonitors");
10428 get_title_bar_info_fn = (GetTitleBarInfo_Proc)
10429 GetProcAddress (user32_lib, "GetTitleBarInfo");
10432 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
10433 get_composition_string_fn = (ImmGetCompositionString_Proc)
10434 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
10435 get_ime_context_fn = (ImmGetContext_Proc)
10436 GetProcAddress (imm32_lib, "ImmGetContext");
10437 release_ime_context_fn = (ImmReleaseContext_Proc)
10438 GetProcAddress (imm32_lib, "ImmReleaseContext");
10439 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
10440 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
10443 except_code = 0;
10444 except_addr = 0;
10445 #ifndef CYGWIN
10446 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
10447 resetstkoflw = NULL;
10448 #endif
10450 DEFVAR_INT ("w32-ansi-code-page",
10451 w32_ansi_code_page,
10452 doc: /* The ANSI code page used by the system. */);
10453 w32_ansi_code_page = GetACP ();
10455 if (os_subtype == OS_NT)
10456 w32_unicode_gui = 1;
10457 else
10458 w32_unicode_gui = 0;
10460 after_deadkey = -1;
10462 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
10463 InitCommonControls ();
10465 syms_of_w32uniscribe ();
10468 #ifdef NTGUI_UNICODE
10470 Lisp_Object
10471 ntgui_encode_system (Lisp_Object str)
10473 Lisp_Object encoded;
10474 to_unicode (str, &encoded);
10475 return encoded;
10478 #endif /* NTGUI_UNICODE */