Fix handling of image cache refcounts. (Bug#20802)
[emacs.git] / src / w32fns.c
blob5f40729011e91628e430580109e1eae3299c1767
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2015 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Added by Kevin Gallo */
22 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <math.h>
29 #include <fcntl.h>
30 #include <unistd.h>
32 #include <c-ctype.h>
34 #include "lisp.h"
35 #include "w32term.h"
36 #include "frame.h"
37 #include "window.h"
38 #include "character.h"
39 #include "buffer.h"
40 #include "intervals.h"
41 #include "dispextern.h"
42 #include "keyboard.h"
43 #include "blockinput.h"
44 #include "epaths.h"
45 #include "charset.h"
46 #include "coding.h"
47 #include "ccl.h"
48 #include "fontset.h"
49 #include "systime.h"
50 #include "termhooks.h"
52 #include "w32common.h"
54 #ifdef WINDOWSNT
55 #include "w32heap.h"
56 #include <mbstring.h>
57 #endif /* WINDOWSNT */
59 #if CYGWIN
60 #include "cygw32.h"
61 #else
62 #include "w32.h"
63 #endif
65 #include "bitmaps/gray.xbm"
67 #include <commctrl.h>
68 #include <commdlg.h>
69 #include <shellapi.h>
70 #include <ctype.h>
71 #include <winspool.h>
72 #include <objbase.h>
74 #include <dlgs.h>
75 #include <imm.h>
77 #include "font.h"
78 #include "w32font.h"
80 #ifndef FOF_NO_CONNECTED_ELEMENTS
81 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
82 #endif
84 void syms_of_w32fns (void);
85 void globals_of_w32fns (void);
87 extern void free_frame_menubar (struct frame *);
88 extern int w32_console_toggle_lock_key (int, Lisp_Object);
89 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
90 extern void w32_free_menu_strings (HWND);
91 extern const char *map_w32_filename (const char *, const char **);
92 extern char * w32_strerror (int error_no);
94 #ifndef IDC_HAND
95 #define IDC_HAND MAKEINTRESOURCE(32649)
96 #endif
98 /* Prefix for system colors. */
99 #define SYSTEM_COLOR_PREFIX "System"
100 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
102 /* State variables for emulating a three button mouse. */
103 #define LMOUSE 1
104 #define MMOUSE 2
105 #define RMOUSE 4
107 static int button_state = 0;
108 static W32Msg saved_mouse_button_msg;
109 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
110 static W32Msg saved_mouse_move_msg;
111 static unsigned mouse_move_timer = 0;
113 /* Window that is tracking the mouse. */
114 static HWND track_mouse_window;
116 /* Multi-monitor API definitions that are not pulled from the headers
117 since we are compiling for NT 4. */
118 #ifndef MONITOR_DEFAULT_TO_NEAREST
119 #define MONITOR_DEFAULT_TO_NEAREST 2
120 #endif
121 #ifndef MONITORINFOF_PRIMARY
122 #define MONITORINFOF_PRIMARY 1
123 #endif
124 #ifndef SM_XVIRTUALSCREEN
125 #define SM_XVIRTUALSCREEN 76
126 #endif
127 #ifndef SM_YVIRTUALSCREEN
128 #define SM_YVIRTUALSCREEN 77
129 #endif
130 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
131 To avoid a compile error on one or the other, redefine with a new name. */
132 struct MONITOR_INFO
134 DWORD cbSize;
135 RECT rcMonitor;
136 RECT rcWork;
137 DWORD dwFlags;
140 #ifndef CCHDEVICENAME
141 #define CCHDEVICENAME 32
142 #endif
143 struct MONITOR_INFO_EX
145 DWORD cbSize;
146 RECT rcMonitor;
147 RECT rcWork;
148 DWORD dwFlags;
149 char szDevice[CCHDEVICENAME];
152 /* Reportedly, MSVC does not have this in its headers. */
153 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
154 DECLARE_HANDLE(HMONITOR);
155 #endif
157 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
158 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
159 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
160 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
161 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
162 typedef BOOL (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
163 typedef BOOL (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
164 IN COMPOSITIONFORM *form);
165 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
166 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
167 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
168 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
169 (IN HWND hwnd, IN DWORD dwFlags);
170 typedef BOOL CALLBACK (* MonitorEnum_Proc)
171 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
172 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
173 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
175 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
176 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
177 ImmGetContext_Proc get_ime_context_fn = NULL;
178 ImmReleaseContext_Proc release_ime_context_fn = NULL;
179 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
180 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
181 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
182 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
183 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
185 #ifdef NTGUI_UNICODE
186 #define unicode_append_menu AppendMenuW
187 #else /* !NTGUI_UNICODE */
188 extern AppendMenuW_Proc unicode_append_menu;
189 #endif /* NTGUI_UNICODE */
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 extern HMENU current_popup_menu;
217 int menubar_in_use = 0;
219 /* From w32uniscribe.c */
220 extern void syms_of_w32uniscribe (void);
221 extern int uniscribe_available;
223 #ifdef WINDOWSNT
224 /* From w32inevt.c */
225 extern int faked_key;
226 #endif /* WINDOWSNT */
228 /* This gives us the page size and the size of the allocation unit on NT. */
229 SYSTEM_INFO sysinfo_cache;
231 /* This gives us version, build, and platform identification. */
232 OSVERSIONINFO osinfo_cache;
234 DWORD_PTR syspage_mask = 0;
236 /* The major and minor versions of NT. */
237 int w32_major_version;
238 int w32_minor_version;
239 int w32_build_number;
241 /* Distinguish between Windows NT and Windows 95. */
242 int os_subtype;
244 #ifdef HAVE_NTGUI
245 HINSTANCE hinst = NULL;
246 #endif
248 static unsigned int sound_type = 0xFFFFFFFF;
249 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
251 /* Let the user specify a display with a frame.
252 nil stands for the selected frame--or, if that is not a w32 frame,
253 the first display on the list. */
255 struct w32_display_info *
256 check_x_display_info (Lisp_Object object)
258 if (NILP (object))
260 struct frame *sf = XFRAME (selected_frame);
262 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
263 return FRAME_DISPLAY_INFO (sf);
264 else
265 return &one_w32_display_info;
267 else if (TERMINALP (object))
269 struct terminal *t = decode_live_terminal (object);
271 if (t->type != output_w32)
272 error ("Terminal %d is not a W32 display", t->id);
274 return t->display_info.w32;
276 else if (STRINGP (object))
277 return x_display_info_for_name (object);
278 else
280 struct frame *f;
282 CHECK_LIVE_FRAME (object);
283 f = XFRAME (object);
284 if (! FRAME_W32_P (f))
285 error ("Non-W32 frame used");
286 return FRAME_DISPLAY_INFO (f);
290 /* Return the Emacs frame-object corresponding to an w32 window.
291 It could be the frame's main window or an icon window. */
293 struct frame *
294 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
296 Lisp_Object tail, frame;
297 struct frame *f;
299 FOR_EACH_FRAME (tail, frame)
301 f = XFRAME (frame);
302 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
303 continue;
305 if (FRAME_W32_WINDOW (f) == wdesc)
306 return f;
308 return 0;
312 static Lisp_Object unwind_create_frame (Lisp_Object);
313 static void unwind_create_tip_frame (Lisp_Object);
314 static void my_create_window (struct frame *);
315 static void my_create_tip_window (struct frame *);
317 /* TODO: Native Input Method support; see x_create_im. */
318 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
319 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
320 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
321 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
322 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
323 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
324 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
325 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
326 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
327 void x_set_menu_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
328 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
329 void x_set_tool_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
330 void x_set_internal_border_width (struct frame *f, Lisp_Object, Lisp_Object);
333 /* Store the screen positions of frame F into XPTR and YPTR.
334 These are the positions of the containing window manager window,
335 not Emacs's own window. */
337 void
338 x_real_positions (struct frame *f, int *xptr, int *yptr)
340 POINT pt;
341 RECT rect;
343 /* Get the bounds of the WM window. */
344 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
346 pt.x = 0;
347 pt.y = 0;
349 /* Convert (0, 0) in the client area to screen co-ordinates. */
350 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
352 *xptr = rect.left;
353 *yptr = rect.top;
356 /* Returns the window rectangle appropriate for the given fullscreen mode.
357 The normal rect parameter was the window's rectangle prior to entering
358 fullscreen mode. If multiple monitor support is available, the nearest
359 monitor to the window is chosen. */
361 void
362 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
364 struct MONITOR_INFO mi = { sizeof(mi) };
365 if (monitor_from_window_fn && get_monitor_info_fn)
367 HMONITOR monitor =
368 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
369 get_monitor_info_fn (monitor, &mi);
371 else
373 mi.rcMonitor.left = 0;
374 mi.rcMonitor.top = 0;
375 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
376 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
377 mi.rcWork.left = 0;
378 mi.rcWork.top = 0;
379 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
380 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
383 switch (fsmode)
385 case FULLSCREEN_BOTH:
386 rect->left = mi.rcMonitor.left;
387 rect->top = mi.rcMonitor.top;
388 rect->right = mi.rcMonitor.right;
389 rect->bottom = mi.rcMonitor.bottom;
390 break;
391 case FULLSCREEN_WIDTH:
392 rect->left = mi.rcWork.left;
393 rect->top = normal.top;
394 rect->right = mi.rcWork.right;
395 rect->bottom = normal.bottom;
396 break;
397 case FULLSCREEN_HEIGHT:
398 rect->left = normal.left;
399 rect->top = mi.rcWork.top;
400 rect->right = normal.right;
401 rect->bottom = mi.rcWork.bottom;
402 break;
403 default:
404 *rect = normal;
405 break;
411 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
412 Sw32_define_rgb_color, 4, 4, 0,
413 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
414 This adds or updates a named color to `w32-color-map', making it
415 available for use. The original entry's RGB ref is returned, or nil
416 if the entry is new. */)
417 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
419 Lisp_Object rgb;
420 Lisp_Object oldrgb = Qnil;
421 Lisp_Object entry;
423 CHECK_NUMBER (red);
424 CHECK_NUMBER (green);
425 CHECK_NUMBER (blue);
426 CHECK_STRING (name);
428 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
430 block_input ();
432 /* replace existing entry in w32-color-map or add new entry. */
433 entry = Fassoc (name, Vw32_color_map);
434 if (NILP (entry))
436 entry = Fcons (name, rgb);
437 Vw32_color_map = Fcons (entry, Vw32_color_map);
439 else
441 oldrgb = Fcdr (entry);
442 Fsetcdr (entry, rgb);
445 unblock_input ();
447 return (oldrgb);
450 /* The default colors for the w32 color map */
451 typedef struct colormap_t
453 char *name;
454 COLORREF colorref;
455 } colormap_t;
457 colormap_t w32_color_map[] =
459 {"snow" , PALETTERGB (255,250,250)},
460 {"ghost white" , PALETTERGB (248,248,255)},
461 {"GhostWhite" , PALETTERGB (248,248,255)},
462 {"white smoke" , PALETTERGB (245,245,245)},
463 {"WhiteSmoke" , PALETTERGB (245,245,245)},
464 {"gainsboro" , PALETTERGB (220,220,220)},
465 {"floral white" , PALETTERGB (255,250,240)},
466 {"FloralWhite" , PALETTERGB (255,250,240)},
467 {"old lace" , PALETTERGB (253,245,230)},
468 {"OldLace" , PALETTERGB (253,245,230)},
469 {"linen" , PALETTERGB (250,240,230)},
470 {"antique white" , PALETTERGB (250,235,215)},
471 {"AntiqueWhite" , PALETTERGB (250,235,215)},
472 {"papaya whip" , PALETTERGB (255,239,213)},
473 {"PapayaWhip" , PALETTERGB (255,239,213)},
474 {"blanched almond" , PALETTERGB (255,235,205)},
475 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
476 {"bisque" , PALETTERGB (255,228,196)},
477 {"peach puff" , PALETTERGB (255,218,185)},
478 {"PeachPuff" , PALETTERGB (255,218,185)},
479 {"navajo white" , PALETTERGB (255,222,173)},
480 {"NavajoWhite" , PALETTERGB (255,222,173)},
481 {"moccasin" , PALETTERGB (255,228,181)},
482 {"cornsilk" , PALETTERGB (255,248,220)},
483 {"ivory" , PALETTERGB (255,255,240)},
484 {"lemon chiffon" , PALETTERGB (255,250,205)},
485 {"LemonChiffon" , PALETTERGB (255,250,205)},
486 {"seashell" , PALETTERGB (255,245,238)},
487 {"honeydew" , PALETTERGB (240,255,240)},
488 {"mint cream" , PALETTERGB (245,255,250)},
489 {"MintCream" , PALETTERGB (245,255,250)},
490 {"azure" , PALETTERGB (240,255,255)},
491 {"alice blue" , PALETTERGB (240,248,255)},
492 {"AliceBlue" , PALETTERGB (240,248,255)},
493 {"lavender" , PALETTERGB (230,230,250)},
494 {"lavender blush" , PALETTERGB (255,240,245)},
495 {"LavenderBlush" , PALETTERGB (255,240,245)},
496 {"misty rose" , PALETTERGB (255,228,225)},
497 {"MistyRose" , PALETTERGB (255,228,225)},
498 {"white" , PALETTERGB (255,255,255)},
499 {"black" , PALETTERGB ( 0, 0, 0)},
500 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
501 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
502 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
503 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
504 {"dim gray" , PALETTERGB (105,105,105)},
505 {"DimGray" , PALETTERGB (105,105,105)},
506 {"dim grey" , PALETTERGB (105,105,105)},
507 {"DimGrey" , PALETTERGB (105,105,105)},
508 {"slate gray" , PALETTERGB (112,128,144)},
509 {"SlateGray" , PALETTERGB (112,128,144)},
510 {"slate grey" , PALETTERGB (112,128,144)},
511 {"SlateGrey" , PALETTERGB (112,128,144)},
512 {"light slate gray" , PALETTERGB (119,136,153)},
513 {"LightSlateGray" , PALETTERGB (119,136,153)},
514 {"light slate grey" , PALETTERGB (119,136,153)},
515 {"LightSlateGrey" , PALETTERGB (119,136,153)},
516 {"gray" , PALETTERGB (190,190,190)},
517 {"grey" , PALETTERGB (190,190,190)},
518 {"light grey" , PALETTERGB (211,211,211)},
519 {"LightGrey" , PALETTERGB (211,211,211)},
520 {"light gray" , PALETTERGB (211,211,211)},
521 {"LightGray" , PALETTERGB (211,211,211)},
522 {"midnight blue" , PALETTERGB ( 25, 25,112)},
523 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
524 {"navy" , PALETTERGB ( 0, 0,128)},
525 {"navy blue" , PALETTERGB ( 0, 0,128)},
526 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
527 {"cornflower blue" , PALETTERGB (100,149,237)},
528 {"CornflowerBlue" , PALETTERGB (100,149,237)},
529 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
530 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
531 {"slate blue" , PALETTERGB (106, 90,205)},
532 {"SlateBlue" , PALETTERGB (106, 90,205)},
533 {"medium slate blue" , PALETTERGB (123,104,238)},
534 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
535 {"light slate blue" , PALETTERGB (132,112,255)},
536 {"LightSlateBlue" , PALETTERGB (132,112,255)},
537 {"medium blue" , PALETTERGB ( 0, 0,205)},
538 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
539 {"royal blue" , PALETTERGB ( 65,105,225)},
540 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
541 {"blue" , PALETTERGB ( 0, 0,255)},
542 {"dodger blue" , PALETTERGB ( 30,144,255)},
543 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
544 {"deep sky blue" , PALETTERGB ( 0,191,255)},
545 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
546 {"sky blue" , PALETTERGB (135,206,235)},
547 {"SkyBlue" , PALETTERGB (135,206,235)},
548 {"light sky blue" , PALETTERGB (135,206,250)},
549 {"LightSkyBlue" , PALETTERGB (135,206,250)},
550 {"steel blue" , PALETTERGB ( 70,130,180)},
551 {"SteelBlue" , PALETTERGB ( 70,130,180)},
552 {"light steel blue" , PALETTERGB (176,196,222)},
553 {"LightSteelBlue" , PALETTERGB (176,196,222)},
554 {"light blue" , PALETTERGB (173,216,230)},
555 {"LightBlue" , PALETTERGB (173,216,230)},
556 {"powder blue" , PALETTERGB (176,224,230)},
557 {"PowderBlue" , PALETTERGB (176,224,230)},
558 {"pale turquoise" , PALETTERGB (175,238,238)},
559 {"PaleTurquoise" , PALETTERGB (175,238,238)},
560 {"dark turquoise" , PALETTERGB ( 0,206,209)},
561 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
562 {"medium turquoise" , PALETTERGB ( 72,209,204)},
563 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
564 {"turquoise" , PALETTERGB ( 64,224,208)},
565 {"cyan" , PALETTERGB ( 0,255,255)},
566 {"light cyan" , PALETTERGB (224,255,255)},
567 {"LightCyan" , PALETTERGB (224,255,255)},
568 {"cadet blue" , PALETTERGB ( 95,158,160)},
569 {"CadetBlue" , PALETTERGB ( 95,158,160)},
570 {"medium aquamarine" , PALETTERGB (102,205,170)},
571 {"MediumAquamarine" , PALETTERGB (102,205,170)},
572 {"aquamarine" , PALETTERGB (127,255,212)},
573 {"dark green" , PALETTERGB ( 0,100, 0)},
574 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
575 {"dark olive green" , PALETTERGB ( 85,107, 47)},
576 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
577 {"dark sea green" , PALETTERGB (143,188,143)},
578 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
579 {"sea green" , PALETTERGB ( 46,139, 87)},
580 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
581 {"medium sea green" , PALETTERGB ( 60,179,113)},
582 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
583 {"light sea green" , PALETTERGB ( 32,178,170)},
584 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
585 {"pale green" , PALETTERGB (152,251,152)},
586 {"PaleGreen" , PALETTERGB (152,251,152)},
587 {"spring green" , PALETTERGB ( 0,255,127)},
588 {"SpringGreen" , PALETTERGB ( 0,255,127)},
589 {"lawn green" , PALETTERGB (124,252, 0)},
590 {"LawnGreen" , PALETTERGB (124,252, 0)},
591 {"green" , PALETTERGB ( 0,255, 0)},
592 {"chartreuse" , PALETTERGB (127,255, 0)},
593 {"medium spring green" , PALETTERGB ( 0,250,154)},
594 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
595 {"green yellow" , PALETTERGB (173,255, 47)},
596 {"GreenYellow" , PALETTERGB (173,255, 47)},
597 {"lime green" , PALETTERGB ( 50,205, 50)},
598 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
599 {"yellow green" , PALETTERGB (154,205, 50)},
600 {"YellowGreen" , PALETTERGB (154,205, 50)},
601 {"forest green" , PALETTERGB ( 34,139, 34)},
602 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
603 {"olive drab" , PALETTERGB (107,142, 35)},
604 {"OliveDrab" , PALETTERGB (107,142, 35)},
605 {"dark khaki" , PALETTERGB (189,183,107)},
606 {"DarkKhaki" , PALETTERGB (189,183,107)},
607 {"khaki" , PALETTERGB (240,230,140)},
608 {"pale goldenrod" , PALETTERGB (238,232,170)},
609 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
610 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
611 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
612 {"light yellow" , PALETTERGB (255,255,224)},
613 {"LightYellow" , PALETTERGB (255,255,224)},
614 {"yellow" , PALETTERGB (255,255, 0)},
615 {"gold" , PALETTERGB (255,215, 0)},
616 {"light goldenrod" , PALETTERGB (238,221,130)},
617 {"LightGoldenrod" , PALETTERGB (238,221,130)},
618 {"goldenrod" , PALETTERGB (218,165, 32)},
619 {"dark goldenrod" , PALETTERGB (184,134, 11)},
620 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
621 {"rosy brown" , PALETTERGB (188,143,143)},
622 {"RosyBrown" , PALETTERGB (188,143,143)},
623 {"indian red" , PALETTERGB (205, 92, 92)},
624 {"IndianRed" , PALETTERGB (205, 92, 92)},
625 {"saddle brown" , PALETTERGB (139, 69, 19)},
626 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
627 {"sienna" , PALETTERGB (160, 82, 45)},
628 {"peru" , PALETTERGB (205,133, 63)},
629 {"burlywood" , PALETTERGB (222,184,135)},
630 {"beige" , PALETTERGB (245,245,220)},
631 {"wheat" , PALETTERGB (245,222,179)},
632 {"sandy brown" , PALETTERGB (244,164, 96)},
633 {"SandyBrown" , PALETTERGB (244,164, 96)},
634 {"tan" , PALETTERGB (210,180,140)},
635 {"chocolate" , PALETTERGB (210,105, 30)},
636 {"firebrick" , PALETTERGB (178,34, 34)},
637 {"brown" , PALETTERGB (165,42, 42)},
638 {"dark salmon" , PALETTERGB (233,150,122)},
639 {"DarkSalmon" , PALETTERGB (233,150,122)},
640 {"salmon" , PALETTERGB (250,128,114)},
641 {"light salmon" , PALETTERGB (255,160,122)},
642 {"LightSalmon" , PALETTERGB (255,160,122)},
643 {"orange" , PALETTERGB (255,165, 0)},
644 {"dark orange" , PALETTERGB (255,140, 0)},
645 {"DarkOrange" , PALETTERGB (255,140, 0)},
646 {"coral" , PALETTERGB (255,127, 80)},
647 {"light coral" , PALETTERGB (240,128,128)},
648 {"LightCoral" , PALETTERGB (240,128,128)},
649 {"tomato" , PALETTERGB (255, 99, 71)},
650 {"orange red" , PALETTERGB (255, 69, 0)},
651 {"OrangeRed" , PALETTERGB (255, 69, 0)},
652 {"red" , PALETTERGB (255, 0, 0)},
653 {"hot pink" , PALETTERGB (255,105,180)},
654 {"HotPink" , PALETTERGB (255,105,180)},
655 {"deep pink" , PALETTERGB (255, 20,147)},
656 {"DeepPink" , PALETTERGB (255, 20,147)},
657 {"pink" , PALETTERGB (255,192,203)},
658 {"light pink" , PALETTERGB (255,182,193)},
659 {"LightPink" , PALETTERGB (255,182,193)},
660 {"pale violet red" , PALETTERGB (219,112,147)},
661 {"PaleVioletRed" , PALETTERGB (219,112,147)},
662 {"maroon" , PALETTERGB (176, 48, 96)},
663 {"medium violet red" , PALETTERGB (199, 21,133)},
664 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
665 {"violet red" , PALETTERGB (208, 32,144)},
666 {"VioletRed" , PALETTERGB (208, 32,144)},
667 {"magenta" , PALETTERGB (255, 0,255)},
668 {"violet" , PALETTERGB (238,130,238)},
669 {"plum" , PALETTERGB (221,160,221)},
670 {"orchid" , PALETTERGB (218,112,214)},
671 {"medium orchid" , PALETTERGB (186, 85,211)},
672 {"MediumOrchid" , PALETTERGB (186, 85,211)},
673 {"dark orchid" , PALETTERGB (153, 50,204)},
674 {"DarkOrchid" , PALETTERGB (153, 50,204)},
675 {"dark violet" , PALETTERGB (148, 0,211)},
676 {"DarkViolet" , PALETTERGB (148, 0,211)},
677 {"blue violet" , PALETTERGB (138, 43,226)},
678 {"BlueViolet" , PALETTERGB (138, 43,226)},
679 {"purple" , PALETTERGB (160, 32,240)},
680 {"medium purple" , PALETTERGB (147,112,219)},
681 {"MediumPurple" , PALETTERGB (147,112,219)},
682 {"thistle" , PALETTERGB (216,191,216)},
683 {"gray0" , PALETTERGB ( 0, 0, 0)},
684 {"grey0" , PALETTERGB ( 0, 0, 0)},
685 {"dark grey" , PALETTERGB (169,169,169)},
686 {"DarkGrey" , PALETTERGB (169,169,169)},
687 {"dark gray" , PALETTERGB (169,169,169)},
688 {"DarkGray" , PALETTERGB (169,169,169)},
689 {"dark blue" , PALETTERGB ( 0, 0,139)},
690 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
691 {"dark cyan" , PALETTERGB ( 0,139,139)},
692 {"DarkCyan" , PALETTERGB ( 0,139,139)},
693 {"dark magenta" , PALETTERGB (139, 0,139)},
694 {"DarkMagenta" , PALETTERGB (139, 0,139)},
695 {"dark red" , PALETTERGB (139, 0, 0)},
696 {"DarkRed" , PALETTERGB (139, 0, 0)},
697 {"light green" , PALETTERGB (144,238,144)},
698 {"LightGreen" , PALETTERGB (144,238,144)},
701 static Lisp_Object
702 w32_default_color_map (void)
704 int i;
705 colormap_t *pc = w32_color_map;
706 Lisp_Object cmap;
708 block_input ();
710 cmap = Qnil;
712 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
713 cmap = Fcons (Fcons (build_string (pc->name),
714 make_number (pc->colorref)),
715 cmap);
717 unblock_input ();
719 return (cmap);
722 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
723 0, 0, 0, doc: /* Return the default color map. */)
724 (void)
726 return w32_default_color_map ();
729 static Lisp_Object
730 w32_color_map_lookup (const char *colorname)
732 Lisp_Object tail, ret = Qnil;
734 block_input ();
736 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
738 register Lisp_Object elt, tem;
740 elt = XCAR (tail);
741 if (!CONSP (elt)) continue;
743 tem = XCAR (elt);
745 if (lstrcmpi (SDATA (tem), colorname) == 0)
747 ret = Fcdr (elt);
748 break;
751 QUIT;
754 unblock_input ();
756 return ret;
760 static void
761 add_system_logical_colors_to_map (Lisp_Object *system_colors)
763 HKEY colors_key;
765 /* Other registry operations are done with input blocked. */
766 block_input ();
768 /* Look for "Control Panel/Colors" under User and Machine registry
769 settings. */
770 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
771 KEY_READ, &colors_key) == ERROR_SUCCESS
772 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
773 KEY_READ, &colors_key) == ERROR_SUCCESS)
775 /* List all keys. */
776 char color_buffer[64];
777 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
778 int index = 0;
779 DWORD name_size, color_size;
780 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
782 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
783 color_size = sizeof (color_buffer);
785 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
787 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
788 NULL, NULL, color_buffer, &color_size)
789 == ERROR_SUCCESS)
791 int r, g, b;
792 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
793 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
794 make_number (RGB (r, g, b))),
795 *system_colors);
797 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
798 color_size = sizeof (color_buffer);
799 index++;
801 RegCloseKey (colors_key);
804 unblock_input ();
808 static Lisp_Object
809 x_to_w32_color (const char * colorname)
811 register Lisp_Object ret = Qnil;
813 block_input ();
815 if (colorname[0] == '#')
817 /* Could be an old-style RGB Device specification. */
818 int size = strlen (colorname + 1);
819 char *color = alloca (size + 1);
821 strcpy (color, colorname + 1);
822 if (size == 3 || size == 6 || size == 9 || size == 12)
824 UINT colorval;
825 int i, pos;
826 pos = 0;
827 size /= 3;
828 colorval = 0;
830 for (i = 0; i < 3; i++)
832 char *end;
833 char t;
834 unsigned long value;
836 /* The check for 'x' in the following conditional takes into
837 account the fact that strtol allows a "0x" in front of
838 our numbers, and we don't. */
839 if (!isxdigit (color[0]) || color[1] == 'x')
840 break;
841 t = color[size];
842 color[size] = '\0';
843 value = strtoul (color, &end, 16);
844 color[size] = t;
845 if (errno == ERANGE || end - color != size)
846 break;
847 switch (size)
849 case 1:
850 value = value * 0x10;
851 break;
852 case 2:
853 break;
854 case 3:
855 value /= 0x10;
856 break;
857 case 4:
858 value /= 0x100;
859 break;
861 colorval |= (value << pos);
862 pos += 0x8;
863 if (i == 2)
865 unblock_input ();
866 XSETINT (ret, colorval);
867 return ret;
869 color = end;
873 else if (strnicmp (colorname, "rgb:", 4) == 0)
875 const char *color;
876 UINT colorval;
877 int i, pos;
878 pos = 0;
880 colorval = 0;
881 color = colorname + 4;
882 for (i = 0; i < 3; i++)
884 char *end;
885 unsigned long value;
887 /* The check for 'x' in the following conditional takes into
888 account the fact that strtol allows a "0x" in front of
889 our numbers, and we don't. */
890 if (!isxdigit (color[0]) || color[1] == 'x')
891 break;
892 value = strtoul (color, &end, 16);
893 if (errno == ERANGE)
894 break;
895 switch (end - color)
897 case 1:
898 value = value * 0x10 + value;
899 break;
900 case 2:
901 break;
902 case 3:
903 value /= 0x10;
904 break;
905 case 4:
906 value /= 0x100;
907 break;
908 default:
909 value = ULONG_MAX;
911 if (value == ULONG_MAX)
912 break;
913 colorval |= (value << pos);
914 pos += 0x8;
915 if (i == 2)
917 if (*end != '\0')
918 break;
919 unblock_input ();
920 XSETINT (ret, colorval);
921 return ret;
923 if (*end != '/')
924 break;
925 color = end + 1;
928 else if (strnicmp (colorname, "rgbi:", 5) == 0)
930 /* This is an RGB Intensity specification. */
931 const char *color;
932 UINT colorval;
933 int i, pos;
934 pos = 0;
936 colorval = 0;
937 color = colorname + 5;
938 for (i = 0; i < 3; i++)
940 char *end;
941 double value;
942 UINT val;
944 value = strtod (color, &end);
945 if (errno == ERANGE)
946 break;
947 if (value < 0.0 || value > 1.0)
948 break;
949 val = (UINT)(0x100 * value);
950 /* We used 0x100 instead of 0xFF to give a continuous
951 range between 0.0 and 1.0 inclusive. The next statement
952 fixes the 1.0 case. */
953 if (val == 0x100)
954 val = 0xFF;
955 colorval |= (val << pos);
956 pos += 0x8;
957 if (i == 2)
959 if (*end != '\0')
960 break;
961 unblock_input ();
962 XSETINT (ret, colorval);
963 return ret;
965 if (*end != '/')
966 break;
967 color = end + 1;
970 /* I am not going to attempt to handle any of the CIE color schemes
971 or TekHVC, since I don't know the algorithms for conversion to
972 RGB. */
974 /* If we fail to lookup the color name in w32_color_map, then check the
975 colorname to see if it can be crudely approximated: If the X color
976 ends in a number (e.g., "darkseagreen2"), strip the number and
977 return the result of looking up the base color name. */
978 ret = w32_color_map_lookup (colorname);
979 if (NILP (ret))
981 int len = strlen (colorname);
983 if (isdigit (colorname[len - 1]))
985 char *ptr, *approx = alloca (len + 1);
987 strcpy (approx, colorname);
988 ptr = &approx[len - 1];
989 while (ptr > approx && isdigit (*ptr))
990 *ptr-- = '\0';
992 ret = w32_color_map_lookup (approx);
996 unblock_input ();
997 return ret;
1000 void
1001 w32_regenerate_palette (struct frame *f)
1003 struct w32_palette_entry * list;
1004 LOGPALETTE * log_palette;
1005 HPALETTE new_palette;
1006 int i;
1008 /* don't bother trying to create palette if not supported */
1009 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1010 return;
1012 log_palette = (LOGPALETTE *)
1013 alloca (sizeof (LOGPALETTE) +
1014 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1015 log_palette->palVersion = 0x300;
1016 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1018 list = FRAME_DISPLAY_INFO (f)->color_list;
1019 for (i = 0;
1020 i < FRAME_DISPLAY_INFO (f)->num_colors;
1021 i++, list = list->next)
1022 log_palette->palPalEntry[i] = list->entry;
1024 new_palette = CreatePalette (log_palette);
1026 enter_crit ();
1028 if (FRAME_DISPLAY_INFO (f)->palette)
1029 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1030 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1032 /* Realize display palette and garbage all frames. */
1033 release_frame_dc (f, get_frame_dc (f));
1035 leave_crit ();
1038 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1039 #define SET_W32_COLOR(pe, color) \
1040 do \
1042 pe.peRed = GetRValue (color); \
1043 pe.peGreen = GetGValue (color); \
1044 pe.peBlue = GetBValue (color); \
1045 pe.peFlags = 0; \
1046 } while (0)
1048 #if 0
1049 /* Keep these around in case we ever want to track color usage. */
1050 void
1051 w32_map_color (struct frame *f, COLORREF color)
1053 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1055 if (NILP (Vw32_enable_palette))
1056 return;
1058 /* check if color is already mapped */
1059 while (list)
1061 if (W32_COLOR (list->entry) == color)
1063 ++list->refcount;
1064 return;
1066 list = list->next;
1069 /* not already mapped, so add to list and recreate Windows palette */
1070 list = xmalloc (sizeof (struct w32_palette_entry));
1071 SET_W32_COLOR (list->entry, color);
1072 list->refcount = 1;
1073 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1074 FRAME_DISPLAY_INFO (f)->color_list = list;
1075 FRAME_DISPLAY_INFO (f)->num_colors++;
1077 /* set flag that palette must be regenerated */
1078 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1081 void
1082 w32_unmap_color (struct frame *f, COLORREF color)
1084 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1085 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1087 if (NILP (Vw32_enable_palette))
1088 return;
1090 /* check if color is already mapped */
1091 while (list)
1093 if (W32_COLOR (list->entry) == color)
1095 if (--list->refcount == 0)
1097 *prev = list->next;
1098 xfree (list);
1099 FRAME_DISPLAY_INFO (f)->num_colors--;
1100 break;
1102 else
1103 return;
1105 prev = &list->next;
1106 list = list->next;
1109 /* set flag that palette must be regenerated */
1110 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1112 #endif
1115 /* Gamma-correct COLOR on frame F. */
1117 void
1118 gamma_correct (struct frame *f, COLORREF *color)
1120 if (f->gamma)
1122 *color = PALETTERGB (
1123 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1124 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1125 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1130 /* Decide if color named COLOR is valid for the display associated with
1131 the selected frame; if so, return the rgb values in COLOR_DEF.
1132 If ALLOC is nonzero, allocate a new colormap cell. */
1135 w32_defined_color (struct frame *f, const char *color, XColor *color_def,
1136 bool alloc_p)
1138 register Lisp_Object tem;
1139 COLORREF w32_color_ref;
1141 tem = x_to_w32_color (color);
1143 if (!NILP (tem))
1145 if (f)
1147 /* Apply gamma correction. */
1148 w32_color_ref = XUINT (tem);
1149 gamma_correct (f, &w32_color_ref);
1150 XSETINT (tem, w32_color_ref);
1153 /* Map this color to the palette if it is enabled. */
1154 if (!NILP (Vw32_enable_palette))
1156 struct w32_palette_entry * entry =
1157 one_w32_display_info.color_list;
1158 struct w32_palette_entry ** prev =
1159 &one_w32_display_info.color_list;
1161 /* check if color is already mapped */
1162 while (entry)
1164 if (W32_COLOR (entry->entry) == XUINT (tem))
1165 break;
1166 prev = &entry->next;
1167 entry = entry->next;
1170 if (entry == NULL && alloc_p)
1172 /* not already mapped, so add to list */
1173 entry = xmalloc (sizeof (struct w32_palette_entry));
1174 SET_W32_COLOR (entry->entry, XUINT (tem));
1175 entry->next = NULL;
1176 *prev = entry;
1177 one_w32_display_info.num_colors++;
1179 /* set flag that palette must be regenerated */
1180 one_w32_display_info.regen_palette = TRUE;
1183 /* Ensure COLORREF value is snapped to nearest color in (default)
1184 palette by simulating the PALETTERGB macro. This works whether
1185 or not the display device has a palette. */
1186 w32_color_ref = XUINT (tem) | 0x2000000;
1188 color_def->pixel = w32_color_ref;
1189 color_def->red = GetRValue (w32_color_ref) * 256;
1190 color_def->green = GetGValue (w32_color_ref) * 256;
1191 color_def->blue = GetBValue (w32_color_ref) * 256;
1193 return 1;
1195 else
1197 return 0;
1201 /* Given a string ARG naming a color, compute a pixel value from it
1202 suitable for screen F.
1203 If F is not a color screen, return DEF (default) regardless of what
1204 ARG says. */
1207 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1209 XColor cdef;
1211 CHECK_STRING (arg);
1213 if (strcmp (SDATA (arg), "black") == 0)
1214 return BLACK_PIX_DEFAULT (f);
1215 else if (strcmp (SDATA (arg), "white") == 0)
1216 return WHITE_PIX_DEFAULT (f);
1218 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1219 return def;
1221 /* w32_defined_color is responsible for coping with failures
1222 by looking for a near-miss. */
1223 if (w32_defined_color (f, SDATA (arg), &cdef, true))
1224 return cdef.pixel;
1226 /* defined_color failed; return an ultimate default. */
1227 return def;
1232 /* Functions called only from `x_set_frame_param'
1233 to set individual parameters.
1235 If FRAME_W32_WINDOW (f) is 0,
1236 the frame is being created and its window does not exist yet.
1237 In that case, just record the parameter's new value
1238 in the standard place; do not attempt to change the window. */
1240 void
1241 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1243 struct w32_output *x = f->output_data.w32;
1244 PIX_TYPE fg, old_fg;
1246 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1247 old_fg = FRAME_FOREGROUND_PIXEL (f);
1248 FRAME_FOREGROUND_PIXEL (f) = fg;
1250 if (FRAME_W32_WINDOW (f) != 0)
1252 if (x->cursor_pixel == old_fg)
1254 x->cursor_pixel = fg;
1255 x->cursor_gc->background = fg;
1258 update_face_from_frame_parameter (f, Qforeground_color, arg);
1259 if (FRAME_VISIBLE_P (f))
1260 redraw_frame (f);
1264 void
1265 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1267 FRAME_BACKGROUND_PIXEL (f)
1268 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1270 if (FRAME_W32_WINDOW (f) != 0)
1272 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1273 FRAME_BACKGROUND_PIXEL (f));
1275 update_face_from_frame_parameter (f, Qbackground_color, arg);
1277 if (FRAME_VISIBLE_P (f))
1278 redraw_frame (f);
1282 void
1283 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1285 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1286 int count;
1287 int mask_color;
1289 if (!EQ (Qnil, arg))
1290 f->output_data.w32->mouse_pixel
1291 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1292 mask_color = FRAME_BACKGROUND_PIXEL (f);
1294 /* Don't let pointers be invisible. */
1295 if (mask_color == f->output_data.w32->mouse_pixel
1296 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1297 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1299 #if 0 /* TODO : Mouse cursor customization. */
1300 block_input ();
1302 /* It's not okay to crash if the user selects a screwy cursor. */
1303 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1305 if (!EQ (Qnil, Vx_pointer_shape))
1307 CHECK_NUMBER (Vx_pointer_shape);
1308 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1310 else
1311 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1312 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1314 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1316 CHECK_NUMBER (Vx_nontext_pointer_shape);
1317 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1318 XINT (Vx_nontext_pointer_shape));
1320 else
1321 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1322 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1324 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1326 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1327 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1328 XINT (Vx_hourglass_pointer_shape));
1330 else
1331 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1332 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1334 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1335 if (!EQ (Qnil, Vx_mode_pointer_shape))
1337 CHECK_NUMBER (Vx_mode_pointer_shape);
1338 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1339 XINT (Vx_mode_pointer_shape));
1341 else
1342 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1343 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1345 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1347 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1348 hand_cursor
1349 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1350 XINT (Vx_sensitive_text_pointer_shape));
1352 else
1353 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1355 if (!NILP (Vx_window_horizontal_drag_shape))
1357 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1358 horizontal_drag_cursor
1359 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1360 XINT (Vx_window_horizontal_drag_shape));
1362 else
1363 horizontal_drag_cursor
1364 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1366 if (!NILP (Vx_window_vertical_drag_shape))
1368 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1369 vertical_drag_cursor
1370 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1371 XINT (Vx_window_vertical_drag_shape));
1373 else
1374 vertical_drag_cursor
1375 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1377 /* Check and report errors with the above calls. */
1378 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1379 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1382 XColor fore_color, back_color;
1384 fore_color.pixel = f->output_data.w32->mouse_pixel;
1385 back_color.pixel = mask_color;
1386 XQueryColor (FRAME_W32_DISPLAY (f),
1387 DefaultColormap (FRAME_W32_DISPLAY (f),
1388 DefaultScreen (FRAME_W32_DISPLAY (f))),
1389 &fore_color);
1390 XQueryColor (FRAME_W32_DISPLAY (f),
1391 DefaultColormap (FRAME_W32_DISPLAY (f),
1392 DefaultScreen (FRAME_W32_DISPLAY (f))),
1393 &back_color);
1394 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1395 &fore_color, &back_color);
1396 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1397 &fore_color, &back_color);
1398 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1399 &fore_color, &back_color);
1400 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1401 &fore_color, &back_color);
1402 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1403 &fore_color, &back_color);
1406 if (FRAME_W32_WINDOW (f) != 0)
1407 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1409 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1410 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1411 f->output_data.w32->text_cursor = cursor;
1413 if (nontext_cursor != f->output_data.w32->nontext_cursor
1414 && f->output_data.w32->nontext_cursor != 0)
1415 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1416 f->output_data.w32->nontext_cursor = nontext_cursor;
1418 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1419 && f->output_data.w32->hourglass_cursor != 0)
1420 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1421 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1423 if (mode_cursor != f->output_data.w32->modeline_cursor
1424 && f->output_data.w32->modeline_cursor != 0)
1425 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1426 f->output_data.w32->modeline_cursor = mode_cursor;
1428 if (hand_cursor != f->output_data.w32->hand_cursor
1429 && f->output_data.w32->hand_cursor != 0)
1430 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1431 f->output_data.w32->hand_cursor = hand_cursor;
1433 XFlush (FRAME_W32_DISPLAY (f));
1434 unblock_input ();
1436 update_face_from_frame_parameter (f, Qmouse_color, arg);
1437 #endif /* TODO */
1440 void
1441 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1443 unsigned long fore_pixel, pixel;
1445 if (!NILP (Vx_cursor_fore_pixel))
1446 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1447 WHITE_PIX_DEFAULT (f));
1448 else
1449 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1451 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1453 /* Make sure that the cursor color differs from the background color. */
1454 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1456 pixel = f->output_data.w32->mouse_pixel;
1457 if (pixel == fore_pixel)
1458 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1461 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1462 f->output_data.w32->cursor_pixel = pixel;
1464 if (FRAME_W32_WINDOW (f) != 0)
1466 block_input ();
1467 /* Update frame's cursor_gc. */
1468 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1469 f->output_data.w32->cursor_gc->background = pixel;
1471 unblock_input ();
1473 if (FRAME_VISIBLE_P (f))
1475 x_update_cursor (f, 0);
1476 x_update_cursor (f, 1);
1480 update_face_from_frame_parameter (f, Qcursor_color, arg);
1483 /* Set the border-color of frame F to pixel value PIX.
1484 Note that this does not fully take effect if done before
1485 F has a window. */
1487 void
1488 x_set_border_pixel (struct frame *f, int pix)
1491 f->output_data.w32->border_pixel = pix;
1493 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1495 if (FRAME_VISIBLE_P (f))
1496 redraw_frame (f);
1500 /* Set the border-color of frame F to value described by ARG.
1501 ARG can be a string naming a color.
1502 The border-color is used for the border that is drawn by the server.
1503 Note that this does not fully take effect if done before
1504 F has a window; it must be redone when the window is created. */
1506 void
1507 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1509 int pix;
1511 CHECK_STRING (arg);
1512 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1513 x_set_border_pixel (f, pix);
1514 update_face_from_frame_parameter (f, Qborder_color, arg);
1518 void
1519 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1521 set_frame_cursor_types (f, arg);
1524 void
1525 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1527 bool result;
1529 if (NILP (arg) && NILP (oldval))
1530 return;
1532 if (STRINGP (arg) && STRINGP (oldval)
1533 && EQ (Fstring_equal (oldval, arg), Qt))
1534 return;
1536 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1537 return;
1539 block_input ();
1541 result = x_bitmap_icon (f, arg);
1542 if (result)
1544 unblock_input ();
1545 error ("No icon window available");
1548 unblock_input ();
1551 void
1552 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1554 if (STRINGP (arg))
1556 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1557 return;
1559 else if (!NILP (arg) || NILP (oldval))
1560 return;
1562 fset_icon_name (f, arg);
1564 #if 0
1565 if (f->output_data.w32->icon_bitmap != 0)
1566 return;
1568 block_input ();
1570 result = x_text_icon (f,
1571 SSDATA ((!NILP (f->icon_name)
1572 ? f->icon_name
1573 : !NILP (f->title)
1574 ? f->title
1575 : f->name)));
1577 if (result)
1579 unblock_input ();
1580 error ("No icon window available");
1583 /* If the window was unmapped (and its icon was mapped),
1584 the new icon is not mapped, so map the window in its stead. */
1585 if (FRAME_VISIBLE_P (f))
1587 #ifdef USE_X_TOOLKIT
1588 XtPopup (f->output_data.w32->widget, XtGrabNone);
1589 #endif
1590 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1593 XFlush (FRAME_W32_DISPLAY (f));
1594 unblock_input ();
1595 #endif
1598 void
1599 x_clear_under_internal_border (struct frame *f)
1601 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1603 /* Clear border if it's larger than before. */
1604 if (border != 0)
1606 HDC hdc = get_frame_dc (f);
1607 int width = FRAME_PIXEL_WIDTH (f);
1608 int height = FRAME_PIXEL_HEIGHT (f);
1610 block_input ();
1611 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1612 w32_clear_area (f, hdc, 0, 0, border, height);
1613 w32_clear_area (f, hdc, width - border, 0, border, height);
1614 w32_clear_area (f, hdc, 0, height - border, width, border);
1615 release_frame_dc (f, hdc);
1616 unblock_input ();
1621 void
1622 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1624 int border;
1626 CHECK_TYPE_RANGED_INTEGER (int, arg);
1627 border = max (XINT (arg), 0);
1629 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1631 FRAME_INTERNAL_BORDER_WIDTH (f) = border;
1633 if (FRAME_X_WINDOW (f) != 0)
1635 adjust_frame_size (f, -1, -1, 3, false, Qinternal_border_width);
1637 if (FRAME_VISIBLE_P (f))
1638 x_clear_under_internal_border (f);
1644 void
1645 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1647 int nlines;
1649 /* Right now, menu bars don't work properly in minibuf-only frames;
1650 most of the commands try to apply themselves to the minibuffer
1651 frame itself, and get an error because you can't switch buffers
1652 in or split the minibuffer window. */
1653 if (FRAME_MINIBUF_ONLY_P (f))
1654 return;
1656 if (INTEGERP (value))
1657 nlines = XINT (value);
1658 else
1659 nlines = 0;
1661 FRAME_MENU_BAR_LINES (f) = 0;
1662 FRAME_MENU_BAR_HEIGHT (f) = 0;
1663 if (nlines)
1665 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1666 windows_or_buffers_changed = 23;
1668 else
1670 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1671 free_frame_menubar (f);
1672 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1674 /* Adjust the frame size so that the client (text) dimensions
1675 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1676 set correctly. Note that we resize twice: The first time upon
1677 a request from the window manager who wants to keep the height
1678 of the outer rectangle (including decorations) unchanged, and a
1679 second time because we want to keep the height of the inner
1680 rectangle (without the decorations unchanged). */
1681 adjust_frame_size (f, -1, -1, 2, true, Qmenu_bar_lines);
1683 /* Not sure whether this is needed. */
1684 x_clear_under_internal_border (f);
1689 /* Set the number of lines used for the tool bar of frame F to VALUE.
1690 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1691 the old number of tool bar lines (and is unused). This function may
1692 change the height of all windows on frame F to match the new tool bar
1693 height. By design, the frame's height doesn't change (but maybe it
1694 should if we don't get enough space otherwise). */
1696 void
1697 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1699 int nlines;
1701 /* Treat tool bars like menu bars. */
1702 if (FRAME_MINIBUF_ONLY_P (f))
1703 return;
1705 /* Use VALUE only if an integer >= 0. */
1706 if (INTEGERP (value) && XINT (value) >= 0)
1707 nlines = XFASTINT (value);
1708 else
1709 nlines = 0;
1711 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1715 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1716 void
1717 x_change_tool_bar_height (struct frame *f, int height)
1719 Lisp_Object frame;
1720 int unit = FRAME_LINE_HEIGHT (f);
1721 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1722 int lines = (height + unit - 1) / unit;
1723 int old_text_height = FRAME_TEXT_HEIGHT (f);
1724 Lisp_Object fullscreen;
1726 /* Make sure we redisplay all windows in this frame. */
1727 windows_or_buffers_changed = 23;
1729 /* Recalculate tool bar and frame text sizes. */
1730 FRAME_TOOL_BAR_HEIGHT (f) = height;
1731 FRAME_TOOL_BAR_LINES (f) = lines;
1732 /* Store `tool-bar-lines' and `height' frame parameters. */
1733 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1734 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1736 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1738 clear_frame (f);
1739 clear_current_matrices (f);
1742 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1743 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1745 /* Recalculate toolbar height. */
1746 f->n_tool_bar_rows = 0;
1748 adjust_frame_size (f, -1, -1,
1749 ((!f->tool_bar_redisplayed_once
1750 && (NILP (fullscreen =
1751 get_frame_param (f, Qfullscreen))
1752 || EQ (fullscreen, Qfullwidth))) ? 1
1753 : (old_height == 0 || height == 0) ? 2
1754 : 4),
1755 false, Qtool_bar_lines);
1757 /* adjust_frame_size might not have done anything, garbage frame
1758 here. */
1759 adjust_frame_glyphs (f);
1760 SET_FRAME_GARBAGED (f);
1761 if (FRAME_X_WINDOW (f))
1762 x_clear_under_internal_border (f);
1765 static void
1766 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1768 if (FRAME_W32_WINDOW (f))
1770 block_input ();
1771 #ifdef __CYGWIN__
1772 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1773 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1774 #else
1775 /* The frame's title many times shows the name of the file
1776 visited in the selected window's buffer, so it makes sense to
1777 support non-ASCII characters outside of the current system
1778 codepage in the title. */
1779 if (w32_unicode_filenames)
1781 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1782 wchar_t *title_w;
1783 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1784 -1, NULL, 0);
1786 if (tlen > 0)
1788 /* Windows truncates the title text beyond what fits on
1789 a single line, so we can limit the length to some
1790 reasonably large value, and use alloca. */
1791 if (tlen > 10000)
1792 tlen = 10000;
1793 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1794 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1795 title_w, tlen);
1796 title_w[tlen] = L'\0';
1797 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1799 else /* Conversion to UTF-16 failed, so we punt. */
1800 SetWindowTextA (FRAME_W32_WINDOW (f),
1801 SSDATA (ENCODE_SYSTEM (name)));
1803 else
1804 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1805 #endif
1806 unblock_input ();
1810 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1811 w32_id_name.
1813 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1814 name; if NAME is a string, set F's name to NAME and set
1815 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1817 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1818 suggesting a new name, which lisp code should override; if
1819 F->explicit_name is set, ignore the new name; otherwise, set it. */
1821 void
1822 x_set_name (struct frame *f, Lisp_Object name, bool explicit)
1824 /* Make sure that requests from lisp code override requests from
1825 Emacs redisplay code. */
1826 if (explicit)
1828 /* If we're switching from explicit to implicit, we had better
1829 update the mode lines and thereby update the title. */
1830 if (f->explicit_name && NILP (name))
1831 update_mode_lines = 25;
1833 f->explicit_name = ! NILP (name);
1835 else if (f->explicit_name)
1836 return;
1838 /* If NAME is nil, set the name to the w32_id_name. */
1839 if (NILP (name))
1841 /* Check for no change needed in this very common case
1842 before we do any consing. */
1843 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1844 SDATA (f->name)))
1845 return;
1846 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1848 else
1849 CHECK_STRING (name);
1851 /* Don't change the name if it's already NAME. */
1852 if (! NILP (Fstring_equal (name, f->name)))
1853 return;
1855 fset_name (f, name);
1857 /* For setting the frame title, the title parameter should override
1858 the name parameter. */
1859 if (! NILP (f->title))
1860 name = f->title;
1862 w32_set_title_bar_text (f, name);
1865 /* This function should be called when the user's lisp code has
1866 specified a name for the frame; the name will override any set by the
1867 redisplay code. */
1868 void
1869 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1871 x_set_name (f, arg, true);
1874 /* This function should be called by Emacs redisplay code to set the
1875 name; names set this way will never override names set by the user's
1876 lisp code. */
1877 void
1878 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1880 x_set_name (f, arg, false);
1883 /* Change the title of frame F to NAME.
1884 If NAME is nil, use the frame name as the title. */
1886 void
1887 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1889 /* Don't change the title if it's already NAME. */
1890 if (EQ (name, f->title))
1891 return;
1893 update_mode_lines = 26;
1895 fset_title (f, name);
1897 if (NILP (name))
1898 name = f->name;
1900 w32_set_title_bar_text (f, name);
1903 void
1904 x_set_scroll_bar_default_width (struct frame *f)
1906 int unit = FRAME_COLUMN_WIDTH (f);
1908 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1909 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1910 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1914 void
1915 x_set_scroll_bar_default_height (struct frame *f)
1917 int unit = FRAME_LINE_HEIGHT (f);
1919 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
1920 FRAME_CONFIG_SCROLL_BAR_LINES (f)
1921 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
1924 /* Subroutines for creating a frame. */
1926 Cursor
1927 w32_load_cursor (LPCTSTR name)
1929 /* Try first to load cursor from application resource. */
1930 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1931 name, IMAGE_CURSOR, 0, 0,
1932 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1933 if (!cursor)
1935 /* Then try to load a shared predefined cursor. */
1936 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1937 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1939 return cursor;
1942 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1944 #define INIT_WINDOW_CLASS(WC) \
1945 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1946 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1947 (WC).cbClsExtra = 0; \
1948 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1949 (WC).hInstance = hinst; \
1950 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1951 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1952 (WC).hbrBackground = NULL; \
1953 (WC).lpszMenuName = NULL; \
1955 static BOOL
1956 w32_init_class (HINSTANCE hinst)
1958 if (w32_unicode_gui)
1960 WNDCLASSW uwc;
1961 INIT_WINDOW_CLASS(uwc);
1962 uwc.lpszClassName = L"Emacs";
1964 return RegisterClassW (&uwc);
1966 else
1968 WNDCLASS wc;
1969 INIT_WINDOW_CLASS(wc);
1970 wc.lpszClassName = EMACS_CLASS;
1972 return RegisterClassA (&wc);
1976 static HWND
1977 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
1979 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1980 /* Position and size of scroll bar. */
1981 bar->left, bar->top, bar->width, bar->height,
1982 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1985 static HWND
1986 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
1988 return CreateWindow ("SCROLLBAR", "", SBS_HORZ | WS_CHILD | WS_VISIBLE,
1989 /* Position and size of scroll bar. */
1990 bar->left, bar->top, bar->width, bar->height,
1991 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1994 static void
1995 w32_createwindow (struct frame *f, int *coords)
1997 HWND hwnd;
1998 RECT rect;
1999 int top;
2000 int left;
2002 rect.left = rect.top = 0;
2003 rect.right = FRAME_PIXEL_WIDTH (f);
2004 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2006 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2007 FRAME_EXTERNAL_MENU_BAR (f));
2009 /* Do first time app init */
2011 w32_init_class (hinst);
2013 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2015 left = f->left_pos;
2016 top = f->top_pos;
2018 else
2020 left = coords[0];
2021 top = coords[1];
2024 FRAME_W32_WINDOW (f) = hwnd
2025 = CreateWindow (EMACS_CLASS,
2026 f->namebuf,
2027 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2028 left, top,
2029 rect.right - rect.left, rect.bottom - rect.top,
2030 NULL,
2031 NULL,
2032 hinst,
2033 NULL);
2035 if (hwnd)
2037 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2038 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2039 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2040 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2041 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2042 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2044 /* Enable drag-n-drop. */
2045 DragAcceptFiles (hwnd, TRUE);
2047 /* Do this to discard the default setting specified by our parent. */
2048 ShowWindow (hwnd, SW_HIDE);
2050 /* Update frame positions. */
2051 GetWindowRect (hwnd, &rect);
2052 f->left_pos = rect.left;
2053 f->top_pos = rect.top;
2057 static void
2058 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2060 wmsg->msg.hwnd = hwnd;
2061 wmsg->msg.message = msg;
2062 wmsg->msg.wParam = wParam;
2063 wmsg->msg.lParam = lParam;
2064 wmsg->msg.time = GetMessageTime ();
2066 post_msg (wmsg);
2069 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2070 between left and right keys as advertised. We test for this
2071 support dynamically, and set a flag when the support is absent. If
2072 absent, we keep track of the left and right control and alt keys
2073 ourselves. This is particularly necessary on keyboards that rely
2074 upon the AltGr key, which is represented as having the left control
2075 and right alt keys pressed. For these keyboards, we need to know
2076 when the left alt key has been pressed in addition to the AltGr key
2077 so that we can properly support M-AltGr-key sequences (such as M-@
2078 on Swedish keyboards). */
2080 #define EMACS_LCONTROL 0
2081 #define EMACS_RCONTROL 1
2082 #define EMACS_LMENU 2
2083 #define EMACS_RMENU 3
2085 static int modifiers[4];
2086 static int modifiers_recorded;
2087 static int modifier_key_support_tested;
2089 static void
2090 test_modifier_support (unsigned int wparam)
2092 unsigned int l, r;
2094 if (wparam != VK_CONTROL && wparam != VK_MENU)
2095 return;
2096 if (wparam == VK_CONTROL)
2098 l = VK_LCONTROL;
2099 r = VK_RCONTROL;
2101 else
2103 l = VK_LMENU;
2104 r = VK_RMENU;
2106 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2107 modifiers_recorded = 1;
2108 else
2109 modifiers_recorded = 0;
2110 modifier_key_support_tested = 1;
2113 static void
2114 record_keydown (unsigned int wparam, unsigned int lparam)
2116 int i;
2118 if (!modifier_key_support_tested)
2119 test_modifier_support (wparam);
2121 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2122 return;
2124 if (wparam == VK_CONTROL)
2125 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2126 else
2127 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2129 modifiers[i] = 1;
2132 static void
2133 record_keyup (unsigned int wparam, unsigned int lparam)
2135 int i;
2137 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2138 return;
2140 if (wparam == VK_CONTROL)
2141 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2142 else
2143 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2145 modifiers[i] = 0;
2148 /* Emacs can lose focus while a modifier key has been pressed. When
2149 it regains focus, be conservative and clear all modifiers since
2150 we cannot reconstruct the left and right modifier state. */
2151 static void
2152 reset_modifiers (void)
2154 SHORT ctrl, alt;
2156 if (GetFocus () == NULL)
2157 /* Emacs doesn't have keyboard focus. Do nothing. */
2158 return;
2160 ctrl = GetAsyncKeyState (VK_CONTROL);
2161 alt = GetAsyncKeyState (VK_MENU);
2163 if (!(ctrl & 0x08000))
2164 /* Clear any recorded control modifier state. */
2165 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2167 if (!(alt & 0x08000))
2168 /* Clear any recorded alt modifier state. */
2169 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2171 /* Update the state of all modifier keys, because modifiers used in
2172 hot-key combinations can get stuck on if Emacs loses focus as a
2173 result of a hot-key being pressed. */
2175 BYTE keystate[256];
2177 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2179 memset (keystate, 0, sizeof (keystate));
2180 GetKeyboardState (keystate);
2181 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2182 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2183 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2184 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2185 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2186 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2187 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2188 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2189 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2190 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2191 SetKeyboardState (keystate);
2195 /* Synchronize modifier state with what is reported with the current
2196 keystroke. Even if we cannot distinguish between left and right
2197 modifier keys, we know that, if no modifiers are set, then neither
2198 the left or right modifier should be set. */
2199 static void
2200 sync_modifiers (void)
2202 if (!modifiers_recorded)
2203 return;
2205 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2206 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2208 if (!(GetKeyState (VK_MENU) & 0x8000))
2209 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2212 static int
2213 modifier_set (int vkey)
2215 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2216 toggle keys is not an omission! If you want to add it, you will
2217 have to make changes in the default sub-case of the WM_KEYDOWN
2218 switch, because if the NUMLOCK modifier is set, the code there
2219 will directly convert any key that looks like an ASCII letter,
2220 and also downcase those that look like upper-case ASCII. */
2221 if (vkey == VK_CAPITAL)
2223 if (NILP (Vw32_enable_caps_lock))
2224 return 0;
2225 else
2226 return (GetKeyState (vkey) & 0x1);
2228 if (vkey == VK_SCROLL)
2230 if (NILP (Vw32_scroll_lock_modifier)
2231 /* w32-scroll-lock-modifier can be any non-nil value that is
2232 not one of the modifiers, in which case it shall be ignored. */
2233 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2234 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2235 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2236 || EQ (Vw32_scroll_lock_modifier, Qalt)
2237 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2238 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2239 return 0;
2240 else
2241 return (GetKeyState (vkey) & 0x1);
2244 if (!modifiers_recorded)
2245 return (GetKeyState (vkey) & 0x8000);
2247 switch (vkey)
2249 case VK_LCONTROL:
2250 return modifiers[EMACS_LCONTROL];
2251 case VK_RCONTROL:
2252 return modifiers[EMACS_RCONTROL];
2253 case VK_LMENU:
2254 return modifiers[EMACS_LMENU];
2255 case VK_RMENU:
2256 return modifiers[EMACS_RMENU];
2258 return (GetKeyState (vkey) & 0x8000);
2261 /* Convert between the modifier bits W32 uses and the modifier bits
2262 Emacs uses. */
2264 unsigned int
2265 w32_key_to_modifier (int key)
2267 Lisp_Object key_mapping;
2269 switch (key)
2271 case VK_LWIN:
2272 key_mapping = Vw32_lwindow_modifier;
2273 break;
2274 case VK_RWIN:
2275 key_mapping = Vw32_rwindow_modifier;
2276 break;
2277 case VK_APPS:
2278 key_mapping = Vw32_apps_modifier;
2279 break;
2280 case VK_SCROLL:
2281 key_mapping = Vw32_scroll_lock_modifier;
2282 break;
2283 default:
2284 key_mapping = Qnil;
2287 /* NB. This code runs in the input thread, asynchronously to the lisp
2288 thread, so we must be careful to ensure access to lisp data is
2289 thread-safe. The following code is safe because the modifier
2290 variable values are updated atomically from lisp and symbols are
2291 not relocated by GC. Also, we don't have to worry about seeing GC
2292 markbits here. */
2293 if (EQ (key_mapping, Qhyper))
2294 return hyper_modifier;
2295 if (EQ (key_mapping, Qsuper))
2296 return super_modifier;
2297 if (EQ (key_mapping, Qmeta))
2298 return meta_modifier;
2299 if (EQ (key_mapping, Qalt))
2300 return alt_modifier;
2301 if (EQ (key_mapping, Qctrl))
2302 return ctrl_modifier;
2303 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2304 return ctrl_modifier;
2305 if (EQ (key_mapping, Qshift))
2306 return shift_modifier;
2308 /* Don't generate any modifier if not explicitly requested. */
2309 return 0;
2312 static unsigned int
2313 w32_get_modifiers (void)
2315 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2316 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2317 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2318 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2319 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2320 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2321 (modifier_set (VK_MENU) ?
2322 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2325 /* We map the VK_* modifiers into console modifier constants
2326 so that we can use the same routines to handle both console
2327 and window input. */
2329 static int
2330 construct_console_modifiers (void)
2332 int mods;
2334 mods = 0;
2335 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2336 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2337 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2338 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2339 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2340 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2341 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2342 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2343 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2344 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2345 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2347 return mods;
2350 static int
2351 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2353 int mods;
2355 /* Convert to emacs modifiers. */
2356 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2358 return mods;
2361 unsigned int
2362 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2364 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2365 return virt_key;
2367 if (virt_key == VK_RETURN)
2368 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2370 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2371 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2373 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2374 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2376 if (virt_key == VK_CLEAR)
2377 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2379 return virt_key;
2382 /* List of special key combinations which w32 would normally capture,
2383 but Emacs should grab instead. Not directly visible to lisp, to
2384 simplify synchronization. Each item is an integer encoding a virtual
2385 key code and modifier combination to capture. */
2386 static Lisp_Object w32_grabbed_keys;
2388 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2389 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2390 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2391 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2393 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2394 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2395 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2397 /* Register hot-keys for reserved key combinations when Emacs has
2398 keyboard focus, since this is the only way Emacs can receive key
2399 combinations like Alt-Tab which are used by the system. */
2401 static void
2402 register_hot_keys (HWND hwnd)
2404 Lisp_Object keylist;
2406 /* Use CONSP, since we are called asynchronously. */
2407 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2409 Lisp_Object key = XCAR (keylist);
2411 /* Deleted entries get set to nil. */
2412 if (!INTEGERP (key))
2413 continue;
2415 RegisterHotKey (hwnd, HOTKEY_ID (key),
2416 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2420 static void
2421 unregister_hot_keys (HWND hwnd)
2423 Lisp_Object keylist;
2425 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2427 Lisp_Object key = XCAR (keylist);
2429 if (!INTEGERP (key))
2430 continue;
2432 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2436 #if EMACSDEBUG
2437 const char*
2438 w32_name_of_message (UINT msg)
2440 unsigned i;
2441 static char buf[64];
2442 static const struct {
2443 UINT msg;
2444 const char* name;
2445 } msgnames[] = {
2446 #define M(msg) { msg, # msg }
2447 M (WM_PAINT),
2448 M (WM_TIMER),
2449 M (WM_USER),
2450 M (WM_MOUSEMOVE),
2451 M (WM_LBUTTONUP),
2452 M (WM_KEYDOWN),
2453 M (WM_EMACS_KILL),
2454 M (WM_EMACS_CREATEWINDOW),
2455 M (WM_EMACS_DONE),
2456 M (WM_EMACS_CREATEVSCROLLBAR),
2457 M (WM_EMACS_CREATEHSCROLLBAR),
2458 M (WM_EMACS_SHOWWINDOW),
2459 M (WM_EMACS_SETWINDOWPOS),
2460 M (WM_EMACS_DESTROYWINDOW),
2461 M (WM_EMACS_TRACKPOPUPMENU),
2462 M (WM_EMACS_SETFOCUS),
2463 M (WM_EMACS_SETFOREGROUND),
2464 M (WM_EMACS_SETLOCALE),
2465 M (WM_EMACS_SETKEYBOARDLAYOUT),
2466 M (WM_EMACS_REGISTER_HOT_KEY),
2467 M (WM_EMACS_UNREGISTER_HOT_KEY),
2468 M (WM_EMACS_TOGGLE_LOCK_KEY),
2469 M (WM_EMACS_TRACK_CARET),
2470 M (WM_EMACS_DESTROY_CARET),
2471 M (WM_EMACS_SHOW_CARET),
2472 M (WM_EMACS_HIDE_CARET),
2473 M (WM_EMACS_SETCURSOR),
2474 M (WM_EMACS_SHOWCURSOR),
2475 M (WM_EMACS_PAINT),
2476 M (WM_CHAR),
2477 #undef M
2478 { 0, 0 }
2481 for (i = 0; msgnames[i].name; ++i)
2482 if (msgnames[i].msg == msg)
2483 return msgnames[i].name;
2485 sprintf (buf, "message 0x%04x", (unsigned)msg);
2486 return buf;
2488 #endif /* EMACSDEBUG */
2490 /* Here's an overview of how Emacs input works in GUI sessions on
2491 MS-Windows. (For description of non-GUI input, see the commentary
2492 before w32_console_read_socket in w32inevt.c.)
2494 System messages are read and processed by w32_msg_pump below. This
2495 function runs in a separate thread. It handles a small number of
2496 custom WM_EMACS_* messages (posted by the main thread, look for
2497 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2498 is the main window procedure for the entire Emacs application.
2500 w32_wnd_proc also runs in the same separate input thread. It
2501 handles some messages, mostly those that need GDI calls, by itself.
2502 For the others, it calls my_post_msg, which inserts the messages
2503 into the input queue serviced by w32_read_socket.
2505 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2506 called synchronously from keyboard.c when it is known or suspected
2507 that some input is available. w32_read_socket either handles
2508 messages immediately, or converts them into Emacs input events and
2509 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2510 them and process them when read_char and its callers require
2511 input.
2513 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2514 select(2) takes the place of w32_read_socket.
2518 /* Main message dispatch loop. */
2520 static void
2521 w32_msg_pump (deferred_msg * msg_buf)
2523 MSG msg;
2524 WPARAM result;
2525 HWND focus_window;
2527 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2529 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2532 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2533 /* w32_name_of_message (msg.message), msg.time)); */
2535 if (msg.hwnd == NULL)
2537 switch (msg.message)
2539 case WM_NULL:
2540 /* Produced by complete_deferred_msg; just ignore. */
2541 break;
2542 case WM_EMACS_CREATEWINDOW:
2543 /* Initialize COM for this window. Even though we don't use it,
2544 some third party shell extensions can cause it to be used in
2545 system dialogs, which causes a crash if it is not initialized.
2546 This is a known bug in Windows, which was fixed long ago, but
2547 the patch for XP is not publicly available until XP SP3,
2548 and older versions will never be patched. */
2549 CoInitialize (NULL);
2550 w32_createwindow ((struct frame *) msg.wParam,
2551 (int *) msg.lParam);
2552 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2553 emacs_abort ();
2554 break;
2555 case WM_EMACS_SETLOCALE:
2556 SetThreadLocale (msg.wParam);
2557 /* Reply is not expected. */
2558 break;
2559 case WM_EMACS_SETKEYBOARDLAYOUT:
2560 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2561 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2562 result, 0))
2563 emacs_abort ();
2564 break;
2565 case WM_EMACS_REGISTER_HOT_KEY:
2566 focus_window = GetFocus ();
2567 if (focus_window != NULL)
2568 RegisterHotKey (focus_window,
2569 RAW_HOTKEY_ID (msg.wParam),
2570 RAW_HOTKEY_MODIFIERS (msg.wParam),
2571 RAW_HOTKEY_VK_CODE (msg.wParam));
2572 /* Reply is not expected. */
2573 break;
2574 case WM_EMACS_UNREGISTER_HOT_KEY:
2575 focus_window = GetFocus ();
2576 if (focus_window != NULL)
2577 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2578 /* Mark item as erased. NB: this code must be
2579 thread-safe. The next line is okay because the cons
2580 cell is never made into garbage and is not relocated by
2581 GC. */
2582 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
2583 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2584 emacs_abort ();
2585 break;
2586 case WM_EMACS_TOGGLE_LOCK_KEY:
2588 int vk_code = (int) msg.wParam;
2589 int cur_state = (GetKeyState (vk_code) & 1);
2590 int new_state = msg.lParam;
2592 if (new_state == -1
2593 || ((new_state & 1) != cur_state))
2595 one_w32_display_info.faked_key = vk_code;
2597 keybd_event ((BYTE) vk_code,
2598 (BYTE) MapVirtualKey (vk_code, 0),
2599 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2600 keybd_event ((BYTE) vk_code,
2601 (BYTE) MapVirtualKey (vk_code, 0),
2602 KEYEVENTF_EXTENDEDKEY | 0, 0);
2603 keybd_event ((BYTE) vk_code,
2604 (BYTE) MapVirtualKey (vk_code, 0),
2605 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2606 cur_state = !cur_state;
2608 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2609 cur_state, 0))
2610 emacs_abort ();
2612 break;
2613 #ifdef MSG_DEBUG
2614 /* Broadcast messages make it here, so you need to be looking
2615 for something in particular for this to be useful. */
2616 default:
2617 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2618 #endif
2621 else
2623 if (w32_unicode_gui)
2624 DispatchMessageW (&msg);
2625 else
2626 DispatchMessageA (&msg);
2629 /* Exit nested loop when our deferred message has completed. */
2630 if (msg_buf->completed)
2631 break;
2635 deferred_msg * deferred_msg_head;
2637 static deferred_msg *
2638 find_deferred_msg (HWND hwnd, UINT msg)
2640 deferred_msg * item;
2642 /* Don't actually need synchronization for read access, since
2643 modification of single pointer is always atomic. */
2644 /* enter_crit (); */
2646 for (item = deferred_msg_head; item != NULL; item = item->next)
2647 if (item->w32msg.msg.hwnd == hwnd
2648 && item->w32msg.msg.message == msg)
2649 break;
2651 /* leave_crit (); */
2653 return item;
2656 static LRESULT
2657 send_deferred_msg (deferred_msg * msg_buf,
2658 HWND hwnd,
2659 UINT msg,
2660 WPARAM wParam,
2661 LPARAM lParam)
2663 /* Only input thread can send deferred messages. */
2664 if (GetCurrentThreadId () != dwWindowsThreadId)
2665 emacs_abort ();
2667 /* It is an error to send a message that is already deferred. */
2668 if (find_deferred_msg (hwnd, msg) != NULL)
2669 emacs_abort ();
2671 /* Enforced synchronization is not needed because this is the only
2672 function that alters deferred_msg_head, and the following critical
2673 section is guaranteed to only be serially reentered (since only the
2674 input thread can call us). */
2676 /* enter_crit (); */
2678 msg_buf->completed = 0;
2679 msg_buf->next = deferred_msg_head;
2680 deferred_msg_head = msg_buf;
2681 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2683 /* leave_crit (); */
2685 /* Start a new nested message loop to process other messages until
2686 this one is completed. */
2687 w32_msg_pump (msg_buf);
2689 deferred_msg_head = msg_buf->next;
2691 return msg_buf->result;
2694 void
2695 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2697 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2699 if (msg_buf == NULL)
2700 /* Message may have been canceled, so don't abort. */
2701 return;
2703 msg_buf->result = result;
2704 msg_buf->completed = 1;
2706 /* Ensure input thread is woken so it notices the completion. */
2707 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2710 static void
2711 cancel_all_deferred_msgs (void)
2713 deferred_msg * item;
2715 /* Don't actually need synchronization for read access, since
2716 modification of single pointer is always atomic. */
2717 /* enter_crit (); */
2719 for (item = deferred_msg_head; item != NULL; item = item->next)
2721 item->result = 0;
2722 item->completed = 1;
2725 /* leave_crit (); */
2727 /* Ensure input thread is woken so it notices the completion. */
2728 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2731 DWORD WINAPI
2732 w32_msg_worker (void *arg)
2734 MSG msg;
2735 deferred_msg dummy_buf;
2737 /* Ensure our message queue is created */
2739 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2741 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2742 emacs_abort ();
2744 memset (&dummy_buf, 0, sizeof (dummy_buf));
2745 dummy_buf.w32msg.msg.hwnd = NULL;
2746 dummy_buf.w32msg.msg.message = WM_NULL;
2748 /* This is the initial message loop which should only exit when the
2749 application quits. */
2750 w32_msg_pump (&dummy_buf);
2752 return 0;
2755 static void
2756 signal_user_input (void)
2758 /* Interrupt any lisp that wants to be interrupted by input. */
2759 if (!NILP (Vthrow_on_input))
2761 Vquit_flag = Vthrow_on_input;
2762 /* Doing a QUIT from this thread is a bad idea, since this
2763 unwinds the stack of the Lisp thread, and the Windows runtime
2764 rightfully barfs. Disabled. */
2765 #if 0
2766 /* If we're inside a function that wants immediate quits,
2767 do it now. */
2768 if (immediate_quit && NILP (Vinhibit_quit))
2770 immediate_quit = 0;
2771 QUIT;
2773 #endif
2778 static void
2779 post_character_message (HWND hwnd, UINT msg,
2780 WPARAM wParam, LPARAM lParam,
2781 DWORD modifiers)
2783 W32Msg wmsg;
2785 wmsg.dwModifiers = modifiers;
2787 /* Detect quit_char and set quit-flag directly. Note that we
2788 still need to post a message to ensure the main thread will be
2789 woken up if blocked in sys_select, but we do NOT want to post
2790 the quit_char message itself (because it will usually be as if
2791 the user had typed quit_char twice). Instead, we post a dummy
2792 message that has no particular effect. */
2794 int c = wParam;
2795 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2796 c = make_ctrl_char (c) & 0377;
2797 if (c == quit_char
2798 || (wmsg.dwModifiers == 0
2799 && w32_quit_key && wParam == w32_quit_key))
2801 Vquit_flag = Qt;
2803 /* The choice of message is somewhat arbitrary, as long as
2804 the main thread handler just ignores it. */
2805 msg = WM_NULL;
2807 /* Interrupt any blocking system calls. */
2808 signal_quit ();
2810 /* As a safety precaution, forcibly complete any deferred
2811 messages. This is a kludge, but I don't see any particularly
2812 clean way to handle the situation where a deferred message is
2813 "dropped" in the lisp thread, and will thus never be
2814 completed, eg. by the user trying to activate the menubar
2815 when the lisp thread is busy, and then typing C-g when the
2816 menubar doesn't open promptly (with the result that the
2817 menubar never responds at all because the deferred
2818 WM_INITMENU message is never completed). Another problem
2819 situation is when the lisp thread calls SendMessage (to send
2820 a window manager command) when a message has been deferred;
2821 the lisp thread gets blocked indefinitely waiting for the
2822 deferred message to be completed, which itself is waiting for
2823 the lisp thread to respond.
2825 Note that we don't want to block the input thread waiting for
2826 a response from the lisp thread (although that would at least
2827 solve the deadlock problem above), because we want to be able
2828 to receive C-g to interrupt the lisp thread. */
2829 cancel_all_deferred_msgs ();
2831 else
2832 signal_user_input ();
2835 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2838 /* Main window procedure */
2840 static LRESULT CALLBACK
2841 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2843 struct frame *f;
2844 struct w32_display_info *dpyinfo = &one_w32_display_info;
2845 W32Msg wmsg;
2846 int windows_translate;
2847 int key;
2849 /* Note that it is okay to call x_window_to_frame, even though we are
2850 not running in the main lisp thread, because frame deletion
2851 requires the lisp thread to synchronize with this thread. Thus, if
2852 a frame struct is returned, it can be used without concern that the
2853 lisp thread might make it disappear while we are using it.
2855 NB. Walking the frame list in this thread is safe (as long as
2856 writes of Lisp_Object slots are atomic, which they are on Windows).
2857 Although delete-frame can destructively modify the frame list while
2858 we are walking it, a garbage collection cannot occur until after
2859 delete-frame has synchronized with this thread.
2861 It is also safe to use functions that make GDI calls, such as
2862 w32_clear_rect, because these functions must obtain a DC handle
2863 from the frame struct using get_frame_dc which is thread-aware. */
2865 switch (msg)
2867 case WM_ERASEBKGND:
2868 f = x_window_to_frame (dpyinfo, hwnd);
2869 if (f)
2871 HDC hdc = get_frame_dc (f);
2872 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2873 w32_clear_rect (f, hdc, &wmsg.rect);
2874 release_frame_dc (f, hdc);
2876 #if defined (W32_DEBUG_DISPLAY)
2877 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2879 wmsg.rect.left, wmsg.rect.top,
2880 wmsg.rect.right, wmsg.rect.bottom));
2881 #endif /* W32_DEBUG_DISPLAY */
2883 return 1;
2884 case WM_PALETTECHANGED:
2885 /* ignore our own changes */
2886 if ((HWND)wParam != hwnd)
2888 f = x_window_to_frame (dpyinfo, hwnd);
2889 if (f)
2890 /* get_frame_dc will realize our palette and force all
2891 frames to be redrawn if needed. */
2892 release_frame_dc (f, get_frame_dc (f));
2894 return 0;
2895 case WM_PAINT:
2897 PAINTSTRUCT paintStruct;
2898 RECT update_rect;
2899 memset (&update_rect, 0, sizeof (update_rect));
2901 f = x_window_to_frame (dpyinfo, hwnd);
2902 if (f == 0)
2904 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2905 return 0;
2908 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2909 fails. Apparently this can happen under some
2910 circumstances. */
2911 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2913 enter_crit ();
2914 BeginPaint (hwnd, &paintStruct);
2916 /* The rectangles returned by GetUpdateRect and BeginPaint
2917 do not always match. Play it safe by assuming both areas
2918 are invalid. */
2919 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2921 #if defined (W32_DEBUG_DISPLAY)
2922 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2924 wmsg.rect.left, wmsg.rect.top,
2925 wmsg.rect.right, wmsg.rect.bottom));
2926 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2927 update_rect.left, update_rect.top,
2928 update_rect.right, update_rect.bottom));
2929 #endif
2930 EndPaint (hwnd, &paintStruct);
2931 leave_crit ();
2933 /* Change the message type to prevent Windows from
2934 combining WM_PAINT messages in the Lisp thread's queue,
2935 since Windows assumes that each message queue is
2936 dedicated to one frame and does not bother checking
2937 that hwnd matches before combining them. */
2938 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
2940 return 0;
2943 /* If GetUpdateRect returns 0 (meaning there is no update
2944 region), assume the whole window needs to be repainted. */
2945 GetClientRect (hwnd, &wmsg.rect);
2946 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2947 return 0;
2950 case WM_INPUTLANGCHANGE:
2951 /* Inform lisp thread of keyboard layout changes. */
2952 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2954 /* Clear dead keys in the keyboard state; for simplicity only
2955 preserve modifier key states. */
2957 int i;
2958 BYTE keystate[256];
2960 GetKeyboardState (keystate);
2961 for (i = 0; i < 256; i++)
2962 if (1
2963 && i != VK_SHIFT
2964 && i != VK_LSHIFT
2965 && i != VK_RSHIFT
2966 && i != VK_CAPITAL
2967 && i != VK_NUMLOCK
2968 && i != VK_SCROLL
2969 && i != VK_CONTROL
2970 && i != VK_LCONTROL
2971 && i != VK_RCONTROL
2972 && i != VK_MENU
2973 && i != VK_LMENU
2974 && i != VK_RMENU
2975 && i != VK_LWIN
2976 && i != VK_RWIN)
2977 keystate[i] = 0;
2978 SetKeyboardState (keystate);
2980 goto dflt;
2982 case WM_HOTKEY:
2983 /* Synchronize hot keys with normal input. */
2984 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2985 return (0);
2987 case WM_KEYUP:
2988 case WM_SYSKEYUP:
2989 record_keyup (wParam, lParam);
2990 goto dflt;
2992 case WM_KEYDOWN:
2993 case WM_SYSKEYDOWN:
2994 /* Ignore keystrokes we fake ourself; see below. */
2995 if (dpyinfo->faked_key == wParam)
2997 dpyinfo->faked_key = 0;
2998 /* Make sure TranslateMessage sees them though (as long as
2999 they don't produce WM_CHAR messages). This ensures that
3000 indicator lights are toggled promptly on Windows 9x, for
3001 example. */
3002 if (wParam < 256 && lispy_function_keys[wParam])
3004 windows_translate = 1;
3005 goto translate;
3007 return 0;
3010 /* Synchronize modifiers with current keystroke. */
3011 sync_modifiers ();
3012 record_keydown (wParam, lParam);
3013 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3015 windows_translate = 0;
3017 switch (wParam)
3019 case VK_LWIN:
3020 if (NILP (Vw32_pass_lwindow_to_system))
3022 /* Prevent system from acting on keyup (which opens the
3023 Start menu if no other key was pressed) by simulating a
3024 press of Space which we will ignore. */
3025 if (GetAsyncKeyState (wParam) & 1)
3027 if (NUMBERP (Vw32_phantom_key_code))
3028 key = XUINT (Vw32_phantom_key_code) & 255;
3029 else
3030 key = VK_SPACE;
3031 dpyinfo->faked_key = key;
3032 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3035 if (!NILP (Vw32_lwindow_modifier))
3036 return 0;
3037 break;
3038 case VK_RWIN:
3039 if (NILP (Vw32_pass_rwindow_to_system))
3041 if (GetAsyncKeyState (wParam) & 1)
3043 if (NUMBERP (Vw32_phantom_key_code))
3044 key = XUINT (Vw32_phantom_key_code) & 255;
3045 else
3046 key = VK_SPACE;
3047 dpyinfo->faked_key = key;
3048 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3051 if (!NILP (Vw32_rwindow_modifier))
3052 return 0;
3053 break;
3054 case VK_APPS:
3055 if (!NILP (Vw32_apps_modifier))
3056 return 0;
3057 break;
3058 case VK_MENU:
3059 if (NILP (Vw32_pass_alt_to_system))
3060 /* Prevent DefWindowProc from activating the menu bar if an
3061 Alt key is pressed and released by itself. */
3062 return 0;
3063 windows_translate = 1;
3064 break;
3065 case VK_CAPITAL:
3066 /* Decide whether to treat as modifier or function key. */
3067 if (NILP (Vw32_enable_caps_lock))
3068 goto disable_lock_key;
3069 windows_translate = 1;
3070 break;
3071 case VK_NUMLOCK:
3072 /* Decide whether to treat as modifier or function key. */
3073 if (NILP (Vw32_enable_num_lock))
3074 goto disable_lock_key;
3075 windows_translate = 1;
3076 break;
3077 case VK_SCROLL:
3078 /* Decide whether to treat as modifier or function key. */
3079 if (NILP (Vw32_scroll_lock_modifier))
3080 goto disable_lock_key;
3081 windows_translate = 1;
3082 break;
3083 disable_lock_key:
3084 /* Ensure the appropriate lock key state (and indicator light)
3085 remains in the same state. We do this by faking another
3086 press of the relevant key. Apparently, this really is the
3087 only way to toggle the state of the indicator lights. */
3088 dpyinfo->faked_key = wParam;
3089 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3090 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3091 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3092 KEYEVENTF_EXTENDEDKEY | 0, 0);
3093 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3094 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3095 /* Ensure indicator lights are updated promptly on Windows 9x
3096 (TranslateMessage apparently does this), after forwarding
3097 input event. */
3098 post_character_message (hwnd, msg, wParam, lParam,
3099 w32_get_key_modifiers (wParam, lParam));
3100 windows_translate = 1;
3101 break;
3102 case VK_CONTROL:
3103 case VK_SHIFT:
3104 case VK_PROCESSKEY: /* Generated by IME. */
3105 windows_translate = 1;
3106 break;
3107 case VK_CANCEL:
3108 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3109 which is confusing for purposes of key binding; convert
3110 VK_CANCEL events into VK_PAUSE events. */
3111 wParam = VK_PAUSE;
3112 break;
3113 case VK_PAUSE:
3114 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3115 for purposes of key binding; convert these back into
3116 VK_NUMLOCK events, at least when we want to see NumLock key
3117 presses. (Note that there is never any possibility that
3118 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3119 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3120 wParam = VK_NUMLOCK;
3121 break;
3122 default:
3123 /* If not defined as a function key, change it to a WM_CHAR message. */
3124 if (wParam > 255 || !lispy_function_keys[wParam])
3126 DWORD modifiers = construct_console_modifiers ();
3128 if (!NILP (Vw32_recognize_altgr)
3129 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3131 /* Always let TranslateMessage handle AltGr key chords;
3132 for some reason, ToAscii doesn't always process AltGr
3133 chords correctly. */
3134 windows_translate = 1;
3136 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3138 /* Handle key chords including any modifiers other
3139 than shift directly, in order to preserve as much
3140 modifier information as possible. */
3141 if ('A' <= wParam && wParam <= 'Z')
3143 /* Don't translate modified alphabetic keystrokes,
3144 so the user doesn't need to constantly switch
3145 layout to type control or meta keystrokes when
3146 the normal layout translates alphabetic
3147 characters to non-ascii characters. */
3148 if (!modifier_set (VK_SHIFT))
3149 wParam += ('a' - 'A');
3150 msg = WM_CHAR;
3152 else
3154 /* Try to handle other keystrokes by determining the
3155 base character (ie. translating the base key plus
3156 shift modifier). */
3157 int add;
3158 KEY_EVENT_RECORD key;
3160 key.bKeyDown = TRUE;
3161 key.wRepeatCount = 1;
3162 key.wVirtualKeyCode = wParam;
3163 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3164 key.uChar.AsciiChar = 0;
3165 key.dwControlKeyState = modifiers;
3167 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3168 /* 0 means an unrecognized keycode, negative means
3169 dead key. Ignore both. */
3170 while (--add >= 0)
3172 /* Forward asciified character sequence. */
3173 post_character_message
3174 (hwnd, WM_CHAR,
3175 (unsigned char) key.uChar.AsciiChar, lParam,
3176 w32_get_key_modifiers (wParam, lParam));
3177 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3179 return 0;
3182 else
3184 /* Let TranslateMessage handle everything else. */
3185 windows_translate = 1;
3190 translate:
3191 if (windows_translate)
3193 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3194 windows_msg.time = GetMessageTime ();
3195 TranslateMessage (&windows_msg);
3196 goto dflt;
3199 /* Fall through */
3201 case WM_SYSCHAR:
3202 case WM_CHAR:
3203 if (wParam > 255 )
3205 W32Msg wmsg;
3207 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3208 signal_user_input ();
3209 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3212 else
3213 post_character_message (hwnd, msg, wParam, lParam,
3214 w32_get_key_modifiers (wParam, lParam));
3215 break;
3217 case WM_UNICHAR:
3218 /* WM_UNICHAR looks promising from the docs, but the exact
3219 circumstances in which TranslateMessage sends it is one of those
3220 Microsoft secret API things that EU and US courts are supposed
3221 to have put a stop to already. Spy++ shows it being sent to Notepad
3222 and other MS apps, but never to Emacs.
3224 Some third party IMEs send it in accordance with the official
3225 documentation though, so handle it here.
3227 UNICODE_NOCHAR is used to test for support for this message.
3228 TRUE indicates that the message is supported. */
3229 if (wParam == UNICODE_NOCHAR)
3230 return TRUE;
3233 W32Msg wmsg;
3234 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3235 signal_user_input ();
3236 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3238 break;
3240 case WM_IME_CHAR:
3241 /* If we can't get the IME result as Unicode, use default processing,
3242 which will at least allow characters decodable in the system locale
3243 get through. */
3244 if (!get_composition_string_fn)
3245 goto dflt;
3247 else if (!ignore_ime_char)
3249 wchar_t * buffer;
3250 int size, i;
3251 W32Msg wmsg;
3252 HIMC context = get_ime_context_fn (hwnd);
3253 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3254 /* Get buffer size. */
3255 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3256 buffer = alloca (size);
3257 size = get_composition_string_fn (context, GCS_RESULTSTR,
3258 buffer, size);
3259 release_ime_context_fn (hwnd, context);
3261 signal_user_input ();
3262 for (i = 0; i < size / sizeof (wchar_t); i++)
3264 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3265 lParam);
3267 /* Ignore the messages for the rest of the
3268 characters in the string that was output above. */
3269 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3271 else
3272 ignore_ime_char--;
3274 break;
3276 case WM_IME_STARTCOMPOSITION:
3277 if (!set_ime_composition_window_fn)
3278 goto dflt;
3279 else
3281 COMPOSITIONFORM form;
3282 HIMC context;
3283 struct window *w;
3285 /* Implementation note: The code below does something that
3286 one shouldn't do: it accesses the window object from a
3287 separate thread, while the main (a.k.a. "Lisp") thread
3288 runs and can legitimately delete and even GC it. That is
3289 why we are extra careful not to futz with a window that
3290 is different from the one recorded when the system caret
3291 coordinates were last modified. That is also why we are
3292 careful not to move the IME window if the window
3293 described by W was deleted, as indicated by its buffer
3294 field being reset to nil. */
3295 f = x_window_to_frame (dpyinfo, hwnd);
3296 if (!(f && FRAME_LIVE_P (f)))
3297 goto dflt;
3298 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3299 /* Punt if someone changed the frame's selected window
3300 behind our back. */
3301 if (w != w32_system_caret_window)
3302 goto dflt;
3304 form.dwStyle = CFS_RECT;
3305 form.ptCurrentPos.x = w32_system_caret_x;
3306 form.ptCurrentPos.y = w32_system_caret_y;
3308 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3309 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3310 + w32_system_caret_hdr_height);
3311 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3312 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3313 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3314 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3315 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3316 - w32_system_caret_mode_height);
3318 /* Punt if the window was deleted behind our back. */
3319 if (!BUFFERP (w->contents))
3320 goto dflt;
3322 context = get_ime_context_fn (hwnd);
3324 if (!context)
3325 goto dflt;
3327 set_ime_composition_window_fn (context, &form);
3328 release_ime_context_fn (hwnd, context);
3330 /* We should "goto dflt" here to pass WM_IME_STARTCOMPOSITION to
3331 DefWindowProc, so that the composition window will actually
3332 be displayed. But doing so causes trouble with displaying
3333 dialog boxes, such as the file selection dialog or font
3334 selection dialog. So something else is needed to fix the
3335 former without breaking the latter. See bug#11732. */
3336 break;
3338 case WM_IME_ENDCOMPOSITION:
3339 ignore_ime_char = 0;
3340 goto dflt;
3342 /* Simulate middle mouse button events when left and right buttons
3343 are used together, but only if user has two button mouse. */
3344 case WM_LBUTTONDOWN:
3345 case WM_RBUTTONDOWN:
3346 if (w32_num_mouse_buttons > 2)
3347 goto handle_plain_button;
3350 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3351 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3353 if (button_state & this)
3354 return 0;
3356 if (button_state == 0)
3357 SetCapture (hwnd);
3359 button_state |= this;
3361 if (button_state & other)
3363 if (mouse_button_timer)
3365 KillTimer (hwnd, mouse_button_timer);
3366 mouse_button_timer = 0;
3368 /* Generate middle mouse event instead. */
3369 msg = WM_MBUTTONDOWN;
3370 button_state |= MMOUSE;
3372 else if (button_state & MMOUSE)
3374 /* Ignore button event if we've already generated a
3375 middle mouse down event. This happens if the
3376 user releases and press one of the two buttons
3377 after we've faked a middle mouse event. */
3378 return 0;
3380 else
3382 /* Flush out saved message. */
3383 post_msg (&saved_mouse_button_msg);
3385 wmsg.dwModifiers = w32_get_modifiers ();
3386 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3387 signal_user_input ();
3389 /* Clear message buffer. */
3390 saved_mouse_button_msg.msg.hwnd = 0;
3392 else
3394 /* Hold onto message for now. */
3395 mouse_button_timer =
3396 SetTimer (hwnd, MOUSE_BUTTON_ID,
3397 w32_mouse_button_tolerance, NULL);
3398 saved_mouse_button_msg.msg.hwnd = hwnd;
3399 saved_mouse_button_msg.msg.message = msg;
3400 saved_mouse_button_msg.msg.wParam = wParam;
3401 saved_mouse_button_msg.msg.lParam = lParam;
3402 saved_mouse_button_msg.msg.time = GetMessageTime ();
3403 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3406 return 0;
3408 case WM_LBUTTONUP:
3409 case WM_RBUTTONUP:
3410 if (w32_num_mouse_buttons > 2)
3411 goto handle_plain_button;
3414 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3415 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3417 if ((button_state & this) == 0)
3418 return 0;
3420 button_state &= ~this;
3422 if (button_state & MMOUSE)
3424 /* Only generate event when second button is released. */
3425 if ((button_state & other) == 0)
3427 msg = WM_MBUTTONUP;
3428 button_state &= ~MMOUSE;
3430 if (button_state) emacs_abort ();
3432 else
3433 return 0;
3435 else
3437 /* Flush out saved message if necessary. */
3438 if (saved_mouse_button_msg.msg.hwnd)
3440 post_msg (&saved_mouse_button_msg);
3443 wmsg.dwModifiers = w32_get_modifiers ();
3444 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3445 signal_user_input ();
3447 /* Always clear message buffer and cancel timer. */
3448 saved_mouse_button_msg.msg.hwnd = 0;
3449 KillTimer (hwnd, mouse_button_timer);
3450 mouse_button_timer = 0;
3452 if (button_state == 0)
3453 ReleaseCapture ();
3455 return 0;
3457 case WM_XBUTTONDOWN:
3458 case WM_XBUTTONUP:
3459 if (w32_pass_extra_mouse_buttons_to_system)
3460 goto dflt;
3461 /* else fall through and process them. */
3462 case WM_MBUTTONDOWN:
3463 case WM_MBUTTONUP:
3464 handle_plain_button:
3466 BOOL up;
3467 int button;
3469 /* Ignore middle and extra buttons as long as the menu is active. */
3470 f = x_window_to_frame (dpyinfo, hwnd);
3471 if (f && f->output_data.w32->menubar_active)
3472 return 0;
3474 if (parse_button (msg, HIWORD (wParam), &button, &up))
3476 if (up) ReleaseCapture ();
3477 else SetCapture (hwnd);
3478 button = (button == 0) ? LMOUSE :
3479 ((button == 1) ? MMOUSE : RMOUSE);
3480 if (up)
3481 button_state &= ~button;
3482 else
3483 button_state |= button;
3487 wmsg.dwModifiers = w32_get_modifiers ();
3488 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3489 signal_user_input ();
3491 /* Need to return true for XBUTTON messages, false for others,
3492 to indicate that we processed the message. */
3493 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3495 case WM_MOUSEMOVE:
3496 /* Ignore mouse movements as long as the menu is active. These
3497 movements are processed by the window manager anyway, and
3498 it's wrong to handle them as if they happened on the
3499 underlying frame. */
3500 f = x_window_to_frame (dpyinfo, hwnd);
3501 if (f && f->output_data.w32->menubar_active)
3502 return 0;
3504 /* If the mouse has just moved into the frame, start tracking
3505 it, so we will be notified when it leaves the frame. Mouse
3506 tracking only works under W98 and NT4 and later. On earlier
3507 versions, there is no way of telling when the mouse leaves the
3508 frame, so we just have to put up with help-echo and mouse
3509 highlighting remaining while the frame is not active. */
3510 if (track_mouse_event_fn && !track_mouse_window
3511 /* If the menu bar is active, turning on tracking of mouse
3512 movement events might send these events to the tooltip
3513 frame, if the user happens to move the mouse pointer over
3514 the tooltip. But since we don't process events for
3515 tooltip frames, this causes Windows to present a
3516 hourglass cursor, which is ugly and unexpected. So don't
3517 enable tracking mouse events in this case; they will be
3518 restarted when the menu pops down. (Confusingly, the
3519 menubar_active member of f->output_data.w32, tested
3520 above, is only set when a menu was popped up _not_ from
3521 the frame's menu bar, but via x-popup-menu.) */
3522 && !menubar_in_use)
3524 TRACKMOUSEEVENT tme;
3525 tme.cbSize = sizeof (tme);
3526 tme.dwFlags = TME_LEAVE;
3527 tme.hwndTrack = hwnd;
3528 tme.dwHoverTime = HOVER_DEFAULT;
3530 track_mouse_event_fn (&tme);
3531 track_mouse_window = hwnd;
3533 case WM_HSCROLL:
3534 case WM_VSCROLL:
3535 if (w32_mouse_move_interval <= 0
3536 || (msg == WM_MOUSEMOVE && button_state == 0))
3538 wmsg.dwModifiers = w32_get_modifiers ();
3539 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3540 return 0;
3543 /* Hang onto mouse move and scroll messages for a bit, to avoid
3544 sending such events to Emacs faster than it can process them.
3545 If we get more events before the timer from the first message
3546 expires, we just replace the first message. */
3548 if (saved_mouse_move_msg.msg.hwnd == 0)
3549 mouse_move_timer =
3550 SetTimer (hwnd, MOUSE_MOVE_ID,
3551 w32_mouse_move_interval, NULL);
3553 /* Hold onto message for now. */
3554 saved_mouse_move_msg.msg.hwnd = hwnd;
3555 saved_mouse_move_msg.msg.message = msg;
3556 saved_mouse_move_msg.msg.wParam = wParam;
3557 saved_mouse_move_msg.msg.lParam = lParam;
3558 saved_mouse_move_msg.msg.time = GetMessageTime ();
3559 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3561 return 0;
3563 case WM_MOUSEWHEEL:
3564 case WM_DROPFILES:
3565 wmsg.dwModifiers = w32_get_modifiers ();
3566 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3567 signal_user_input ();
3568 return 0;
3570 case WM_APPCOMMAND:
3571 if (w32_pass_multimedia_buttons_to_system)
3572 goto dflt;
3573 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3574 case WM_MOUSEHWHEEL:
3575 wmsg.dwModifiers = w32_get_modifiers ();
3576 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3577 signal_user_input ();
3578 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3579 handled, to prevent the system trying to handle it by faking
3580 scroll bar events. */
3581 return 1;
3583 case WM_TIMER:
3584 /* Flush out saved messages if necessary. */
3585 if (wParam == mouse_button_timer)
3587 if (saved_mouse_button_msg.msg.hwnd)
3589 post_msg (&saved_mouse_button_msg);
3590 signal_user_input ();
3591 saved_mouse_button_msg.msg.hwnd = 0;
3593 KillTimer (hwnd, mouse_button_timer);
3594 mouse_button_timer = 0;
3596 else if (wParam == mouse_move_timer)
3598 if (saved_mouse_move_msg.msg.hwnd)
3600 post_msg (&saved_mouse_move_msg);
3601 saved_mouse_move_msg.msg.hwnd = 0;
3603 KillTimer (hwnd, mouse_move_timer);
3604 mouse_move_timer = 0;
3606 else if (wParam == menu_free_timer)
3608 KillTimer (hwnd, menu_free_timer);
3609 menu_free_timer = 0;
3610 f = x_window_to_frame (dpyinfo, hwnd);
3611 /* If a popup menu is active, don't wipe its strings. */
3612 if (menubar_in_use
3613 && current_popup_menu == NULL)
3615 /* Free memory used by owner-drawn and help-echo strings. */
3616 w32_free_menu_strings (hwnd);
3617 if (f)
3618 f->output_data.w32->menubar_active = 0;
3619 menubar_in_use = 0;
3622 return 0;
3624 case WM_NCACTIVATE:
3625 /* Windows doesn't send us focus messages when putting up and
3626 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3627 The only indication we get that something happened is receiving
3628 this message afterwards. So this is a good time to reset our
3629 keyboard modifiers' state. */
3630 reset_modifiers ();
3631 goto dflt;
3633 case WM_INITMENU:
3634 button_state = 0;
3635 ReleaseCapture ();
3636 /* We must ensure menu bar is fully constructed and up to date
3637 before allowing user interaction with it. To achieve this
3638 we send this message to the lisp thread and wait for a
3639 reply (whose value is not actually needed) to indicate that
3640 the menu bar is now ready for use, so we can now return.
3642 To remain responsive in the meantime, we enter a nested message
3643 loop that can process all other messages.
3645 However, we skip all this if the message results from calling
3646 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3647 thread a message because it is blocked on us at this point. We
3648 set menubar_active before calling TrackPopupMenu to indicate
3649 this (there is no possibility of confusion with real menubar
3650 being active). */
3652 f = x_window_to_frame (dpyinfo, hwnd);
3653 if (f
3654 && (f->output_data.w32->menubar_active
3655 /* We can receive this message even in the absence of a
3656 menubar (ie. when the system menu is activated) - in this
3657 case we do NOT want to forward the message, otherwise it
3658 will cause the menubar to suddenly appear when the user
3659 had requested it to be turned off! */
3660 || f->output_data.w32->menubar_widget == NULL))
3661 return 0;
3664 deferred_msg msg_buf;
3666 /* Detect if message has already been deferred; in this case
3667 we cannot return any sensible value to ignore this. */
3668 if (find_deferred_msg (hwnd, msg) != NULL)
3669 emacs_abort ();
3671 menubar_in_use = 1;
3673 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3676 case WM_EXITMENULOOP:
3677 f = x_window_to_frame (dpyinfo, hwnd);
3679 /* If a menu is still active, check again after a short delay,
3680 since Windows often (always?) sends the WM_EXITMENULOOP
3681 before the corresponding WM_COMMAND message.
3682 Don't do this if a popup menu is active, since it is only
3683 menubar menus that require cleaning up in this way.
3685 if (f && menubar_in_use && current_popup_menu == NULL)
3686 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3688 /* If hourglass cursor should be displayed, display it now. */
3689 if (f && f->output_data.w32->hourglass_p)
3690 SetCursor (f->output_data.w32->hourglass_cursor);
3692 goto dflt;
3694 case WM_MENUSELECT:
3695 /* Direct handling of help_echo in menus. Should be safe now
3696 that we generate the help_echo by placing a help event in the
3697 keyboard buffer. */
3699 HMENU menu = (HMENU) lParam;
3700 UINT menu_item = (UINT) LOWORD (wParam);
3701 UINT flags = (UINT) HIWORD (wParam);
3703 w32_menu_display_help (hwnd, menu, menu_item, flags);
3705 return 0;
3707 case WM_MEASUREITEM:
3708 f = x_window_to_frame (dpyinfo, hwnd);
3709 if (f)
3711 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3713 if (pMis->CtlType == ODT_MENU)
3715 /* Work out dimensions for popup menu titles. */
3716 char * title = (char *) pMis->itemData;
3717 HDC hdc = GetDC (hwnd);
3718 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3719 LOGFONT menu_logfont;
3720 HFONT old_font;
3721 SIZE size;
3723 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3724 menu_logfont.lfWeight = FW_BOLD;
3725 menu_font = CreateFontIndirect (&menu_logfont);
3726 old_font = SelectObject (hdc, menu_font);
3728 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3729 if (title)
3731 if (unicode_append_menu)
3732 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3733 wcslen ((WCHAR *) title),
3734 &size);
3735 else
3736 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3738 pMis->itemWidth = size.cx;
3739 if (pMis->itemHeight < size.cy)
3740 pMis->itemHeight = size.cy;
3742 else
3743 pMis->itemWidth = 0;
3745 SelectObject (hdc, old_font);
3746 DeleteObject (menu_font);
3747 ReleaseDC (hwnd, hdc);
3748 return TRUE;
3751 return 0;
3753 case WM_DRAWITEM:
3754 f = x_window_to_frame (dpyinfo, hwnd);
3755 if (f)
3757 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3759 if (pDis->CtlType == ODT_MENU)
3761 /* Draw popup menu title. */
3762 char * title = (char *) pDis->itemData;
3763 if (title)
3765 HDC hdc = pDis->hDC;
3766 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3767 LOGFONT menu_logfont;
3768 HFONT old_font;
3770 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3771 menu_logfont.lfWeight = FW_BOLD;
3772 menu_font = CreateFontIndirect (&menu_logfont);
3773 old_font = SelectObject (hdc, menu_font);
3775 /* Always draw title as if not selected. */
3776 if (unicode_append_menu)
3777 ExtTextOutW (hdc,
3778 pDis->rcItem.left
3779 + GetSystemMetrics (SM_CXMENUCHECK),
3780 pDis->rcItem.top,
3781 ETO_OPAQUE, &pDis->rcItem,
3782 (WCHAR *) title,
3783 wcslen ((WCHAR *) title), NULL);
3784 else
3785 ExtTextOut (hdc,
3786 pDis->rcItem.left
3787 + GetSystemMetrics (SM_CXMENUCHECK),
3788 pDis->rcItem.top,
3789 ETO_OPAQUE, &pDis->rcItem,
3790 title, strlen (title), NULL);
3792 SelectObject (hdc, old_font);
3793 DeleteObject (menu_font);
3795 return TRUE;
3798 return 0;
3800 #if 0
3801 /* Still not right - can't distinguish between clicks in the
3802 client area of the frame from clicks forwarded from the scroll
3803 bars - may have to hook WM_NCHITTEST to remember the mouse
3804 position and then check if it is in the client area ourselves. */
3805 case WM_MOUSEACTIVATE:
3806 /* Discard the mouse click that activates a frame, allowing the
3807 user to click anywhere without changing point (or worse!).
3808 Don't eat mouse clicks on scrollbars though!! */
3809 if (LOWORD (lParam) == HTCLIENT )
3810 return MA_ACTIVATEANDEAT;
3811 goto dflt;
3812 #endif
3814 case WM_MOUSELEAVE:
3815 /* No longer tracking mouse. */
3816 track_mouse_window = NULL;
3818 case WM_ACTIVATEAPP:
3819 case WM_ACTIVATE:
3820 case WM_WINDOWPOSCHANGED:
3821 case WM_SHOWWINDOW:
3822 /* Inform lisp thread that a frame might have just been obscured
3823 or exposed, so should recheck visibility of all frames. */
3824 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3825 goto dflt;
3827 case WM_SETFOCUS:
3828 dpyinfo->faked_key = 0;
3829 reset_modifiers ();
3830 register_hot_keys (hwnd);
3831 goto command;
3832 case WM_KILLFOCUS:
3833 unregister_hot_keys (hwnd);
3834 button_state = 0;
3835 ReleaseCapture ();
3836 /* Relinquish the system caret. */
3837 if (w32_system_caret_hwnd)
3839 w32_visible_system_caret_hwnd = NULL;
3840 w32_system_caret_hwnd = NULL;
3841 DestroyCaret ();
3843 goto command;
3844 case WM_COMMAND:
3845 menubar_in_use = 0;
3846 f = x_window_to_frame (dpyinfo, hwnd);
3847 if (f && HIWORD (wParam) == 0)
3849 if (menu_free_timer)
3851 KillTimer (hwnd, menu_free_timer);
3852 menu_free_timer = 0;
3855 case WM_MOVE:
3856 case WM_SIZE:
3857 command:
3858 wmsg.dwModifiers = w32_get_modifiers ();
3859 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3860 goto dflt;
3862 case WM_DESTROY:
3863 CoUninitialize ();
3864 return 0;
3866 case WM_CLOSE:
3867 wmsg.dwModifiers = w32_get_modifiers ();
3868 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3869 return 0;
3871 case WM_WINDOWPOSCHANGING:
3872 /* Don't restrict the sizing of any kind of frames. If the window
3873 manager doesn't, there's no reason to do it ourselves. */
3874 #if 0
3875 if (frame_resize_pixelwise || hwnd == tip_window)
3876 #endif
3877 return 0;
3879 #if 0
3880 /* Don't restrict the sizing of fullscreened frames, allowing them to be
3881 flush with the sides of the screen. */
3882 f = x_window_to_frame (dpyinfo, hwnd);
3883 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
3884 return 0;
3887 WINDOWPLACEMENT wp;
3888 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3890 wp.length = sizeof (WINDOWPLACEMENT);
3891 GetWindowPlacement (hwnd, &wp);
3893 if (wp.showCmd != SW_SHOWMAXIMIZED && wp.showCmd != SW_SHOWMINIMIZED
3894 && (lppos->flags & SWP_NOSIZE) == 0)
3896 RECT rect;
3897 int wdiff;
3898 int hdiff;
3899 DWORD font_width;
3900 DWORD line_height;
3901 DWORD internal_border;
3902 DWORD vscrollbar_extra;
3903 DWORD hscrollbar_extra;
3904 RECT wr;
3906 wp.length = sizeof (wp);
3907 GetWindowRect (hwnd, &wr);
3909 enter_crit ();
3911 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3912 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3913 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3914 vscrollbar_extra = GetWindowLong (hwnd, WND_VSCROLLBAR_INDEX);
3915 hscrollbar_extra = GetWindowLong (hwnd, WND_HSCROLLBAR_INDEX);
3917 leave_crit ();
3919 memset (&rect, 0, sizeof (rect));
3920 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3921 GetMenu (hwnd) != NULL);
3923 /* Force width and height of client area to be exact
3924 multiples of the character cell dimensions. */
3925 wdiff = (lppos->cx - (rect.right - rect.left)
3926 - 2 * internal_border - vscrollbar_extra)
3927 % font_width;
3928 hdiff = (lppos->cy - (rect.bottom - rect.top)
3929 - 2 * internal_border - hscrollbar_extra)
3930 % line_height;
3932 if (wdiff || hdiff)
3934 /* For right/bottom sizing we can just fix the sizes.
3935 However for top/left sizing we will need to fix the X
3936 and Y positions as well. */
3938 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3939 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3941 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3942 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3944 if (wp.showCmd != SW_SHOWMAXIMIZED
3945 && (lppos->flags & SWP_NOMOVE) == 0)
3947 if (lppos->x != wr.left || lppos->y != wr.top)
3949 lppos->x += wdiff;
3950 lppos->y += hdiff;
3952 else
3954 lppos->flags |= SWP_NOMOVE;
3958 return 0;
3963 goto dflt;
3964 #endif
3966 case WM_GETMINMAXINFO:
3967 /* Hack to allow resizing the Emacs frame above the screen size.
3968 Note that Windows 9x limits coordinates to 16-bits. */
3969 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3970 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3971 return 0;
3973 case WM_SETCURSOR:
3974 if (LOWORD (lParam) == HTCLIENT)
3976 f = x_window_to_frame (dpyinfo, hwnd);
3977 if (f && f->output_data.w32->hourglass_p
3978 && !menubar_in_use && !current_popup_menu)
3979 SetCursor (f->output_data.w32->hourglass_cursor);
3980 else if (f)
3981 SetCursor (f->output_data.w32->current_cursor);
3982 return 0;
3984 goto dflt;
3986 case WM_EMACS_SETCURSOR:
3988 Cursor cursor = (Cursor) wParam;
3989 f = x_window_to_frame (dpyinfo, hwnd);
3990 if (f && cursor)
3992 f->output_data.w32->current_cursor = cursor;
3993 if (!f->output_data.w32->hourglass_p)
3994 SetCursor (cursor);
3996 return 0;
3999 case WM_EMACS_SHOWCURSOR:
4001 ShowCursor ((BOOL) wParam);
4003 return 0;
4006 case WM_EMACS_CREATEVSCROLLBAR:
4007 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
4008 (struct scroll_bar *) lParam);
4010 case WM_EMACS_CREATEHSCROLLBAR:
4011 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
4012 (struct scroll_bar *) lParam);
4014 case WM_EMACS_SHOWWINDOW:
4015 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4017 case WM_EMACS_BRINGTOTOP:
4018 case WM_EMACS_SETFOREGROUND:
4020 HWND foreground_window;
4021 DWORD foreground_thread, retval;
4023 /* On NT 5.0, and apparently Windows 98, it is necessary to
4024 attach to the thread that currently has focus in order to
4025 pull the focus away from it. */
4026 foreground_window = GetForegroundWindow ();
4027 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4028 if (!foreground_window
4029 || foreground_thread == GetCurrentThreadId ()
4030 || !AttachThreadInput (GetCurrentThreadId (),
4031 foreground_thread, TRUE))
4032 foreground_thread = 0;
4034 retval = SetForegroundWindow ((HWND) wParam);
4035 if (msg == WM_EMACS_BRINGTOTOP)
4036 retval = BringWindowToTop ((HWND) wParam);
4038 /* Detach from the previous foreground thread. */
4039 if (foreground_thread)
4040 AttachThreadInput (GetCurrentThreadId (),
4041 foreground_thread, FALSE);
4043 return retval;
4046 case WM_EMACS_SETWINDOWPOS:
4048 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4049 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4050 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4053 case WM_EMACS_DESTROYWINDOW:
4054 DragAcceptFiles ((HWND) wParam, FALSE);
4055 return DestroyWindow ((HWND) wParam);
4057 case WM_EMACS_HIDE_CARET:
4058 return HideCaret (hwnd);
4060 case WM_EMACS_SHOW_CARET:
4061 return ShowCaret (hwnd);
4063 case WM_EMACS_DESTROY_CARET:
4064 w32_system_caret_hwnd = NULL;
4065 w32_visible_system_caret_hwnd = NULL;
4066 return DestroyCaret ();
4068 case WM_EMACS_TRACK_CARET:
4069 /* If there is currently no system caret, create one. */
4070 if (w32_system_caret_hwnd == NULL)
4072 /* Use the default caret width, and avoid changing it
4073 unnecessarily, as it confuses screen reader software. */
4074 w32_system_caret_hwnd = hwnd;
4075 CreateCaret (hwnd, NULL, 0,
4076 w32_system_caret_height);
4079 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4080 return 0;
4081 /* Ensure visible caret gets turned on when requested. */
4082 else if (w32_use_visible_system_caret
4083 && w32_visible_system_caret_hwnd != hwnd)
4085 w32_visible_system_caret_hwnd = hwnd;
4086 return ShowCaret (hwnd);
4088 /* Ensure visible caret gets turned off when requested. */
4089 else if (!w32_use_visible_system_caret
4090 && w32_visible_system_caret_hwnd)
4092 w32_visible_system_caret_hwnd = NULL;
4093 return HideCaret (hwnd);
4095 else
4096 return 1;
4098 case WM_EMACS_TRACKPOPUPMENU:
4100 UINT flags;
4101 POINT *pos;
4102 int retval;
4103 pos = (POINT *)lParam;
4104 flags = TPM_CENTERALIGN;
4105 if (button_state & LMOUSE)
4106 flags |= TPM_LEFTBUTTON;
4107 else if (button_state & RMOUSE)
4108 flags |= TPM_RIGHTBUTTON;
4110 /* Remember we did a SetCapture on the initial mouse down event,
4111 so for safety, we make sure the capture is canceled now. */
4112 ReleaseCapture ();
4113 button_state = 0;
4115 /* Use menubar_active to indicate that WM_INITMENU is from
4116 TrackPopupMenu below, and should be ignored. */
4117 f = x_window_to_frame (dpyinfo, hwnd);
4118 if (f)
4119 f->output_data.w32->menubar_active = 1;
4121 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4122 0, hwnd, NULL))
4124 MSG amsg;
4125 /* Eat any mouse messages during popupmenu */
4126 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4127 PM_REMOVE));
4128 /* Get the menu selection, if any */
4129 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4131 retval = LOWORD (amsg.wParam);
4133 else
4135 retval = 0;
4138 else
4140 retval = -1;
4143 return retval;
4145 case WM_EMACS_FILENOTIFY:
4146 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4147 return 1;
4149 default:
4150 /* Check for messages registered at runtime. */
4151 if (msg == msh_mousewheel)
4153 wmsg.dwModifiers = w32_get_modifiers ();
4154 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4155 signal_user_input ();
4156 return 0;
4159 dflt:
4160 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4163 /* The most common default return code for handled messages is 0. */
4164 return 0;
4167 static void
4168 my_create_window (struct frame * f)
4170 MSG msg;
4171 static int coords[2];
4172 Lisp_Object left, top;
4173 struct w32_display_info *dpyinfo = &one_w32_display_info;
4175 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
4176 anything that is not a number and is not Qunbound. */
4177 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
4178 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
4179 if (EQ (left, Qunbound))
4180 coords[0] = CW_USEDEFAULT;
4181 else
4182 coords[0] = XINT (left);
4183 if (EQ (top, Qunbound))
4184 coords[1] = CW_USEDEFAULT;
4185 else
4186 coords[1] = XINT (top);
4188 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
4189 (WPARAM)f, (LPARAM)coords))
4190 emacs_abort ();
4191 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4195 /* Create a tooltip window. Unlike my_create_window, we do not do this
4196 indirectly via the Window thread, as we do not need to process Window
4197 messages for the tooltip. Creating tooltips indirectly also creates
4198 deadlocks when tooltips are created for menu items. */
4199 static void
4200 my_create_tip_window (struct frame *f)
4202 RECT rect;
4204 rect.left = rect.top = 0;
4205 rect.right = FRAME_PIXEL_WIDTH (f);
4206 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4208 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4209 FRAME_EXTERNAL_MENU_BAR (f));
4211 tip_window = FRAME_W32_WINDOW (f)
4212 = CreateWindow (EMACS_CLASS,
4213 f->namebuf,
4214 f->output_data.w32->dwStyle,
4215 f->left_pos,
4216 f->top_pos,
4217 rect.right - rect.left,
4218 rect.bottom - rect.top,
4219 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4220 NULL,
4221 hinst,
4222 NULL);
4224 if (tip_window)
4226 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4227 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4228 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4229 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4231 /* Tip frames have no scrollbars. */
4232 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
4233 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
4235 /* Do this to discard the default setting specified by our parent. */
4236 ShowWindow (tip_window, SW_HIDE);
4241 /* Create and set up the w32 window for frame F. */
4243 static void
4244 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
4246 block_input ();
4248 /* Use the resource name as the top-level window name
4249 for looking up resources. Make a non-Lisp copy
4250 for the window manager, so GC relocation won't bother it.
4252 Elsewhere we specify the window name for the window manager. */
4253 f->namebuf = xlispstrdup (Vx_resource_name);
4255 my_create_window (f);
4257 validate_x_resource_name ();
4259 /* x_set_name normally ignores requests to set the name if the
4260 requested name is the same as the current name. This is the one
4261 place where that assumption isn't correct; f->name is set, but
4262 the server hasn't been told. */
4264 Lisp_Object name;
4265 int explicit = f->explicit_name;
4267 f->explicit_name = 0;
4268 name = f->name;
4269 fset_name (f, Qnil);
4270 x_set_name (f, name, explicit);
4273 unblock_input ();
4275 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4276 initialize_frame_menubar (f);
4278 if (FRAME_W32_WINDOW (f) == 0)
4279 error ("Unable to create window");
4282 /* Handle the icon stuff for this window. Perhaps later we might
4283 want an x_set_icon_position which can be called interactively as
4284 well. */
4286 static void
4287 x_icon (struct frame *f, Lisp_Object parms)
4289 Lisp_Object icon_x, icon_y;
4290 struct w32_display_info *dpyinfo = &one_w32_display_info;
4292 /* Set the position of the icon. Note that Windows 95 groups all
4293 icons in the tray. */
4294 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4295 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4296 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4298 CHECK_NUMBER (icon_x);
4299 CHECK_NUMBER (icon_y);
4301 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4302 error ("Both left and top icon corners of icon must be specified");
4304 block_input ();
4306 #if 0 /* TODO */
4307 /* Start up iconic or window? */
4308 x_wm_set_window_state
4309 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4310 ? IconicState
4311 : NormalState));
4313 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4314 ? f->icon_name
4315 : f->name)));
4316 #endif
4318 unblock_input ();
4322 static void
4323 x_make_gc (struct frame *f)
4325 XGCValues gc_values;
4327 block_input ();
4329 /* Create the GC's of this frame.
4330 Note that many default values are used. */
4332 /* Normal video */
4333 gc_values.font = FRAME_FONT (f);
4335 /* Cursor has cursor-color background, background-color foreground. */
4336 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4337 gc_values.background = f->output_data.w32->cursor_pixel;
4338 f->output_data.w32->cursor_gc
4339 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4340 (GCFont | GCForeground | GCBackground),
4341 &gc_values);
4343 /* Reliefs. */
4344 f->output_data.w32->white_relief.gc = 0;
4345 f->output_data.w32->black_relief.gc = 0;
4347 unblock_input ();
4351 /* Handler for signals raised during x_create_frame and
4352 x_create_tip_frame. FRAME is the frame which is partially
4353 constructed. */
4355 static Lisp_Object
4356 unwind_create_frame (Lisp_Object frame)
4358 struct frame *f = XFRAME (frame);
4360 /* If frame is ``official'', nothing to do. */
4361 if (NILP (Fmemq (frame, Vframe_list)))
4363 #ifdef GLYPH_DEBUG
4364 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4366 /* If the frame's image cache refcount is still the same as our
4367 private shadow variable, it means we are unwinding a frame
4368 for which we didn't yet call init_frame_faces, where the
4369 refcount is incremented. Therefore, we increment it here, so
4370 that free_frame_faces, called in x_free_frame_resources
4371 below, will not mistakenly decrement the counter that was not
4372 incremented yet to account for this new frame. */
4373 if (FRAME_IMAGE_CACHE (f) != NULL
4374 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
4375 FRAME_IMAGE_CACHE (f)->refcount++;
4376 #endif
4378 x_free_frame_resources (f);
4379 free_glyphs (f);
4381 #ifdef GLYPH_DEBUG
4382 /* Check that reference counts are indeed correct. */
4383 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4384 eassert ((dpyinfo->terminal->image_cache == NULL
4385 && image_cache_refcount == 0)
4386 || (dpyinfo->terminal->image_cache != NULL
4387 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
4388 #endif
4389 return Qt;
4392 return Qnil;
4395 static void
4396 do_unwind_create_frame (Lisp_Object frame)
4398 unwind_create_frame (frame);
4401 static void
4402 unwind_create_frame_1 (Lisp_Object val)
4404 inhibit_lisp_code = val;
4407 static void
4408 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4410 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4411 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4412 RES_TYPE_STRING);
4413 Lisp_Object font;
4414 if (EQ (font_param, Qunbound))
4415 font_param = Qnil;
4416 font = !NILP (font_param) ? font_param
4417 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4419 if (!STRINGP (font))
4421 int i;
4422 static char *names[]
4423 = { "Courier New-10",
4424 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4425 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4426 "Fixedsys",
4427 NULL };
4429 for (i = 0; names[i]; i++)
4431 font = font_open_by_name (f, build_unibyte_string (names[i]));
4432 if (! NILP (font))
4433 break;
4435 if (NILP (font))
4436 error ("No suitable font was found");
4438 else if (!NILP (font_param))
4440 /* Remember the explicit font parameter, so we can re-apply it after
4441 we've applied the `default' face settings. */
4442 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4444 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4447 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4448 1, 1, 0,
4449 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4450 Return an Emacs frame object.
4451 PARAMETERS is an alist of frame parameters.
4452 If the parameters specify that the frame should not have a minibuffer,
4453 and do not specify a specific minibuffer window to use,
4454 then `default-minibuffer-frame' must be a frame whose minibuffer can
4455 be shared by the new frame.
4457 This function is an internal primitive--use `make-frame' instead. */)
4458 (Lisp_Object parameters)
4460 struct frame *f;
4461 Lisp_Object frame, tem;
4462 Lisp_Object name;
4463 bool minibuffer_only = false;
4464 long window_prompting = 0;
4465 ptrdiff_t count = SPECPDL_INDEX ();
4466 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4467 Lisp_Object display;
4468 struct w32_display_info *dpyinfo = NULL;
4469 Lisp_Object parent;
4470 struct kboard *kb;
4472 if (!FRAME_W32_P (SELECTED_FRAME ())
4473 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4474 error ("Cannot create a GUI frame in a -nw session");
4476 /* Make copy of frame parameters because the original is in pure
4477 storage now. */
4478 parameters = Fcopy_alist (parameters);
4480 /* Use this general default value to start with
4481 until we know if this frame has a specified name. */
4482 Vx_resource_name = Vinvocation_name;
4484 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4485 if (EQ (display, Qunbound))
4486 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4487 if (EQ (display, Qunbound))
4488 display = Qnil;
4489 dpyinfo = check_x_display_info (display);
4490 kb = dpyinfo->terminal->kboard;
4492 if (!dpyinfo->terminal->name)
4493 error ("Terminal is not live, can't create new frames on it");
4495 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4496 if (!STRINGP (name)
4497 && ! EQ (name, Qunbound)
4498 && ! NILP (name))
4499 error ("Invalid frame name--not a string or nil");
4501 if (STRINGP (name))
4502 Vx_resource_name = name;
4504 /* See if parent window is specified. */
4505 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4506 if (EQ (parent, Qunbound))
4507 parent = Qnil;
4508 if (! NILP (parent))
4509 CHECK_NUMBER (parent);
4511 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4512 /* No need to protect DISPLAY because that's not used after passing
4513 it to make_frame_without_minibuffer. */
4514 frame = Qnil;
4515 GCPRO4 (parameters, parent, name, frame);
4516 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
4517 RES_TYPE_SYMBOL);
4518 if (EQ (tem, Qnone) || NILP (tem))
4519 f = make_frame_without_minibuffer (Qnil, kb, display);
4520 else if (EQ (tem, Qonly))
4522 f = make_minibuffer_frame ();
4523 minibuffer_only = true;
4525 else if (WINDOWP (tem))
4526 f = make_frame_without_minibuffer (tem, kb, display);
4527 else
4528 f = make_frame (true);
4530 XSETFRAME (frame, f);
4532 /* By default, make scrollbars the system standard width and height. */
4533 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4534 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
4536 f->terminal = dpyinfo->terminal;
4538 f->output_method = output_w32;
4539 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
4540 FRAME_FONTSET (f) = -1;
4542 fset_icon_name
4543 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
4544 RES_TYPE_STRING));
4545 if (! STRINGP (f->icon_name))
4546 fset_icon_name (f, Qnil);
4548 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
4550 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
4551 record_unwind_protect (do_unwind_create_frame, frame);
4553 #ifdef GLYPH_DEBUG
4554 image_cache_refcount =
4555 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
4556 dpyinfo_refcount = dpyinfo->reference_count;
4557 #endif /* GLYPH_DEBUG */
4559 /* Specify the parent under which to make this window. */
4560 if (!NILP (parent))
4562 /* Cast to UINT_PTR shuts up compiler warnings about cast to
4563 pointer from integer of different size. */
4564 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
4565 f->output_data.w32->explicit_parent = true;
4567 else
4569 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4570 f->output_data.w32->explicit_parent = false;
4573 /* Set the name; the functions to which we pass f expect the name to
4574 be set. */
4575 if (EQ (name, Qunbound) || NILP (name))
4577 fset_name (f, build_string (dpyinfo->w32_id_name));
4578 f->explicit_name = false;
4580 else
4582 fset_name (f, name);
4583 f->explicit_name = true;
4584 /* Use the frame's title when getting resources for this frame. */
4585 specbind (Qx_resource_name, name);
4588 if (uniscribe_available)
4589 register_font_driver (&uniscribe_font_driver, f);
4590 register_font_driver (&w32font_driver, f);
4592 x_default_parameter (f, parameters, Qfont_backend, Qnil,
4593 "fontBackend", "FontBackend", RES_TYPE_STRING);
4595 /* Extract the window parameters from the supplied values
4596 that are needed to determine window geometry. */
4597 x_default_font_parameter (f, parameters);
4599 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4600 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4602 /* We recognize either internalBorderWidth or internalBorder
4603 (which is what xterm calls it). */
4604 if (NILP (Fassq (Qinternal_border_width, parameters)))
4606 Lisp_Object value;
4608 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
4609 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4610 if (! EQ (value, Qunbound))
4611 parameters = Fcons (Fcons (Qinternal_border_width, value),
4612 parameters);
4614 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4615 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4616 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4617 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
4618 NULL, NULL, RES_TYPE_NUMBER);
4619 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
4620 NULL, NULL, RES_TYPE_NUMBER);
4621 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4622 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4623 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
4624 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4626 /* Also do the stuff which must be set before the window exists. */
4627 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4628 "foreground", "Foreground", RES_TYPE_STRING);
4629 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4630 "background", "Background", RES_TYPE_STRING);
4631 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4632 "pointerColor", "Foreground", RES_TYPE_STRING);
4633 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4634 "borderColor", "BorderColor", RES_TYPE_STRING);
4635 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4636 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4637 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4638 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4639 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4640 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4641 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4642 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4643 /* Process alpha here (Bug#16619). */
4644 x_default_parameter (f, parameters, Qalpha, Qnil,
4645 "alpha", "Alpha", RES_TYPE_NUMBER);
4647 /* Init faces first since we need the frame's column width/line
4648 height in various occasions. */
4649 init_frame_faces (f);
4651 /* The following call of change_frame_size is needed since otherwise
4652 x_set_tool_bar_lines will already work with the character sizes
4653 installed by init_frame_faces while the frame's pixel size is
4654 still calculated from a character size of 1 and we subsequently
4655 hit the (height >= 0) assertion in window_box_height.
4657 The non-pixelwise code apparently worked around this because it
4658 had one frame line vs one toolbar line which left us with a zero
4659 root window height which was obviously wrong as well ... */
4660 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
4661 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
4662 Qx_create_frame_1);
4664 /* The X resources controlling the menu-bar and tool-bar are
4665 processed specially at startup, and reflected in the mode
4666 variables; ignore them here. */
4667 x_default_parameter (f, parameters, Qmenu_bar_lines,
4668 NILP (Vmenu_bar_mode)
4669 ? make_number (0) : make_number (1),
4670 NULL, NULL, RES_TYPE_NUMBER);
4671 x_default_parameter (f, parameters, Qtool_bar_lines,
4672 NILP (Vtool_bar_mode)
4673 ? make_number (0) : make_number (1),
4674 NULL, NULL, RES_TYPE_NUMBER);
4676 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4677 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4678 x_default_parameter (f, parameters, Qtitle, Qnil,
4679 "title", "Title", RES_TYPE_STRING);
4681 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4682 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4684 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4685 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4686 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4687 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4688 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4689 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4690 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
4692 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
4694 window_prompting = x_figure_window_size (f, parameters, true);
4696 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4697 f->no_split = minibuffer_only || EQ (tem, Qt);
4699 w32_window (f, window_prompting, minibuffer_only);
4700 x_icon (f, parameters);
4702 x_make_gc (f);
4704 /* Now consider the frame official. */
4705 f->terminal->reference_count++;
4706 FRAME_DISPLAY_INFO (f)->reference_count++;
4707 Vframe_list = Fcons (frame, Vframe_list);
4709 /* We need to do this after creating the window, so that the
4710 icon-creation functions can say whose icon they're describing. */
4711 x_default_parameter (f, parameters, Qicon_type, Qnil,
4712 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4714 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4715 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4716 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4717 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4718 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4719 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4720 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4721 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4722 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
4723 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
4725 /* Allow x_set_window_size, now. */
4726 f->can_x_set_window_size = true;
4728 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
4729 Qx_create_frame_2);
4731 /* Tell the server what size and position, etc, we want, and how
4732 badly we want them. This should be done after we have the menu
4733 bar so that its size can be taken into account. */
4734 block_input ();
4735 x_wm_set_size_hint (f, window_prompting, false);
4736 unblock_input ();
4738 /* Process fullscreen parameter here in the hope that normalizing a
4739 fullheight/fullwidth frame will produce the size set by the last
4740 adjust_frame_size call. */
4741 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4742 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4744 /* Make the window appear on the frame and enable display, unless
4745 the caller says not to. However, with explicit parent, Emacs
4746 cannot control visibility, so don't try. */
4747 if (! f->output_data.w32->explicit_parent)
4749 Lisp_Object visibility;
4751 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4752 if (EQ (visibility, Qunbound))
4753 visibility = Qt;
4755 if (EQ (visibility, Qicon))
4756 x_iconify_frame (f);
4757 else if (! NILP (visibility))
4758 x_make_frame_visible (f);
4759 else
4760 /* Must have been Qnil. */
4764 /* Initialize `default-minibuffer-frame' in case this is the first
4765 frame on this terminal. */
4766 if (FRAME_HAS_MINIBUF_P (f)
4767 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
4768 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
4769 kset_default_minibuffer_frame (kb, frame);
4771 /* All remaining specified parameters, which have not been "used"
4772 by x_get_arg and friends, now go in the misc. alist of the frame. */
4773 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4774 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4775 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
4777 UNGCPRO;
4779 /* Make sure windows on this frame appear in calls to next-window
4780 and similar functions. */
4781 Vwindow_list = Qnil;
4783 return unbind_to (count, frame);
4786 /* FRAME is used only to get a handle on the X display. We don't pass the
4787 display info directly because we're called from frame.c, which doesn't
4788 know about that structure. */
4789 Lisp_Object
4790 x_get_focus_frame (struct frame *frame)
4792 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
4793 Lisp_Object xfocus;
4794 if (! dpyinfo->w32_focus_frame)
4795 return Qnil;
4797 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4798 return xfocus;
4801 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4802 doc: /* Internal function called by `color-defined-p', which see.
4803 \(Note that the Nextstep version of this function ignores FRAME.) */)
4804 (Lisp_Object color, Lisp_Object frame)
4806 XColor foo;
4807 struct frame *f = decode_window_system_frame (frame);
4809 CHECK_STRING (color);
4811 if (w32_defined_color (f, SDATA (color), &foo, false))
4812 return Qt;
4813 else
4814 return Qnil;
4817 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
4818 doc: /* Internal function called by `color-values', which see. */)
4819 (Lisp_Object color, Lisp_Object frame)
4821 XColor foo;
4822 struct frame *f = decode_window_system_frame (frame);
4824 CHECK_STRING (color);
4826 if (w32_defined_color (f, SDATA (color), &foo, false))
4827 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4828 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4829 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
4830 else
4831 return Qnil;
4834 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
4835 doc: /* Internal function called by `display-color-p', which see. */)
4836 (Lisp_Object display)
4838 struct w32_display_info *dpyinfo = check_x_display_info (display);
4840 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4841 return Qnil;
4843 return Qt;
4846 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4847 Sx_display_grayscale_p, 0, 1, 0,
4848 doc: /* Return t if DISPLAY supports shades of gray.
4849 Note that color displays do support shades of gray.
4850 The optional argument DISPLAY specifies which display to ask about.
4851 DISPLAY should be either a frame or a display name (a string).
4852 If omitted or nil, that stands for the selected frame's display. */)
4853 (Lisp_Object display)
4855 struct w32_display_info *dpyinfo = check_x_display_info (display);
4857 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4858 return Qnil;
4860 return Qt;
4863 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4864 Sx_display_pixel_width, 0, 1, 0,
4865 doc: /* Return the width in pixels of DISPLAY.
4866 The optional argument DISPLAY specifies which display to ask about.
4867 DISPLAY should be either a frame or a display name (a string).
4868 If omitted or nil, that stands for the selected frame's display.
4870 On \"multi-monitor\" setups this refers to the pixel width for all
4871 physical monitors associated with DISPLAY. To get information for
4872 each physical monitor, use `display-monitor-attributes-list'. */)
4873 (Lisp_Object display)
4875 struct w32_display_info *dpyinfo = check_x_display_info (display);
4877 return make_number (x_display_pixel_width (dpyinfo));
4880 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
4881 Sx_display_pixel_height, 0, 1, 0,
4882 doc: /* Return the height in pixels of DISPLAY.
4883 The optional argument DISPLAY specifies which display to ask about.
4884 DISPLAY should be either a frame or a display name (a string).
4885 If omitted or nil, that stands for the selected frame's display.
4887 On \"multi-monitor\" setups this refers to the pixel height for all
4888 physical monitors associated with DISPLAY. To get information for
4889 each physical monitor, use `display-monitor-attributes-list'. */)
4890 (Lisp_Object display)
4892 struct w32_display_info *dpyinfo = check_x_display_info (display);
4894 return make_number (x_display_pixel_height (dpyinfo));
4897 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
4898 0, 1, 0,
4899 doc: /* Return the number of bitplanes of DISPLAY.
4900 The optional argument DISPLAY specifies which display to ask about.
4901 DISPLAY should be either a frame or a display name (a string).
4902 If omitted or nil, that stands for the selected frame's display. */)
4903 (Lisp_Object display)
4905 struct w32_display_info *dpyinfo = check_x_display_info (display);
4907 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4910 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
4911 0, 1, 0,
4912 doc: /* Return the number of color cells of DISPLAY.
4913 The optional argument DISPLAY specifies which display to ask about.
4914 DISPLAY should be either a frame or a display name (a string).
4915 If omitted or nil, that stands for the selected frame's display. */)
4916 (Lisp_Object display)
4918 struct w32_display_info *dpyinfo = check_x_display_info (display);
4919 int cap;
4921 /* Don't use NCOLORS: it returns incorrect results under remote
4922 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4923 * overflow and because probably is more meaningful on Windows
4924 * anyway. */
4926 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
4927 return make_number (cap);
4930 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4931 Sx_server_max_request_size,
4932 0, 1, 0,
4933 doc: /* Return the maximum request size of the server of DISPLAY.
4934 The optional argument DISPLAY specifies which display to ask about.
4935 DISPLAY should be either a frame or a display name (a string).
4936 If omitted or nil, that stands for the selected frame's display. */)
4937 (Lisp_Object display)
4939 return make_number (1);
4942 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
4943 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
4945 \(Labeling every distributor as a "vendor" embodies the false assumption
4946 that operating systems cannot be developed and distributed noncommercially.)
4948 For GNU and Unix systems, this queries the X server software; for
4949 MS-Windows, this queries the OS.
4951 The optional argument TERMINAL specifies which display to ask about.
4952 TERMINAL should be a terminal object, a frame or a display name (a string).
4953 If omitted or nil, that stands for the selected frame's display. */)
4954 (Lisp_Object terminal)
4956 return build_string ("Microsoft Corp.");
4959 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
4960 doc: /* Return the version numbers of the GUI software on TERMINAL.
4961 The value is a list of three integers specifying the version of the GUI
4962 software in use.
4964 For GNU and Unix system, the first 2 numbers are the version of the X
4965 Protocol used on TERMINAL and the 3rd number is the distributor-specific
4966 release number. For MS-Windows, the 3 numbers report the version and
4967 the build number of the OS.
4969 See also the function `x-server-vendor'.
4971 The optional argument TERMINAL specifies which display to ask about.
4972 TERMINAL should be a terminal object, a frame or a display name (a string).
4973 If omitted or nil, that stands for the selected frame's display. */)
4974 (Lisp_Object terminal)
4976 return list3i (w32_major_version, w32_minor_version, w32_build_number);
4979 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
4980 doc: /* Return the number of screens on the server of DISPLAY.
4981 The optional argument DISPLAY specifies which display to ask about.
4982 DISPLAY should be either a frame or a display name (a string).
4983 If omitted or nil, that stands for the selected frame's display. */)
4984 (Lisp_Object display)
4986 return make_number (1);
4989 DEFUN ("x-display-mm-height", Fx_display_mm_height,
4990 Sx_display_mm_height, 0, 1, 0,
4991 doc: /* Return the height in millimeters of DISPLAY.
4992 The optional argument DISPLAY specifies which display to ask about.
4993 DISPLAY should be either a frame or a display name (a string).
4994 If omitted or nil, that stands for the selected frame's display.
4996 On \"multi-monitor\" setups this refers to the height in millimeters for
4997 all physical monitors associated with DISPLAY. To get information
4998 for each physical monitor, use `display-monitor-attributes-list'. */)
4999 (Lisp_Object display)
5001 struct w32_display_info *dpyinfo = check_x_display_info (display);
5002 HDC hdc;
5003 double mm_per_pixel;
5005 hdc = GetDC (NULL);
5006 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5007 / GetDeviceCaps (hdc, VERTRES));
5008 ReleaseDC (NULL, hdc);
5010 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5013 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5014 doc: /* Return the width in millimeters of DISPLAY.
5015 The optional argument DISPLAY specifies which display to ask about.
5016 DISPLAY should be either a frame or a display name (a string).
5017 If omitted or nil, that stands for the selected frame's display.
5019 On \"multi-monitor\" setups this refers to the width in millimeters for
5020 all physical monitors associated with TERMINAL. To get information
5021 for each physical monitor, use `display-monitor-attributes-list'. */)
5022 (Lisp_Object display)
5024 struct w32_display_info *dpyinfo = check_x_display_info (display);
5025 HDC hdc;
5026 double mm_per_pixel;
5028 hdc = GetDC (NULL);
5029 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5030 / GetDeviceCaps (hdc, HORZRES));
5031 ReleaseDC (NULL, hdc);
5033 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5036 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5037 Sx_display_backing_store, 0, 1, 0,
5038 doc: /* Return an indication of whether DISPLAY does backing store.
5039 The value may be `always', `when-mapped', or `not-useful'.
5040 The optional argument DISPLAY specifies which display to ask about.
5041 DISPLAY should be either a frame or a display name (a string).
5042 If omitted or nil, that stands for the selected frame's display. */)
5043 (Lisp_Object display)
5045 return intern ("not-useful");
5048 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5049 Sx_display_visual_class, 0, 1, 0,
5050 doc: /* Return the visual class of DISPLAY.
5051 The value is one of the symbols `static-gray', `gray-scale',
5052 `static-color', `pseudo-color', `true-color', or `direct-color'.
5054 The optional argument DISPLAY specifies which display to ask about.
5055 DISPLAY should be either a frame or a display name (a string).
5056 If omitted or nil, that stands for the selected frame's display. */)
5057 (Lisp_Object display)
5059 struct w32_display_info *dpyinfo = check_x_display_info (display);
5060 Lisp_Object result = Qnil;
5062 if (dpyinfo->has_palette)
5063 result = intern ("pseudo-color");
5064 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5065 result = intern ("static-grey");
5066 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5067 result = intern ("static-color");
5068 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5069 result = intern ("true-color");
5071 return result;
5074 DEFUN ("x-display-save-under", Fx_display_save_under,
5075 Sx_display_save_under, 0, 1, 0,
5076 doc: /* Return t if DISPLAY supports the save-under feature.
5077 The optional argument DISPLAY specifies which display to ask about.
5078 DISPLAY should be either a frame or a display name (a string).
5079 If omitted or nil, that stands for the selected frame's display. */)
5080 (Lisp_Object display)
5082 return Qnil;
5085 static BOOL CALLBACK ALIGN_STACK
5086 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5088 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5090 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5092 return TRUE;
5095 static Lisp_Object
5096 w32_display_monitor_attributes_list (void)
5098 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5099 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5100 int i, n_monitors;
5101 HMONITOR *monitors;
5102 struct gcpro gcpro1, gcpro2, gcpro3;
5104 if (!(enum_display_monitors_fn && get_monitor_info_fn
5105 && monitor_from_window_fn))
5106 return Qnil;
5108 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5109 (LPARAM) &monitor_list)
5110 || NILP (monitor_list))
5111 return Qnil;
5113 n_monitors = 0;
5114 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5115 n_monitors++;
5117 monitors = xmalloc (n_monitors * sizeof (*monitors));
5118 for (i = 0; i < n_monitors; i++)
5120 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5121 monitor_list = XCDR (monitor_list);
5124 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5125 FOR_EACH_FRAME (rest, frame)
5127 struct frame *f = XFRAME (frame);
5129 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5131 HMONITOR monitor =
5132 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5133 MONITOR_DEFAULT_TO_NEAREST);
5135 for (i = 0; i < n_monitors; i++)
5136 if (monitors[i] == monitor)
5137 break;
5139 if (i < n_monitors)
5140 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5144 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5146 for (i = 0; i < n_monitors; i++)
5148 Lisp_Object geometry, workarea, name, attributes = Qnil;
5149 HDC hdc;
5150 int width_mm, height_mm;
5151 struct MONITOR_INFO_EX mi;
5153 mi.cbSize = sizeof (mi);
5154 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5155 continue;
5157 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5158 if (hdc == NULL)
5159 continue;
5160 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5161 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5162 DeleteDC (hdc);
5164 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5165 attributes);
5167 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5169 attributes = Fcons (Fcons (Qname, name), attributes);
5171 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5172 attributes);
5174 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5175 mi.rcWork.right - mi.rcWork.left,
5176 mi.rcWork.bottom - mi.rcWork.top);
5177 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5179 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5180 mi.rcMonitor.right - mi.rcMonitor.left,
5181 mi.rcMonitor.bottom - mi.rcMonitor.top);
5182 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5184 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5185 primary_monitor_attributes = attributes;
5186 else
5187 attributes_list = Fcons (attributes, attributes_list);
5190 if (!NILP (primary_monitor_attributes))
5191 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5193 UNGCPRO;
5195 xfree (monitors);
5197 return attributes_list;
5200 static Lisp_Object
5201 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5203 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5204 HDC hdc;
5205 double mm_per_pixel;
5206 int pixel_width, pixel_height, width_mm, height_mm;
5207 RECT workarea_rect;
5209 /* Fallback: treat (possibly) multiple physical monitors as if they
5210 formed a single monitor as a whole. This should provide a
5211 consistent result at least on single monitor environments. */
5212 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5213 attributes);
5215 frames = Qnil;
5216 FOR_EACH_FRAME (rest, frame)
5218 struct frame *f = XFRAME (frame);
5220 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5221 frames = Fcons (frame, frames);
5223 attributes = Fcons (Fcons (Qframes, frames), attributes);
5225 pixel_width = x_display_pixel_width (dpyinfo);
5226 pixel_height = x_display_pixel_height (dpyinfo);
5228 hdc = GetDC (NULL);
5229 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5230 / GetDeviceCaps (hdc, HORZRES));
5231 width_mm = pixel_width * mm_per_pixel + 0.5;
5232 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5233 / GetDeviceCaps (hdc, VERTRES));
5234 height_mm = pixel_height * mm_per_pixel + 0.5;
5235 ReleaseDC (NULL, hdc);
5236 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5237 attributes);
5239 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5240 we don't care. */
5241 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5242 GetSystemMetrics (SM_YVIRTUALSCREEN),
5243 pixel_width, pixel_height);
5244 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5245 workarea = list4i (workarea_rect.left, workarea_rect.top,
5246 workarea_rect.right - workarea_rect.left,
5247 workarea_rect.bottom - workarea_rect.top);
5248 else
5249 workarea = geometry;
5250 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5252 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5254 return list1 (attributes);
5257 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5258 Sw32_display_monitor_attributes_list,
5259 0, 1, 0,
5260 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5262 The optional argument DISPLAY specifies which display to ask about.
5263 DISPLAY should be either a frame or a display name (a string).
5264 If omitted or nil, that stands for the selected frame's display.
5266 Internal use only, use `display-monitor-attributes-list' instead. */)
5267 (Lisp_Object display)
5269 struct w32_display_info *dpyinfo = check_x_display_info (display);
5270 Lisp_Object attributes_list;
5272 block_input ();
5273 attributes_list = w32_display_monitor_attributes_list ();
5274 if (NILP (attributes_list))
5275 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5276 unblock_input ();
5278 return attributes_list;
5281 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5282 doc: /* Set the sound generated when the bell is rung.
5283 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5284 to use the corresponding system sound for the bell. The 'silent sound
5285 prevents Emacs from making any sound at all.
5286 SOUND is nil to use the normal beep. */)
5287 (Lisp_Object sound)
5289 CHECK_SYMBOL (sound);
5291 if (NILP (sound))
5292 sound_type = 0xFFFFFFFF;
5293 else if (EQ (sound, intern ("asterisk")))
5294 sound_type = MB_ICONASTERISK;
5295 else if (EQ (sound, intern ("exclamation")))
5296 sound_type = MB_ICONEXCLAMATION;
5297 else if (EQ (sound, intern ("hand")))
5298 sound_type = MB_ICONHAND;
5299 else if (EQ (sound, intern ("question")))
5300 sound_type = MB_ICONQUESTION;
5301 else if (EQ (sound, intern ("ok")))
5302 sound_type = MB_OK;
5303 else if (EQ (sound, intern ("silent")))
5304 sound_type = MB_EMACS_SILENT;
5305 else
5306 sound_type = 0xFFFFFFFF;
5308 return sound;
5312 x_screen_planes (register struct frame *f)
5314 return FRAME_DISPLAY_INFO (f)->n_planes;
5317 /* Return the display structure for the display named NAME.
5318 Open a new connection if necessary. */
5320 struct w32_display_info *
5321 x_display_info_for_name (Lisp_Object name)
5323 struct w32_display_info *dpyinfo;
5325 CHECK_STRING (name);
5327 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5328 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5329 return dpyinfo;
5331 /* Use this general default value to start with. */
5332 Vx_resource_name = Vinvocation_name;
5334 validate_x_resource_name ();
5336 dpyinfo = w32_term_init (name, (unsigned char *)0,
5337 SSDATA (Vx_resource_name));
5339 if (dpyinfo == 0)
5340 error ("Cannot connect to server %s", SDATA (name));
5342 XSETFASTINT (Vwindow_system_version, w32_major_version);
5344 return dpyinfo;
5347 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5348 1, 3, 0, doc: /* Open a connection to a display server.
5349 DISPLAY is the name of the display to connect to.
5350 Optional second arg XRM-STRING is a string of resources in xrdb format.
5351 If the optional third arg MUST-SUCCEED is non-nil,
5352 terminate Emacs if we can't open the connection.
5353 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5354 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5356 unsigned char *xrm_option;
5357 struct w32_display_info *dpyinfo;
5359 CHECK_STRING (display);
5361 /* Signal an error in order to encourage correct use from callers.
5362 * If we ever support multiple window systems in the same Emacs,
5363 * we'll need callers to be precise about what window system they
5364 * want. */
5366 if (strcmp (SSDATA (display), "w32") != 0)
5367 error ("The name of the display in this Emacs must be \"w32\"");
5369 /* If initialization has already been done, return now to avoid
5370 overwriting critical parts of one_w32_display_info. */
5371 if (window_system_available (NULL))
5372 return Qnil;
5374 if (! NILP (xrm_string))
5375 CHECK_STRING (xrm_string);
5377 /* Allow color mapping to be defined externally; first look in user's
5378 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5380 Lisp_Object color_file;
5381 struct gcpro gcpro1;
5383 color_file = build_string ("~/rgb.txt");
5385 GCPRO1 (color_file);
5387 if (NILP (Ffile_readable_p (color_file)))
5388 color_file =
5389 Fexpand_file_name (build_string ("rgb.txt"),
5390 Fsymbol_value (intern ("data-directory")));
5392 Vw32_color_map = Fx_load_color_file (color_file);
5394 UNGCPRO;
5396 if (NILP (Vw32_color_map))
5397 Vw32_color_map = w32_default_color_map ();
5399 /* Merge in system logical colors. */
5400 add_system_logical_colors_to_map (&Vw32_color_map);
5402 if (! NILP (xrm_string))
5403 xrm_option = SDATA (xrm_string);
5404 else
5405 xrm_option = (unsigned char *) 0;
5407 /* Use this general default value to start with. */
5408 /* First remove .exe suffix from invocation-name - it looks ugly. */
5410 char basename[ MAX_PATH ], *str;
5412 lispstpcpy (basename, Vinvocation_name);
5413 str = strrchr (basename, '.');
5414 if (str) *str = 0;
5415 Vinvocation_name = build_string (basename);
5417 Vx_resource_name = Vinvocation_name;
5419 validate_x_resource_name ();
5421 /* This is what opens the connection and sets x_current_display.
5422 This also initializes many symbols, such as those used for input. */
5423 dpyinfo = w32_term_init (display, xrm_option,
5424 SSDATA (Vx_resource_name));
5426 if (dpyinfo == 0)
5428 if (!NILP (must_succeed))
5429 fatal ("Cannot connect to server %s.\n",
5430 SDATA (display));
5431 else
5432 error ("Cannot connect to server %s", SDATA (display));
5435 XSETFASTINT (Vwindow_system_version, w32_major_version);
5436 return Qnil;
5439 DEFUN ("x-close-connection", Fx_close_connection,
5440 Sx_close_connection, 1, 1, 0,
5441 doc: /* Close the connection to DISPLAY's server.
5442 For DISPLAY, specify either a frame or a display name (a string).
5443 If DISPLAY is nil, that stands for the selected frame's display. */)
5444 (Lisp_Object display)
5446 struct w32_display_info *dpyinfo = check_x_display_info (display);
5448 if (dpyinfo->reference_count > 0)
5449 error ("Display still has frames on it");
5451 block_input ();
5452 x_destroy_all_bitmaps (dpyinfo);
5454 x_delete_display (dpyinfo);
5455 unblock_input ();
5457 return Qnil;
5460 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5461 doc: /* Return the list of display names that Emacs has connections to. */)
5462 (void)
5464 Lisp_Object result = Qnil;
5465 struct w32_display_info *wdi;
5467 for (wdi = x_display_list; wdi; wdi = wdi->next)
5468 result = Fcons (XCAR (wdi->name_list_element), result);
5470 return result;
5473 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5474 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5475 This function only has an effect on X Windows. With MS Windows, it is
5476 defined but does nothing.
5478 If ON is nil, allow buffering of requests.
5479 Turning on synchronization prohibits the Xlib routines from buffering
5480 requests and seriously degrades performance, but makes debugging much
5481 easier.
5482 The optional second argument TERMINAL specifies which display to act on.
5483 TERMINAL should be a terminal object, a frame or a display name (a string).
5484 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5485 (Lisp_Object on, Lisp_Object display)
5487 return Qnil;
5492 /***********************************************************************
5493 Window properties
5494 ***********************************************************************/
5496 #if 0 /* TODO : port window properties to W32 */
5498 DEFUN ("x-change-window-property", Fx_change_window_property,
5499 Sx_change_window_property, 2, 6, 0,
5500 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5501 PROP must be a string. VALUE may be a string or a list of conses,
5502 numbers and/or strings. If an element in the list is a string, it is
5503 converted to an atom and the value of the Atom is used. If an element
5504 is a cons, it is converted to a 32 bit number where the car is the 16
5505 top bits and the cdr is the lower 16 bits.
5507 FRAME nil or omitted means use the selected frame.
5508 If TYPE is given and non-nil, it is the name of the type of VALUE.
5509 If TYPE is not given or nil, the type is STRING.
5510 FORMAT gives the size in bits of each element if VALUE is a list.
5511 It must be one of 8, 16 or 32.
5512 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
5513 If OUTER-P is non-nil, the property is changed for the outer X window of
5514 FRAME. Default is to change on the edit X window. */)
5515 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5516 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
5518 struct frame *f = decode_window_system_frame (frame);
5519 Atom prop_atom;
5521 CHECK_STRING (prop);
5522 CHECK_STRING (value);
5524 block_input ();
5525 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5526 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5527 prop_atom, XA_STRING, 8, PropModeReplace,
5528 SDATA (value), SCHARS (value));
5530 /* Make sure the property is set when we return. */
5531 XFlush (FRAME_W32_DISPLAY (f));
5532 unblock_input ();
5534 return value;
5538 DEFUN ("x-delete-window-property", Fx_delete_window_property,
5539 Sx_delete_window_property, 1, 2, 0,
5540 doc: /* Remove window property PROP from X window of FRAME.
5541 FRAME nil or omitted means use the selected frame. Value is PROP. */)
5542 (Lisp_Object prop, Lisp_Object frame)
5544 struct frame *f = decode_window_system_frame (frame);
5545 Atom prop_atom;
5547 CHECK_STRING (prop);
5548 block_input ();
5549 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5550 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
5552 /* Make sure the property is removed when we return. */
5553 XFlush (FRAME_W32_DISPLAY (f));
5554 unblock_input ();
5556 return prop;
5560 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
5561 1, 6, 0,
5562 doc: /* Value is the value of window property PROP on FRAME.
5563 If FRAME is nil or omitted, use the selected frame.
5565 On X Windows, the following optional arguments are also accepted:
5566 If TYPE is nil or omitted, get the property as a string.
5567 Otherwise TYPE is the name of the atom that denotes the type expected.
5568 If SOURCE is non-nil, get the property on that window instead of from
5569 FRAME. The number 0 denotes the root window.
5570 If DELETE-P is non-nil, delete the property after retrieving it.
5571 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5573 On MS Windows, this function accepts but ignores those optional arguments.
5575 Value is nil if FRAME hasn't a property with name PROP or if PROP has
5576 no value of TYPE (always string in the MS Windows case). */)
5577 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5578 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
5580 struct frame *f = decode_window_system_frame (frame);
5581 Atom prop_atom;
5582 int rc;
5583 Lisp_Object prop_value = Qnil;
5584 char *tmp_data = NULL;
5585 Atom actual_type;
5586 int actual_format;
5587 unsigned long actual_size, bytes_remaining;
5589 CHECK_STRING (prop);
5590 block_input ();
5591 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5592 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5593 prop_atom, 0, 0, False, XA_STRING,
5594 &actual_type, &actual_format, &actual_size,
5595 &bytes_remaining, (unsigned char **) &tmp_data);
5596 if (rc == Success)
5598 int size = bytes_remaining;
5600 XFree (tmp_data);
5601 tmp_data = NULL;
5603 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5604 prop_atom, 0, bytes_remaining,
5605 False, XA_STRING,
5606 &actual_type, &actual_format,
5607 &actual_size, &bytes_remaining,
5608 (unsigned char **) &tmp_data);
5609 if (rc == Success)
5610 prop_value = make_string (tmp_data, size);
5612 XFree (tmp_data);
5615 unblock_input ();
5617 return prop_value;
5619 return Qnil;
5622 #endif /* TODO */
5624 /***********************************************************************
5625 Tool tips
5626 ***********************************************************************/
5628 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5629 Lisp_Object, Lisp_Object);
5630 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5631 Lisp_Object, int, int, int *, int *);
5633 /* The frame of a currently visible tooltip. */
5635 Lisp_Object tip_frame;
5637 /* If non-nil, a timer started that hides the last tooltip when it
5638 fires. */
5640 Lisp_Object tip_timer;
5641 Window tip_window;
5643 /* If non-nil, a vector of 3 elements containing the last args
5644 with which x-show-tip was called. See there. */
5646 Lisp_Object last_show_tip_args;
5649 static void
5650 unwind_create_tip_frame (Lisp_Object frame)
5652 Lisp_Object deleted;
5654 deleted = unwind_create_frame (frame);
5655 if (EQ (deleted, Qt))
5657 tip_window = NULL;
5658 tip_frame = Qnil;
5663 /* Create a frame for a tooltip on the display described by DPYINFO.
5664 PARMS is a list of frame parameters. TEXT is the string to
5665 display in the tip frame. Value is the frame.
5667 Note that functions called here, esp. x_default_parameter can
5668 signal errors, for instance when a specified color name is
5669 undefined. We have to make sure that we're in a consistent state
5670 when this happens. */
5672 static Lisp_Object
5673 x_create_tip_frame (struct w32_display_info *dpyinfo,
5674 Lisp_Object parms, Lisp_Object text)
5676 struct frame *f;
5677 Lisp_Object frame;
5678 Lisp_Object name;
5679 long window_prompting = 0;
5680 int width, height;
5681 ptrdiff_t count = SPECPDL_INDEX ();
5682 struct gcpro gcpro1, gcpro2, gcpro3;
5683 struct kboard *kb;
5684 bool face_change_before = face_change;
5685 Lisp_Object buffer;
5686 struct buffer *old_buffer;
5688 /* Use this general default value to start with until we know if
5689 this frame has a specified name. */
5690 Vx_resource_name = Vinvocation_name;
5692 kb = dpyinfo->terminal->kboard;
5694 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5695 avoid destructive changes behind our caller's back. */
5696 parms = Fcopy_alist (parms);
5698 /* Get the name of the frame to use for resource lookup. */
5699 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
5700 if (!STRINGP (name)
5701 && !EQ (name, Qunbound)
5702 && !NILP (name))
5703 error ("Invalid frame name--not a string or nil");
5704 Vx_resource_name = name;
5706 frame = Qnil;
5707 GCPRO3 (parms, name, frame);
5708 /* Make a frame without minibuffer nor mode-line. */
5709 f = make_frame (false);
5710 f->wants_modeline = 0;
5711 XSETFRAME (frame, f);
5713 AUTO_STRING (tip, " *tip*");
5714 buffer = Fget_buffer_create (tip);
5715 /* Use set_window_buffer instead of Fset_window_buffer (see
5716 discussion of bug#11984, bug#12025, bug#12026). */
5717 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, false, false);
5718 old_buffer = current_buffer;
5719 set_buffer_internal_1 (XBUFFER (buffer));
5720 bset_truncate_lines (current_buffer, Qnil);
5721 specbind (Qinhibit_read_only, Qt);
5722 specbind (Qinhibit_modification_hooks, Qt);
5723 Ferase_buffer ();
5724 Finsert (1, &text);
5725 set_buffer_internal_1 (old_buffer);
5727 record_unwind_protect (unwind_create_tip_frame, frame);
5729 /* By setting the output method, we're essentially saying that
5730 the frame is live, as per FRAME_LIVE_P. If we get a signal
5731 from this point on, x_destroy_window might screw up reference
5732 counts etc. */
5733 f->terminal = dpyinfo->terminal;
5734 f->output_method = output_w32;
5735 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5737 FRAME_FONTSET (f) = -1;
5738 fset_icon_name (f, Qnil);
5740 #ifdef GLYPH_DEBUG
5741 image_cache_refcount =
5742 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5743 dpyinfo_refcount = dpyinfo->reference_count;
5744 #endif /* GLYPH_DEBUG */
5745 FRAME_KBOARD (f) = kb;
5746 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5747 f->output_data.w32->explicit_parent = false;
5749 /* Set the name; the functions to which we pass f expect the name to
5750 be set. */
5751 if (EQ (name, Qunbound) || NILP (name))
5753 fset_name (f, build_string (dpyinfo->w32_id_name));
5754 f->explicit_name = false;
5756 else
5758 fset_name (f, name);
5759 f->explicit_name = true;
5760 /* use the frame's title when getting resources for this frame. */
5761 specbind (Qx_resource_name, name);
5764 if (uniscribe_available)
5765 register_font_driver (&uniscribe_font_driver, f);
5766 register_font_driver (&w32font_driver, f);
5768 x_default_parameter (f, parms, Qfont_backend, Qnil,
5769 "fontBackend", "FontBackend", RES_TYPE_STRING);
5771 /* Extract the window parameters from the supplied values
5772 that are needed to determine window geometry. */
5773 x_default_font_parameter (f, parms);
5775 x_default_parameter (f, parms, Qborder_width, make_number (2),
5776 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5777 /* This defaults to 2 in order to match xterm. We recognize either
5778 internalBorderWidth or internalBorder (which is what xterm calls
5779 it). */
5780 if (NILP (Fassq (Qinternal_border_width, parms)))
5782 Lisp_Object value;
5784 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
5785 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5786 if (! EQ (value, Qunbound))
5787 parms = Fcons (Fcons (Qinternal_border_width, value),
5788 parms);
5790 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
5791 "internalBorderWidth", "internalBorderWidth",
5792 RES_TYPE_NUMBER);
5793 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5794 NULL, NULL, RES_TYPE_NUMBER);
5795 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5796 NULL, NULL, RES_TYPE_NUMBER);
5798 /* Also do the stuff which must be set before the window exists. */
5799 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5800 "foreground", "Foreground", RES_TYPE_STRING);
5801 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5802 "background", "Background", RES_TYPE_STRING);
5803 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5804 "pointerColor", "Foreground", RES_TYPE_STRING);
5805 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5806 "cursorColor", "Foreground", RES_TYPE_STRING);
5807 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5808 "borderColor", "BorderColor", RES_TYPE_STRING);
5809 x_default_parameter (f, parms, Qalpha, Qnil,
5810 "alpha", "Alpha", RES_TYPE_NUMBER);
5812 /* Init faces before x_default_parameter is called for the
5813 scroll-bar-width parameter because otherwise we end up in
5814 init_iterator with a null face cache, which should not happen. */
5815 init_frame_faces (f);
5817 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
5818 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5820 window_prompting = x_figure_window_size (f, parms, false);
5822 /* No fringes on tip frame. */
5823 f->fringe_cols = 0;
5824 f->left_fringe_width = 0;
5825 f->right_fringe_width = 0;
5827 block_input ();
5828 my_create_tip_window (f);
5829 unblock_input ();
5831 x_make_gc (f);
5833 x_default_parameter (f, parms, Qauto_raise, Qnil,
5834 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5835 x_default_parameter (f, parms, Qauto_lower, Qnil,
5836 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5837 x_default_parameter (f, parms, Qcursor_type, Qbox,
5838 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5840 /* Dimensions, especially FRAME_LINES (f), must be done via
5841 change_frame_size. Change will not be effected unless different
5842 from the current FRAME_LINES (f). */
5843 width = FRAME_COLS (f);
5844 height = FRAME_LINES (f);
5845 SET_FRAME_COLS (f, 0);
5846 SET_FRAME_LINES (f, 0);
5847 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
5848 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
5850 /* Add `tooltip' frame parameter's default value. */
5851 if (NILP (Fframe_parameter (frame, Qtooltip)))
5852 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
5854 /* Set up faces after all frame parameters are known. This call
5855 also merges in face attributes specified for new frames.
5857 Frame parameters may be changed if .Xdefaults contains
5858 specifications for the default font. For example, if there is an
5859 `Emacs.default.attributeBackground: pink', the `background-color'
5860 attribute of the frame get's set, which let's the internal border
5861 of the tooltip frame appear in pink. Prevent this. */
5863 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
5864 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5865 Lisp_Object colors = Qnil;
5867 /* Set tip_frame here, so that */
5868 tip_frame = frame;
5869 call2 (Qface_set_after_frame_default, frame, Qnil);
5871 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
5872 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5873 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5874 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5876 if (!NILP (colors))
5877 Fmodify_frame_parameters (frame, colors);
5880 f->no_split = true;
5882 UNGCPRO;
5884 /* Now that the frame is official, it counts as a reference to
5885 its display. */
5886 FRAME_DISPLAY_INFO (f)->reference_count++;
5887 f->terminal->reference_count++;
5889 /* It is now ok to make the frame official even if we get an error
5890 below. And the frame needs to be on Vframe_list or making it
5891 visible won't work. */
5892 Vframe_list = Fcons (frame, Vframe_list);
5893 f->can_x_set_window_size = true;
5895 /* Setting attributes of faces of the tooltip frame from resources
5896 and similar will set face_change, which leads to the
5897 clearing of all current matrices. Since this isn't necessary
5898 here, avoid it by resetting face_change to the value it
5899 had before we created the tip frame. */
5900 face_change = face_change_before;
5902 /* Discard the unwind_protect. */
5903 return unbind_to (count, frame);
5907 /* Compute where to display tip frame F. PARMS is the list of frame
5908 parameters for F. DX and DY are specified offsets from the current
5909 location of the mouse. WIDTH and HEIGHT are the width and height
5910 of the tooltip. Return coordinates relative to the root window of
5911 the display in *ROOT_X, and *ROOT_Y. */
5913 static void
5914 compute_tip_xy (struct frame *f,
5915 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5916 int width, int height, int *root_x, int *root_y)
5918 Lisp_Object left, top;
5919 int min_x, min_y, max_x, max_y;
5921 /* User-specified position? */
5922 left = Fcdr (Fassq (Qleft, parms));
5923 top = Fcdr (Fassq (Qtop, parms));
5925 /* Move the tooltip window where the mouse pointer is. Resize and
5926 show it. */
5927 if (!INTEGERP (left) || !INTEGERP (top))
5929 POINT pt;
5931 /* Default min and max values. */
5932 min_x = 0;
5933 min_y = 0;
5934 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5935 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
5937 block_input ();
5938 GetCursorPos (&pt);
5939 *root_x = pt.x;
5940 *root_y = pt.y;
5941 unblock_input ();
5943 /* If multiple monitor support is available, constrain the tip onto
5944 the current monitor. This improves the above by allowing negative
5945 co-ordinates if monitor positions are such that they are valid, and
5946 snaps a tooltip onto a single monitor if we are close to the edge
5947 where it would otherwise flow onto the other monitor (or into
5948 nothingness if there is a gap in the overlap). */
5949 if (monitor_from_point_fn && get_monitor_info_fn)
5951 struct MONITOR_INFO info;
5952 HMONITOR monitor
5953 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5954 info.cbSize = sizeof (info);
5956 if (get_monitor_info_fn (monitor, &info))
5958 min_x = info.rcWork.left;
5959 min_y = info.rcWork.top;
5960 max_x = info.rcWork.right;
5961 max_y = info.rcWork.bottom;
5966 if (INTEGERP (top))
5967 *root_y = XINT (top);
5968 else if (*root_y + XINT (dy) <= min_y)
5969 *root_y = min_y; /* Can happen for negative dy */
5970 else if (*root_y + XINT (dy) + height <= max_y)
5971 /* It fits below the pointer */
5972 *root_y += XINT (dy);
5973 else if (height + XINT (dy) + min_y <= *root_y)
5974 /* It fits above the pointer. */
5975 *root_y -= height + XINT (dy);
5976 else
5977 /* Put it on the top. */
5978 *root_y = min_y;
5980 if (INTEGERP (left))
5981 *root_x = XINT (left);
5982 else if (*root_x + XINT (dx) <= min_x)
5983 *root_x = 0; /* Can happen for negative dx */
5984 else if (*root_x + XINT (dx) + width <= max_x)
5985 /* It fits to the right of the pointer. */
5986 *root_x += XINT (dx);
5987 else if (width + XINT (dx) + min_x <= *root_x)
5988 /* It fits to the left of the pointer. */
5989 *root_x -= width + XINT (dx);
5990 else
5991 /* Put it left justified on the screen -- it ought to fit that way. */
5992 *root_x = min_x;
5996 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
5997 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
5998 A tooltip window is a small window displaying a string.
6000 This is an internal function; Lisp code should call `tooltip-show'.
6002 FRAME nil or omitted means use the selected frame.
6004 PARMS is an optional list of frame parameters which can be
6005 used to change the tooltip's appearance.
6007 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6008 means use the default timeout of 5 seconds.
6010 If the list of frame parameters PARMS contains a `left' parameter,
6011 the tooltip is displayed at that x-position. Otherwise it is
6012 displayed at the mouse position, with offset DX added (default is 5 if
6013 DX isn't specified). Likewise for the y-position; if a `top' frame
6014 parameter is specified, it determines the y-position of the tooltip
6015 window, otherwise it is displayed at the mouse position, with offset
6016 DY added (default is -10).
6018 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6019 Text larger than the specified size is clipped. */)
6020 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6022 struct frame *f;
6023 struct window *w;
6024 int root_x, root_y;
6025 struct buffer *old_buffer;
6026 struct text_pos pos;
6027 int i, width, height;
6028 bool seen_reversed_p;
6029 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
6030 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6031 ptrdiff_t count = SPECPDL_INDEX ();
6033 specbind (Qinhibit_redisplay, Qt);
6035 GCPRO4 (string, parms, frame, timeout);
6037 CHECK_STRING (string);
6038 f = decode_window_system_frame (frame);
6039 if (NILP (timeout))
6040 timeout = make_number (5);
6041 else
6042 CHECK_NATNUM (timeout);
6044 if (NILP (dx))
6045 dx = make_number (5);
6046 else
6047 CHECK_NUMBER (dx);
6049 if (NILP (dy))
6050 dy = make_number (-10);
6051 else
6052 CHECK_NUMBER (dy);
6054 if (NILP (last_show_tip_args))
6055 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6057 if (!NILP (tip_frame))
6059 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6060 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6061 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6063 if (EQ (frame, last_frame)
6064 && !NILP (Fequal (last_string, string))
6065 && !NILP (Fequal (last_parms, parms)))
6067 struct frame *f = XFRAME (tip_frame);
6069 /* Only DX and DY have changed. */
6070 if (!NILP (tip_timer))
6072 Lisp_Object timer = tip_timer;
6073 tip_timer = Qnil;
6074 call1 (Qcancel_timer, timer);
6077 block_input ();
6078 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6079 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6081 /* Put tooltip in topmost group and in position. */
6082 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6083 root_x, root_y, 0, 0,
6084 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6086 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6087 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6088 0, 0, 0, 0,
6089 SWP_NOMOVE | SWP_NOSIZE
6090 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6092 unblock_input ();
6093 goto start_timer;
6097 /* Hide a previous tip, if any. */
6098 Fx_hide_tip ();
6100 ASET (last_show_tip_args, 0, string);
6101 ASET (last_show_tip_args, 1, frame);
6102 ASET (last_show_tip_args, 2, parms);
6104 /* Add default values to frame parameters. */
6105 if (NILP (Fassq (Qname, parms)))
6106 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6107 if (NILP (Fassq (Qinternal_border_width, parms)))
6108 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6109 if (NILP (Fassq (Qright_divider_width, parms)))
6110 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6111 if (NILP (Fassq (Qbottom_divider_width, parms)))
6112 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6113 if (NILP (Fassq (Qborder_width, parms)))
6114 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6115 if (NILP (Fassq (Qborder_color, parms)))
6116 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6117 if (NILP (Fassq (Qbackground_color, parms)))
6118 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6119 parms);
6121 /* Block input until the tip has been fully drawn, to avoid crashes
6122 when drawing tips in menus. */
6123 block_input ();
6125 /* Create a frame for the tooltip, and record it in the global
6126 variable tip_frame. */
6127 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6128 f = XFRAME (frame);
6130 /* Set up the frame's root window. */
6131 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6132 w->left_col = 0;
6133 w->top_line = 0;
6134 w->pixel_left = 0;
6135 w->pixel_top = 0;
6137 if (CONSP (Vx_max_tooltip_size)
6138 && INTEGERP (XCAR (Vx_max_tooltip_size))
6139 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6140 && INTEGERP (XCDR (Vx_max_tooltip_size))
6141 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6143 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6144 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6146 else
6148 w->total_cols = 80;
6149 w->total_lines = 40;
6152 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6153 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6155 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6156 adjust_frame_glyphs (f);
6157 w->pseudo_window_p = true;
6159 /* Display the tooltip text in a temporary buffer. */
6160 old_buffer = current_buffer;
6161 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6162 bset_truncate_lines (current_buffer, Qnil);
6163 clear_glyph_matrix (w->desired_matrix);
6164 clear_glyph_matrix (w->current_matrix);
6165 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6166 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6168 /* Compute width and height of the tooltip. */
6169 width = height = 0;
6170 seen_reversed_p = false;
6171 for (i = 0; i < w->desired_matrix->nrows; ++i)
6173 struct glyph_row *row = &w->desired_matrix->rows[i];
6174 struct glyph *last;
6175 int row_width;
6177 /* Stop at the first empty row at the end. */
6178 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6179 break;
6181 /* Let the row go over the full width of the frame. */
6182 row->full_width_p = true;
6184 row_width = row->pixel_width;
6185 if (row->used[TEXT_AREA])
6187 if (!row->reversed_p)
6189 /* There's a glyph at the end of rows that is used to
6190 place the cursor there. Don't include the width of
6191 this glyph. */
6192 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6193 if (NILP (last->object))
6194 row_width -= last->pixel_width;
6196 else
6198 /* There could be a stretch glyph at the beginning of R2L
6199 rows that is produced by extend_face_to_end_of_line.
6200 Don't count that glyph. */
6201 struct glyph *g = row->glyphs[TEXT_AREA];
6203 if (g->type == STRETCH_GLYPH && NILP (g->object))
6205 row_width -= g->pixel_width;
6206 seen_reversed_p = true;
6211 height += row->height;
6212 width = max (width, row_width);
6215 /* If we've seen partial-length R2L rows, we need to re-adjust the
6216 tool-tip frame width and redisplay it again, to avoid over-wide
6217 tips due to the stretch glyph that extends R2L lines to full
6218 width of the frame. */
6219 if (seen_reversed_p)
6221 /* PXW: Why do we do the pixel-to-cols conversion only if
6222 seen_reversed_p holds? Don't we have to set other fields of
6223 the window/frame structure?
6225 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6226 not in pixels. */
6227 w->pixel_width = width;
6228 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6229 w->total_cols = width;
6230 FRAME_TOTAL_COLS (f) = width;
6231 SET_FRAME_WIDTH (f, width);
6232 adjust_frame_glyphs (f);
6233 w->pseudo_window_p = 1;
6234 clear_glyph_matrix (w->desired_matrix);
6235 clear_glyph_matrix (w->current_matrix);
6236 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6237 width = height = 0;
6238 /* Recompute width and height of the tooltip. */
6239 for (i = 0; i < w->desired_matrix->nrows; ++i)
6241 struct glyph_row *row = &w->desired_matrix->rows[i];
6242 struct glyph *last;
6243 int row_width;
6245 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6246 break;
6247 row->full_width_p = true;
6248 row_width = row->pixel_width;
6249 if (row->used[TEXT_AREA] && !row->reversed_p)
6251 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6252 if (NILP (last->object))
6253 row_width -= last->pixel_width;
6256 height += row->height;
6257 width = max (width, row_width);
6261 /* Add the frame's internal border to the width and height the w32
6262 window should have. */
6263 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6264 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6266 /* Move the tooltip window where the mouse pointer is. Resize and
6267 show it.
6269 PXW: This should use the frame's pixel coordinates. */
6270 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6273 /* Adjust Window size to take border into account. */
6274 RECT rect;
6275 rect.left = rect.top = 0;
6276 rect.right = width;
6277 rect.bottom = height;
6278 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6279 FRAME_EXTERNAL_MENU_BAR (f));
6281 /* Position and size tooltip, and put it in the topmost group.
6282 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6283 peculiarity of w32 display: without it, some fonts cause the
6284 last character of the tip to be truncated or wrapped around to
6285 the next line. */
6286 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6287 root_x, root_y,
6288 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6289 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6291 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6292 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6293 0, 0, 0, 0,
6294 SWP_NOMOVE | SWP_NOSIZE
6295 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6297 /* Let redisplay know that we have made the frame visible already. */
6298 SET_FRAME_VISIBLE (f, 1);
6300 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6303 /* Draw into the window. */
6304 w->must_be_updated_p = true;
6305 update_single_window (w);
6307 unblock_input ();
6309 /* Restore original current buffer. */
6310 set_buffer_internal_1 (old_buffer);
6311 windows_or_buffers_changed = old_windows_or_buffers_changed;
6313 start_timer:
6314 /* Let the tip disappear after timeout seconds. */
6315 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6316 intern ("x-hide-tip"));
6318 UNGCPRO;
6319 return unbind_to (count, Qnil);
6323 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6324 doc: /* Hide the current tooltip window, if there is any.
6325 Value is t if tooltip was open, nil otherwise. */)
6326 (void)
6328 ptrdiff_t count;
6329 Lisp_Object deleted, frame, timer;
6330 struct gcpro gcpro1, gcpro2;
6332 /* Return quickly if nothing to do. */
6333 if (NILP (tip_timer) && NILP (tip_frame))
6334 return Qnil;
6336 frame = tip_frame;
6337 timer = tip_timer;
6338 GCPRO2 (frame, timer);
6339 tip_frame = tip_timer = deleted = Qnil;
6341 count = SPECPDL_INDEX ();
6342 specbind (Qinhibit_redisplay, Qt);
6343 specbind (Qinhibit_quit, Qt);
6345 if (!NILP (timer))
6346 call1 (Qcancel_timer, timer);
6348 if (FRAMEP (frame))
6350 delete_frame (frame, Qnil);
6351 deleted = Qt;
6354 UNGCPRO;
6355 return unbind_to (count, deleted);
6358 /***********************************************************************
6359 File selection dialog
6360 ***********************************************************************/
6362 #define FILE_NAME_TEXT_FIELD edt1
6363 #define FILE_NAME_COMBO_BOX cmb13
6364 #define FILE_NAME_LIST lst1
6366 /* Callback for altering the behavior of the Open File dialog.
6367 Makes the Filename text field contain "Current Directory" and be
6368 read-only when "Directories" is selected in the filter. This
6369 allows us to work around the fact that the standard Open File
6370 dialog does not support directories. */
6371 static UINT_PTR CALLBACK
6372 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6374 if (msg == WM_NOTIFY)
6376 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6377 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6378 int dropdown_changed;
6379 int dir_index;
6380 #ifdef NTGUI_UNICODE
6381 const int use_unicode = 1;
6382 #else /* !NTGUI_UNICODE */
6383 int use_unicode = w32_unicode_filenames;
6384 #endif /* NTGUI_UNICODE */
6386 /* Detect when the Filter dropdown is changed. */
6387 if (use_unicode)
6388 dropdown_changed =
6389 notify_w->hdr.code == CDN_TYPECHANGE
6390 || notify_w->hdr.code == CDN_INITDONE;
6391 else
6392 dropdown_changed =
6393 notify_a->hdr.code == CDN_TYPECHANGE
6394 || notify_a->hdr.code == CDN_INITDONE;
6395 if (dropdown_changed)
6397 HWND dialog = GetParent (hwnd);
6398 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6399 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6400 int hdr_code;
6402 /* At least on Windows 7, the above attempt to get the window handle
6403 to the File Name Text Field fails. The following code does the
6404 job though. Note that this code is based on my examination of the
6405 window hierarchy using Microsoft Spy++. bk */
6406 if (edit_control == NULL)
6408 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6409 if (tmp)
6411 tmp = GetWindow (tmp, GW_CHILD);
6412 if (tmp)
6413 edit_control = GetWindow (tmp, GW_CHILD);
6417 /* Directories is in index 2. */
6418 if (use_unicode)
6420 dir_index = notify_w->lpOFN->nFilterIndex;
6421 hdr_code = notify_w->hdr.code;
6423 else
6425 dir_index = notify_a->lpOFN->nFilterIndex;
6426 hdr_code = notify_a->hdr.code;
6428 if (dir_index == 2)
6430 if (use_unicode)
6431 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6432 (LPARAM)L"Current Directory");
6433 else
6434 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6435 (LPARAM)"Current Directory");
6436 EnableWindow (edit_control, FALSE);
6437 /* Note that at least on Windows 7, the above call to EnableWindow
6438 disables the window that would ordinarily have focus. If we
6439 do not set focus to some other window here, focus will land in
6440 no man's land and the user will be unable to tab through the
6441 dialog box (pressing tab will only result in a beep).
6442 Avoid that problem by setting focus to the list here. */
6443 if (hdr_code == CDN_INITDONE)
6444 SetFocus (list);
6446 else
6448 /* Don't override default filename on init done. */
6449 if (hdr_code == CDN_TYPECHANGE)
6451 if (use_unicode)
6452 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6453 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6454 else
6455 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6456 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6458 EnableWindow (edit_control, TRUE);
6462 return 0;
6465 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6466 doc: /* Read file name, prompting with PROMPT in directory DIR.
6467 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6468 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6469 or directory must exist.
6471 This function is only defined on NS, MS Windows, and X Windows with the
6472 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6473 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6474 On Windows 7 and later, the file selection dialog "remembers" the last
6475 directory where the user selected a file, and will open that directory
6476 instead of DIR on subsequent invocations of this function with the same
6477 value of DIR as in previous invocations; this is standard Windows behavior. */)
6478 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6480 /* Filter index: 1: All Files, 2: Directories only */
6481 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6482 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6484 Lisp_Object filename = default_filename;
6485 struct frame *f = SELECTED_FRAME ();
6486 BOOL file_opened = FALSE;
6487 Lisp_Object orig_dir = dir;
6488 Lisp_Object orig_prompt = prompt;
6490 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6491 compatibility) we end up with the old file dialogs. Define a big
6492 enough struct for the new dialog to trick GetOpenFileName into
6493 giving us the new dialogs on newer versions of Windows. */
6494 struct {
6495 OPENFILENAMEW details;
6496 #if _WIN32_WINNT < 0x500 /* < win2k */
6497 PVOID pvReserved;
6498 DWORD dwReserved;
6499 DWORD FlagsEx;
6500 #endif /* < win2k */
6501 } new_file_details_w;
6503 #ifdef NTGUI_UNICODE
6504 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6505 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6506 const int use_unicode = 1;
6507 #else /* not NTGUI_UNICODE */
6508 struct {
6509 OPENFILENAMEA details;
6510 #if _WIN32_WINNT < 0x500 /* < win2k */
6511 PVOID pvReserved;
6512 DWORD dwReserved;
6513 DWORD FlagsEx;
6514 #endif /* < win2k */
6515 } new_file_details_a;
6516 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6517 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6518 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6519 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6520 int use_unicode = w32_unicode_filenames;
6521 wchar_t *prompt_w;
6522 char *prompt_a;
6523 int len;
6524 char fname_ret[MAX_UTF8_PATH];
6525 #endif /* NTGUI_UNICODE */
6527 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
6528 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
6531 struct gcpro gcpro1, gcpro2;
6532 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
6534 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6535 system file encoding expected by the platform APIs (e.g. Cygwin's
6536 POSIX implementation) may not be the same as the encoding expected
6537 by the Windows "ANSI" APIs! */
6539 CHECK_STRING (prompt);
6540 CHECK_STRING (dir);
6542 dir = Fexpand_file_name (dir, Qnil);
6544 if (STRINGP (filename))
6545 filename = Ffile_name_nondirectory (filename);
6546 else
6547 filename = empty_unibyte_string;
6549 #ifdef CYGWIN
6550 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
6551 if (SCHARS (filename) > 0)
6552 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
6553 #endif
6555 CHECK_STRING (dir);
6556 CHECK_STRING (filename);
6558 /* The code in file_dialog_callback that attempts to set the text
6559 of the file name edit window when handling the CDN_INITDONE
6560 WM_NOTIFY message does not work. Setting filename to "Current
6561 Directory" in the only_dir_p case here does work however. */
6562 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6563 filename = build_string ("Current Directory");
6565 /* Convert the values we've computed so far to system form. */
6566 #ifdef NTGUI_UNICODE
6567 to_unicode (prompt, &prompt);
6568 to_unicode (dir, &dir);
6569 to_unicode (filename, &filename);
6570 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6571 report_file_error ("filename too long", default_filename);
6573 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
6574 #else /* !NTGUI_UNICODE */
6575 prompt = ENCODE_FILE (prompt);
6576 dir = ENCODE_FILE (dir);
6577 filename = ENCODE_FILE (filename);
6579 /* We modify these in-place, so make copies for safety. */
6580 dir = Fcopy_sequence (dir);
6581 unixtodos_filename (SDATA (dir));
6582 filename = Fcopy_sequence (filename);
6583 unixtodos_filename (SDATA (filename));
6584 if (SBYTES (filename) >= MAX_UTF8_PATH)
6585 report_file_error ("filename too long", default_filename);
6586 if (w32_unicode_filenames)
6588 filename_to_utf16 (SSDATA (dir), dir_w);
6589 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6591 /* filename_to_utf16 sets errno to ENOENT when the file
6592 name is too long or cannot be converted to UTF-16. */
6593 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6594 report_file_error ("filename too long", default_filename);
6596 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6597 SSDATA (prompt), -1, NULL, 0);
6598 if (len > 32768)
6599 len = 32768;
6600 prompt_w = alloca (len * sizeof (wchar_t));
6601 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6602 SSDATA (prompt), -1, prompt_w, len);
6604 else
6606 filename_to_ansi (SSDATA (dir), dir_a);
6607 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6609 /* filename_to_ansi sets errno to ENOENT when the file
6610 name is too long or cannot be converted to UTF-16. */
6611 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6612 report_file_error ("filename too long", default_filename);
6614 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6615 SSDATA (prompt), -1, NULL, 0);
6616 if (len > 32768)
6617 len = 32768;
6618 prompt_w = alloca (len * sizeof (wchar_t));
6619 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6620 SSDATA (prompt), -1, prompt_w, len);
6621 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
6622 if (len > 32768)
6623 len = 32768;
6624 prompt_a = alloca (len);
6625 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
6627 #endif /* NTGUI_UNICODE */
6629 /* Fill in the structure for the call to GetOpenFileName below.
6630 For NTGUI_UNICODE builds (which run only on NT), we just use
6631 the actual size of the structure. For non-NTGUI_UNICODE
6632 builds, we tell the OS we're using an old version of the
6633 structure if the OS isn't new enough to support the newer
6634 version. */
6635 if (use_unicode)
6637 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6638 if (w32_major_version > 4 && w32_major_version < 95)
6639 file_details_w->lStructSize = sizeof (new_file_details_w);
6640 else
6641 file_details_w->lStructSize = sizeof (*file_details_w);
6642 /* Set up the inout parameter for the selected file name. */
6643 file_details_w->lpstrFile = filename_buf_w;
6644 file_details_w->nMaxFile =
6645 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6646 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6647 /* Undocumented Bug in Common File Dialog:
6648 If a filter is not specified, shell links are not resolved. */
6649 file_details_w->lpstrFilter = filter_w;
6650 #ifdef NTGUI_UNICODE
6651 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
6652 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
6653 #else
6654 file_details_w->lpstrInitialDir = dir_w;
6655 file_details_w->lpstrTitle = prompt_w;
6656 #endif
6657 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6658 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6659 | OFN_EXPLORER | OFN_ENABLEHOOK);
6660 if (!NILP (mustmatch))
6662 /* Require that the path to the parent directory exists. */
6663 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6664 /* If we are looking for a file, require that it exists. */
6665 if (NILP (only_dir_p))
6666 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6669 #ifndef NTGUI_UNICODE
6670 else
6672 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6673 if (w32_major_version > 4 && w32_major_version < 95)
6674 file_details_a->lStructSize = sizeof (new_file_details_a);
6675 else
6676 file_details_a->lStructSize = sizeof (*file_details_a);
6677 file_details_a->lpstrFile = filename_buf_a;
6678 file_details_a->nMaxFile =
6679 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6680 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6681 file_details_a->lpstrFilter = filter_a;
6682 file_details_a->lpstrInitialDir = dir_a;
6683 file_details_a->lpstrTitle = prompt_a;
6684 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6685 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6686 | OFN_EXPLORER | OFN_ENABLEHOOK);
6687 if (!NILP (mustmatch))
6689 /* Require that the path to the parent directory exists. */
6690 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6691 /* If we are looking for a file, require that it exists. */
6692 if (NILP (only_dir_p))
6693 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6696 #endif /* !NTGUI_UNICODE */
6699 int count = SPECPDL_INDEX ();
6700 /* Prevent redisplay. */
6701 specbind (Qinhibit_redisplay, Qt);
6702 block_input ();
6703 if (use_unicode)
6705 file_details_w->lpfnHook = file_dialog_callback;
6707 file_opened = GetOpenFileNameW (file_details_w);
6709 #ifndef NTGUI_UNICODE
6710 else
6712 file_details_a->lpfnHook = file_dialog_callback;
6714 file_opened = GetOpenFileNameA (file_details_a);
6716 #endif /* !NTGUI_UNICODE */
6717 unblock_input ();
6718 unbind_to (count, Qnil);
6721 if (file_opened)
6723 /* Get an Emacs string from the value Windows gave us. */
6724 #ifdef NTGUI_UNICODE
6725 filename = from_unicode_buffer (filename_buf_w);
6726 #else /* !NTGUI_UNICODE */
6727 if (use_unicode)
6728 filename_from_utf16 (filename_buf_w, fname_ret);
6729 else
6730 filename_from_ansi (filename_buf_a, fname_ret);
6731 dostounix_filename (fname_ret);
6732 filename = DECODE_FILE (build_unibyte_string (fname_ret));
6733 #endif /* NTGUI_UNICODE */
6735 #ifdef CYGWIN
6736 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
6737 #endif /* CYGWIN */
6739 /* Strip the dummy filename off the end of the string if we
6740 added it to select a directory. */
6741 if ((use_unicode && file_details_w->nFilterIndex == 2)
6742 #ifndef NTGUI_UNICODE
6743 || (!use_unicode && file_details_a->nFilterIndex == 2)
6744 #endif
6746 filename = Ffile_name_directory (filename);
6748 /* User canceled the dialog without making a selection. */
6749 else if (!CommDlgExtendedError ())
6750 filename = Qnil;
6751 /* An error occurred, fallback on reading from the mini-buffer. */
6752 else
6753 filename = Fcompleting_read (
6754 orig_prompt,
6755 intern ("read-file-name-internal"),
6756 orig_dir,
6757 mustmatch,
6758 orig_dir,
6759 Qfile_name_history,
6760 default_filename,
6761 Qnil);
6763 UNGCPRO;
6766 /* Make "Cancel" equivalent to C-g. */
6767 if (NILP (filename))
6768 Fsignal (Qquit, Qnil);
6770 RETURN_UNGCPRO (filename);
6774 #ifdef WINDOWSNT
6775 /* Moving files to the system recycle bin.
6776 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6777 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6778 Ssystem_move_file_to_trash, 1, 1, 0,
6779 doc: /* Move file or directory named FILENAME to the recycle bin. */)
6780 (Lisp_Object filename)
6782 Lisp_Object handler;
6783 Lisp_Object encoded_file;
6784 Lisp_Object operation;
6786 operation = Qdelete_file;
6787 if (!NILP (Ffile_directory_p (filename))
6788 && NILP (Ffile_symlink_p (filename)))
6790 operation = intern ("delete-directory");
6791 filename = Fdirectory_file_name (filename);
6794 /* Must have fully qualified file names for moving files to Recycle
6795 Bin. */
6796 filename = Fexpand_file_name (filename, Qnil);
6798 handler = Ffind_file_name_handler (filename, operation);
6799 if (!NILP (handler))
6800 return call2 (handler, operation, filename);
6801 else
6803 const char * path;
6804 int result;
6806 encoded_file = ENCODE_FILE (filename);
6808 path = map_w32_filename (SDATA (encoded_file), NULL);
6810 /* The Unicode version of SHFileOperation is not supported on
6811 Windows 9X. */
6812 if (w32_unicode_filenames && os_subtype != OS_9X)
6814 SHFILEOPSTRUCTW file_op_w;
6815 /* We need one more element beyond MAX_PATH because this is
6816 a list of file names, with the last element double-null
6817 terminated. */
6818 wchar_t tmp_path_w[MAX_PATH + 1];
6820 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6821 filename_to_utf16 (path, tmp_path_w);
6823 /* On Windows, write permission is required to delete/move files. */
6824 _wchmod (tmp_path_w, 0666);
6826 memset (&file_op_w, 0, sizeof (file_op_w));
6827 file_op_w.hwnd = HWND_DESKTOP;
6828 file_op_w.wFunc = FO_DELETE;
6829 file_op_w.pFrom = tmp_path_w;
6830 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6831 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6832 file_op_w.fAnyOperationsAborted = FALSE;
6834 result = SHFileOperationW (&file_op_w);
6836 else
6838 SHFILEOPSTRUCTA file_op_a;
6839 char tmp_path_a[MAX_PATH + 1];
6841 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6842 filename_to_ansi (path, tmp_path_a);
6844 /* If a file cannot be represented in ANSI codepage, don't
6845 let them inadvertently delete other files because some
6846 characters are interpreted as a wildcards. */
6847 if (_mbspbrk (tmp_path_a, "?*"))
6848 result = ERROR_FILE_NOT_FOUND;
6849 else
6851 _chmod (tmp_path_a, 0666);
6853 memset (&file_op_a, 0, sizeof (file_op_a));
6854 file_op_a.hwnd = HWND_DESKTOP;
6855 file_op_a.wFunc = FO_DELETE;
6856 file_op_a.pFrom = tmp_path_a;
6857 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6858 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6859 file_op_a.fAnyOperationsAborted = FALSE;
6861 result = SHFileOperationA (&file_op_a);
6864 if (result != 0)
6865 report_file_error ("Removing old name", list1 (filename));
6867 return Qnil;
6870 #endif /* WINDOWSNT */
6873 /***********************************************************************
6874 w32 specialized functions
6875 ***********************************************************************/
6877 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6878 Sw32_send_sys_command, 1, 2, 0,
6879 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
6880 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
6881 to minimize), #xf120 to restore frame to original size, and #xf100
6882 to activate the menubar for keyboard access. #xf140 activates the
6883 screen saver if defined.
6885 If optional parameter FRAME is not specified, use selected frame. */)
6886 (Lisp_Object command, Lisp_Object frame)
6888 struct frame *f = decode_window_system_frame (frame);
6890 CHECK_NUMBER (command);
6892 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
6894 return Qnil;
6897 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
6898 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6899 This is a wrapper around the ShellExecute system function, which
6900 invokes the application registered to handle OPERATION for DOCUMENT.
6902 OPERATION is either nil or a string that names a supported operation.
6903 What operations can be used depends on the particular DOCUMENT and its
6904 handler application, but typically it is one of the following common
6905 operations:
6907 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6908 executable program (application). If it is an application,
6909 that application is launched in the current buffer's default
6910 directory. Otherwise, the application associated with
6911 DOCUMENT is launched in the buffer's default directory.
6912 \"opennew\" - like \"open\", but instruct the application to open
6913 DOCUMENT in a new window.
6914 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
6915 \"print\" - print DOCUMENT, which must be a file.
6916 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
6917 The printer should be provided in PARAMETERS, see below.
6918 \"explore\" - start the Windows Explorer on DOCUMENT.
6919 \"edit\" - launch an editor and open DOCUMENT for editing; which
6920 editor is launched depends on the association for the
6921 specified DOCUMENT.
6922 \"find\" - initiate search starting from DOCUMENT, which must specify
6923 a directory.
6924 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
6925 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
6926 the clipboard.
6927 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
6928 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
6929 which must be a directory.
6930 \"pastelink\"
6931 - create a shortcut in DOCUMENT (which must be a directory)
6932 the file or directory whose name is in the clipboard.
6933 \"runas\" - run DOCUMENT, which must be an excutable file, with
6934 elevated privileges (a.k.a. \"as Administrator\").
6935 \"properties\"
6936 - open the property sheet dialog for DOCUMENT.
6937 nil - invoke the default OPERATION, or \"open\" if default is
6938 not defined or unavailable.
6940 DOCUMENT is typically the name of a document file or a URL, but can
6941 also be an executable program to run, or a directory to open in the
6942 Windows Explorer. If it is a file or a directory, it must be a local
6943 one; this function does not support remote file names.
6945 If DOCUMENT is an executable program, the optional third arg PARAMETERS
6946 can be a string containing command line parameters, separated by blanks,
6947 that will be passed to the program. Some values of OPERATION also require
6948 parameters (e.g., \"printto\" requires the printer address). Otherwise,
6949 PARAMETERS should be nil or unspecified. Note that double quote characters
6950 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
6952 Optional fourth argument SHOW-FLAG can be used to control how the
6953 application will be displayed when it is invoked. If SHOW-FLAG is nil
6954 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
6955 specified, otherwise it is an integer between 0 and 11 representing
6956 a ShowWindow flag:
6958 0 - start hidden
6959 1 - start as normal-size window
6960 3 - start in a maximized window
6961 6 - start in a minimized window
6962 10 - start as the application itself specifies; this is the default. */)
6963 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
6965 char *errstr;
6966 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6967 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
6968 #ifdef CYGWIN
6969 intptr_t result;
6970 #else
6971 int use_unicode = w32_unicode_filenames;
6972 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
6973 Lisp_Object absdoc, handler;
6974 BOOL success;
6975 struct gcpro gcpro1;
6976 #endif
6978 CHECK_STRING (document);
6980 #ifdef CYGWIN
6981 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
6982 document = Fcygwin_convert_file_name_to_windows (document, Qt);
6984 /* Encode filename, current directory and parameters. */
6985 current_dir = GUI_ENCODE_FILE (current_dir);
6986 document = GUI_ENCODE_FILE (document);
6987 doc_w = GUI_SDATA (document);
6988 if (STRINGP (parameters))
6990 parameters = GUI_ENCODE_SYSTEM (parameters);
6991 params_w = GUI_SDATA (parameters);
6993 if (STRINGP (operation))
6995 operation = GUI_ENCODE_SYSTEM (operation);
6996 ops_w = GUI_SDATA (operation);
6998 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6999 GUI_SDATA (current_dir),
7000 (INTEGERP (show_flag)
7001 ? XINT (show_flag) : SW_SHOWDEFAULT));
7003 if (result > 32)
7004 return Qt;
7006 switch (result)
7008 case SE_ERR_ACCESSDENIED:
7009 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7010 break;
7011 case SE_ERR_ASSOCINCOMPLETE:
7012 case SE_ERR_NOASSOC:
7013 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7014 break;
7015 case SE_ERR_DDEBUSY:
7016 case SE_ERR_DDEFAIL:
7017 errstr = w32_strerror (ERROR_DDE_FAIL);
7018 break;
7019 case SE_ERR_DDETIMEOUT:
7020 errstr = w32_strerror (ERROR_TIMEOUT);
7021 break;
7022 case SE_ERR_DLLNOTFOUND:
7023 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7024 break;
7025 case SE_ERR_FNF:
7026 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7027 break;
7028 case SE_ERR_OOM:
7029 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7030 break;
7031 case SE_ERR_PNF:
7032 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7033 break;
7034 case SE_ERR_SHARE:
7035 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7036 break;
7037 default:
7038 errstr = w32_strerror (0);
7039 break;
7042 #else /* !CYGWIN */
7044 const char file_url_str[] = "file:///";
7045 const int file_url_len = sizeof (file_url_str) - 1;
7046 if (strncmp (SSDATA (document), file_url_str, file_url_len) == 0)
7048 /* Passing "file:///" URLs to ShellExecute causes shlwapi.dll to
7049 start a thread in some rare system configurations, for
7050 unknown reasons. That thread is started in the context of
7051 the Emacs process, but out of control of our code, and seems
7052 to never exit afterwards. Each such thread reserves 8MB of
7053 stack space (because that's the value recorded in the Emacs
7054 executable at link time: Emacs needs a large stack). So a
7055 large enough number of invocations of w32-shell-execute can
7056 potentially cause the Emacs process to run out of available
7057 address space, which is nasty. To work around this, we
7058 convert such URLs to local file names, which seems to prevent
7059 those threads from starting. See bug #20220. */
7060 char *p = SSDATA (document) + file_url_len;
7062 if (c_isalpha (*p) && p[1] == ':' && IS_DIRECTORY_SEP (p[2]))
7063 document = Fsubstring_no_properties (document,
7064 make_number (file_url_len), Qnil);
7066 /* We have a situation here. If DOCUMENT is a relative file name,
7067 but its name includes leading directories, i.e. it lives not in
7068 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7069 will fail to find it. So we need to make the file name is
7070 absolute. But DOCUMENT does not have to be a file, it can be a
7071 URL, for example. So we make it absolute only if it is an
7072 existing file; if it is a file that does not exist, tough. */
7073 GCPRO1 (absdoc);
7074 absdoc = Fexpand_file_name (document, Qnil);
7075 /* Don't call file handlers for file-exists-p, since they might
7076 attempt to access the file, which could fail or produce undesired
7077 consequences, see bug#16558 for an example. */
7078 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7079 if (NILP (handler))
7081 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7083 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7085 /* ShellExecute fails if DOCUMENT is a UNC with forward
7086 slashes (expand-file-name above converts all backslashes
7087 to forward slashes). Now that we know DOCUMENT is a
7088 file, we can mirror all forward slashes into backslashes. */
7089 unixtodos_filename (SSDATA (absdoc_encoded));
7090 document = absdoc_encoded;
7092 else
7093 document = ENCODE_FILE (document);
7095 else
7096 document = ENCODE_FILE (document);
7097 UNGCPRO;
7099 current_dir = ENCODE_FILE (current_dir);
7100 if (use_unicode)
7102 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
7103 SHELLEXECUTEINFOW shexinfo_w;
7105 /* Encode filename, current directory and parameters, and
7106 convert operation to UTF-16. */
7107 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7108 filename_to_utf16 (SSDATA (document), document_w);
7109 doc_w = document_w;
7110 if (STRINGP (parameters))
7112 int len;
7114 parameters = ENCODE_SYSTEM (parameters);
7115 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7116 SSDATA (parameters), -1, NULL, 0);
7117 if (len > 32768)
7118 len = 32768;
7119 params_w = alloca (len * sizeof (wchar_t));
7120 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7121 SSDATA (parameters), -1, params_w, len);
7123 if (STRINGP (operation))
7125 /* Assume OPERATION is pure ASCII. */
7126 const char *s = SSDATA (operation);
7127 wchar_t *d;
7128 int len = SBYTES (operation) + 1;
7130 if (len > 32768)
7131 len = 32768;
7132 d = ops_w = alloca (len * sizeof (wchar_t));
7133 while (d < ops_w + len - 1)
7134 *d++ = *s++;
7135 *d = 0;
7138 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7139 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7140 able to invoke verbs from shortcut menu extensions, not just
7141 static verbs listed in the Registry. */
7142 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7143 shexinfo_w.cbSize = sizeof (shexinfo_w);
7144 shexinfo_w.fMask =
7145 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7146 shexinfo_w.hwnd = NULL;
7147 shexinfo_w.lpVerb = ops_w;
7148 shexinfo_w.lpFile = doc_w;
7149 shexinfo_w.lpParameters = params_w;
7150 shexinfo_w.lpDirectory = current_dir_w;
7151 shexinfo_w.nShow =
7152 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7153 success = ShellExecuteExW (&shexinfo_w);
7155 else
7157 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7158 SHELLEXECUTEINFOA shexinfo_a;
7160 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7161 filename_to_ansi (SSDATA (document), document_a);
7162 doc_a = document_a;
7163 if (STRINGP (parameters))
7165 parameters = ENCODE_SYSTEM (parameters);
7166 params_a = SSDATA (parameters);
7168 if (STRINGP (operation))
7170 /* Assume OPERATION is pure ASCII. */
7171 ops_a = SSDATA (operation);
7173 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7174 shexinfo_a.cbSize = sizeof (shexinfo_a);
7175 shexinfo_a.fMask =
7176 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7177 shexinfo_a.hwnd = NULL;
7178 shexinfo_a.lpVerb = ops_a;
7179 shexinfo_a.lpFile = doc_a;
7180 shexinfo_a.lpParameters = params_a;
7181 shexinfo_a.lpDirectory = current_dir_a;
7182 shexinfo_a.nShow =
7183 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7184 success = ShellExecuteExA (&shexinfo_a);
7187 if (success)
7188 return Qt;
7190 errstr = w32_strerror (0);
7192 #endif /* !CYGWIN */
7194 /* The error string might be encoded in the locale's encoding. */
7195 if (!NILP (Vlocale_coding_system))
7197 Lisp_Object decoded =
7198 code_convert_string_norecord (build_unibyte_string (errstr),
7199 Vlocale_coding_system, 0);
7200 errstr = SSDATA (decoded);
7202 error ("ShellExecute failed: %s", errstr);
7205 /* Lookup virtual keycode from string representing the name of a
7206 non-ascii keystroke into the corresponding virtual key, using
7207 lispy_function_keys. */
7208 static int
7209 lookup_vk_code (char *key)
7211 int i;
7213 for (i = 0; i < 256; i++)
7214 if (lispy_function_keys[i]
7215 && strcmp (lispy_function_keys[i], key) == 0)
7216 return i;
7218 return -1;
7221 /* Convert a one-element vector style key sequence to a hot key
7222 definition. */
7223 static Lisp_Object
7224 w32_parse_hot_key (Lisp_Object key)
7226 /* Copied from Fdefine_key and store_in_keymap. */
7227 register Lisp_Object c;
7228 int vk_code;
7229 int lisp_modifiers;
7230 int w32_modifiers;
7231 struct gcpro gcpro1;
7233 CHECK_VECTOR (key);
7235 if (ASIZE (key) != 1)
7236 return Qnil;
7238 GCPRO1 (key);
7240 c = AREF (key, 0);
7242 if (CONSP (c) && lucid_event_type_list_p (c))
7243 c = Fevent_convert_list (c);
7245 UNGCPRO;
7247 if (! INTEGERP (c) && ! SYMBOLP (c))
7248 error ("Key definition is invalid");
7250 /* Work out the base key and the modifiers. */
7251 if (SYMBOLP (c))
7253 c = parse_modifiers (c);
7254 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7255 c = Fcar (c);
7256 if (!SYMBOLP (c))
7257 emacs_abort ();
7258 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7260 else if (INTEGERP (c))
7262 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7263 /* Many ascii characters are their own virtual key code. */
7264 vk_code = XINT (c) & CHARACTERBITS;
7267 if (vk_code < 0 || vk_code > 255)
7268 return Qnil;
7270 if ((lisp_modifiers & meta_modifier) != 0
7271 && !NILP (Vw32_alt_is_meta))
7272 lisp_modifiers |= alt_modifier;
7274 /* Supply defs missing from mingw32. */
7275 #ifndef MOD_ALT
7276 #define MOD_ALT 0x0001
7277 #define MOD_CONTROL 0x0002
7278 #define MOD_SHIFT 0x0004
7279 #define MOD_WIN 0x0008
7280 #endif
7282 /* Convert lisp modifiers to Windows hot-key form. */
7283 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7284 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7285 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7286 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7288 return HOTKEY (vk_code, w32_modifiers);
7291 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7292 Sw32_register_hot_key, 1, 1, 0,
7293 doc: /* Register KEY as a hot-key combination.
7294 Certain key combinations like Alt-Tab are reserved for system use on
7295 Windows, and therefore are normally intercepted by the system. However,
7296 most of these key combinations can be received by registering them as
7297 hot-keys, overriding their special meaning.
7299 KEY must be a one element key definition in vector form that would be
7300 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7301 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7302 is always interpreted as the Windows modifier keys.
7304 The return value is the hotkey-id if registered, otherwise nil. */)
7305 (Lisp_Object key)
7307 key = w32_parse_hot_key (key);
7309 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7311 /* Reuse an empty slot if possible. */
7312 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7314 /* Safe to add new key to list, even if we have focus. */
7315 if (NILP (item))
7316 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7317 else
7318 XSETCAR (item, key);
7320 /* Notify input thread about new hot-key definition, so that it
7321 takes effect without needing to switch focus. */
7322 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7323 (WPARAM) XINT (key), 0);
7326 return key;
7329 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7330 Sw32_unregister_hot_key, 1, 1, 0,
7331 doc: /* Unregister KEY as a hot-key combination. */)
7332 (Lisp_Object key)
7334 Lisp_Object item;
7336 if (!INTEGERP (key))
7337 key = w32_parse_hot_key (key);
7339 item = Fmemq (key, w32_grabbed_keys);
7341 if (!NILP (item))
7343 LPARAM lparam;
7345 eassert (CONSP (item));
7346 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
7347 so that it works in a --with-wide-int build as well. */
7348 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
7350 /* Notify input thread about hot-key definition being removed, so
7351 that it takes effect without needing focus switch. */
7352 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7353 (WPARAM) XINT (XCAR (item)), lparam))
7355 MSG msg;
7356 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7358 return Qt;
7360 return Qnil;
7363 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7364 Sw32_registered_hot_keys, 0, 0, 0,
7365 doc: /* Return list of registered hot-key IDs. */)
7366 (void)
7368 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7371 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7372 Sw32_reconstruct_hot_key, 1, 1, 0,
7373 doc: /* Convert hot-key ID to a lisp key combination.
7374 usage: (w32-reconstruct-hot-key ID) */)
7375 (Lisp_Object hotkeyid)
7377 int vk_code, w32_modifiers;
7378 Lisp_Object key;
7380 CHECK_NUMBER (hotkeyid);
7382 vk_code = HOTKEY_VK_CODE (hotkeyid);
7383 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7385 if (vk_code < 256 && lispy_function_keys[vk_code])
7386 key = intern (lispy_function_keys[vk_code]);
7387 else
7388 key = make_number (vk_code);
7390 key = Fcons (key, Qnil);
7391 if (w32_modifiers & MOD_SHIFT)
7392 key = Fcons (Qshift, key);
7393 if (w32_modifiers & MOD_CONTROL)
7394 key = Fcons (Qctrl, key);
7395 if (w32_modifiers & MOD_ALT)
7396 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7397 if (w32_modifiers & MOD_WIN)
7398 key = Fcons (Qhyper, key);
7400 return key;
7403 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7404 Sw32_toggle_lock_key, 1, 2, 0,
7405 doc: /* Toggle the state of the lock key KEY.
7406 KEY can be `capslock', `kp-numlock', or `scroll'.
7407 If the optional parameter NEW-STATE is a number, then the state of KEY
7408 is set to off if the low bit of NEW-STATE is zero, otherwise on.
7409 If NEW-STATE is omitted or nil, the function toggles the state,
7411 Value is the new state of the key, or nil if the function failed
7412 to change the state. */)
7413 (Lisp_Object key, Lisp_Object new_state)
7415 int vk_code;
7416 LPARAM lparam;
7418 if (EQ (key, intern ("capslock")))
7419 vk_code = VK_CAPITAL;
7420 else if (EQ (key, intern ("kp-numlock")))
7421 vk_code = VK_NUMLOCK;
7422 else if (EQ (key, intern ("scroll")))
7423 vk_code = VK_SCROLL;
7424 else
7425 return Qnil;
7427 if (!dwWindowsThreadId)
7428 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7430 if (NILP (new_state))
7431 lparam = -1;
7432 else
7433 lparam = (XUINT (new_state)) & 1;
7434 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7435 (WPARAM) vk_code, lparam))
7437 MSG msg;
7438 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7439 return make_number (msg.wParam);
7441 return Qnil;
7444 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7445 2, 2, 0,
7446 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7448 This is a direct interface to the Windows API FindWindow function. */)
7449 (Lisp_Object class, Lisp_Object name)
7451 HWND hnd;
7453 if (!NILP (class))
7454 CHECK_STRING (class);
7455 if (!NILP (name))
7456 CHECK_STRING (name);
7458 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7459 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7460 if (!hnd)
7461 return Qnil;
7462 return Qt;
7465 DEFUN ("w32-frame-menu-bar-size", Fw32_frame_menu_bar_size, Sw32_frame_menu_bar_size, 0, 1, 0,
7466 doc: /* Return sizes of menu bar on frame FRAME.
7467 The return value is a list of four elements: The current width and
7468 height of FRAME's menu bar in pixels, the height of one menu bar line in
7469 a wrapped menu bar in pixels, and the height of a single line menu bar
7470 in pixels.
7472 If FRAME is omitted or nil, the selected frame is used. */)
7473 (Lisp_Object frame)
7475 struct frame *f = decode_any_frame (frame);
7476 MENUBARINFO menu_bar;
7477 int width, height, single_height, wrapped_height;
7479 block_input ();
7481 single_height = GetSystemMetrics (SM_CYMENU);
7482 wrapped_height = GetSystemMetrics (SM_CYMENUSIZE);
7483 menu_bar.cbSize = sizeof (menu_bar);
7484 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
7485 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
7486 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
7487 width = menu_bar.rcBar.right - menu_bar.rcBar.left;
7488 height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
7490 unblock_input ();
7492 return list4 (make_number (width), make_number (height),
7493 make_number (wrapped_height), make_number (single_height));
7496 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7497 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7498 FRAME must be a live frame and defaults to the selected one.
7500 The boundary rectangle is a list of four elements, specifying the left,
7501 top, right and bottom screen coordinates of FRAME including menu and
7502 title bar and decorations. Optional argument CLIENT non-nil means to
7503 return the boundaries of the client rectangle which excludes menu and
7504 title bar and decorations. */)
7505 (Lisp_Object frame, Lisp_Object client)
7507 struct frame *f = decode_live_frame (frame);
7508 RECT rect;
7510 block_input ();
7512 if (!NILP (client))
7513 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7514 else
7515 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7517 unblock_input ();
7519 return list4 (make_number (rect.left), make_number (rect.top),
7520 make_number (rect.right), make_number (rect.bottom));
7523 DEFUN ("x-frame-geometry", Fx_frame_geometry, Sx_frame_geometry, 0, 1, 0,
7524 doc: /* Return geometric attributes of frame FRAME.
7525 FRAME must be a live frame and defaults to the selected one.
7527 The return value is an association list containing the following
7528 elements (all size values are in pixels).
7530 - `frame-outer-size' is a cons of the outer width and height of FRAME.
7531 The outer size includes the title bar and the external borders as well
7532 as any menu and/or tool bar of frame.
7534 - `border' is a cons of the horizontal and vertical width of FRAME's
7535 external borders.
7537 - `title-bar-height' is the height of the title bar of FRAME.
7539 - `menu-bar-external' if t means the menu bar is by default external
7540 (not included in the inner size of FRAME).
7542 - `menu-bar-size' is a cons of the width and height of the menu bar of
7543 FRAME.
7545 - `tool-bar-external' if t means the tool bar is by default external
7546 (not included in the inner size of FRAME).
7548 - `tool-bar-side' tells tells on which side the tool bar on FRAME is by
7549 default and can be one of `left', `top', `right' or `bottom'.
7551 - `tool-bar-size' is a cons of the width and height of the tool bar of
7552 FRAME.
7554 - `frame-inner-size' is a cons of the inner width and height of FRAME.
7555 This excludes FRAME's title bar and external border as well as any
7556 external menu and/or tool bar. */)
7557 (Lisp_Object frame)
7559 struct frame *f = decode_live_frame (frame);
7560 Lisp_Object geometry = Qnil;
7561 RECT frame_outer_edges, frame_inner_edges;
7562 MENUBARINFO menu_bar;
7563 int border_width, border_height, title_height;
7564 int single_bar_height, wrapped_bar_height, menu_bar_height;
7565 Lisp_Object fullscreen = Fframe_parameter (frame, Qfullscreen);
7567 block_input ();
7569 /* Outer frame rectangle, including outer borders and title bar. */
7570 GetWindowRect (FRAME_W32_WINDOW (f), &frame_outer_edges);
7571 /* Inner frame rectangle, excluding borders and title bar. */
7572 GetClientRect (FRAME_W32_WINDOW (f), &frame_inner_edges);
7573 /* Outer border. */
7574 border_width = GetSystemMetrics (SM_CXFRAME);
7575 border_height = GetSystemMetrics (SM_CYFRAME);
7576 /* Title bar. */
7577 title_height = GetSystemMetrics (SM_CYCAPTION);
7578 /* Menu bar. */
7579 menu_bar.cbSize = sizeof (menu_bar);
7580 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
7581 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
7582 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
7583 single_bar_height = GetSystemMetrics (SM_CYMENU);
7584 wrapped_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
7585 unblock_input ();
7587 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
7588 /* Fix menu bar height reported by GetMenuBarInfo. */
7589 if (menu_bar_height > single_bar_height)
7590 /* A wrapped menu bar. */
7591 menu_bar_height += single_bar_height - wrapped_bar_height;
7592 else if (menu_bar_height > 0)
7593 /* A single line menu bar. */
7594 menu_bar_height = single_bar_height;
7596 return
7597 listn (CONSTYPE_HEAP, 10,
7598 Fcons (Qframe_position,
7599 Fcons (make_number (frame_outer_edges.left),
7600 make_number (frame_outer_edges.top))),
7601 Fcons (Qframe_outer_size,
7602 Fcons (make_number
7603 (frame_outer_edges.right - frame_outer_edges.left),
7604 make_number
7605 (frame_outer_edges.bottom - frame_outer_edges.top))),
7606 Fcons (Qexternal_border_size,
7607 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
7608 ? Fcons (make_number (0), make_number (0))
7609 : Fcons (make_number (border_width),
7610 make_number (border_height)))),
7611 Fcons (Qtitle_height,
7612 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
7613 ? make_number (0)
7614 : make_number (title_height))),
7615 Fcons (Qmenu_bar_external, Qt),
7616 Fcons (Qmenu_bar_size,
7617 Fcons (make_number
7618 (menu_bar.rcBar.right - menu_bar.rcBar.left),
7619 make_number (menu_bar_height))),
7620 Fcons (Qtool_bar_external, Qnil),
7621 Fcons (Qtool_bar_position, Qtop),
7622 Fcons (Qtool_bar_size,
7623 Fcons (make_number (FRAME_TOOL_BAR_LINES (f)
7624 ? (FRAME_PIXEL_WIDTH (f)
7625 - 2 * FRAME_INTERNAL_BORDER_WIDTH (f))
7626 : 0),
7627 make_number (FRAME_TOOL_BAR_HEIGHT (f)))),
7628 Fcons (Qframe_inner_size,
7629 Fcons (make_number
7630 (frame_inner_edges.right - frame_inner_edges.left),
7631 make_number
7632 (frame_inner_edges.bottom - frame_inner_edges.top))));
7635 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7636 doc: /* Get power status information from Windows system.
7638 The following %-sequences are provided:
7639 %L AC line status (verbose)
7640 %B Battery status (verbose)
7641 %b Battery status, empty means high, `-' means low,
7642 `!' means critical, and `+' means charging
7643 %p Battery load percentage
7644 %s Remaining time (to charge or discharge) in seconds
7645 %m Remaining time (to charge or discharge) in minutes
7646 %h Remaining time (to charge or discharge) in hours
7647 %t Remaining time (to charge or discharge) in the form `h:min' */)
7648 (void)
7650 Lisp_Object status = Qnil;
7652 SYSTEM_POWER_STATUS system_status;
7653 if (GetSystemPowerStatus (&system_status))
7655 Lisp_Object line_status, battery_status, battery_status_symbol;
7656 Lisp_Object load_percentage, seconds, minutes, hours, remain;
7658 long seconds_left = (long) system_status.BatteryLifeTime;
7660 if (system_status.ACLineStatus == 0)
7661 line_status = build_string ("off-line");
7662 else if (system_status.ACLineStatus == 1)
7663 line_status = build_string ("on-line");
7664 else
7665 line_status = build_string ("N/A");
7667 if (system_status.BatteryFlag & 128)
7669 battery_status = build_string ("N/A");
7670 battery_status_symbol = empty_unibyte_string;
7672 else if (system_status.BatteryFlag & 8)
7674 battery_status = build_string ("charging");
7675 battery_status_symbol = build_string ("+");
7676 if (system_status.BatteryFullLifeTime != -1L)
7677 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7679 else if (system_status.BatteryFlag & 4)
7681 battery_status = build_string ("critical");
7682 battery_status_symbol = build_string ("!");
7684 else if (system_status.BatteryFlag & 2)
7686 battery_status = build_string ("low");
7687 battery_status_symbol = build_string ("-");
7689 else if (system_status.BatteryFlag & 1)
7691 battery_status = build_string ("high");
7692 battery_status_symbol = empty_unibyte_string;
7694 else
7696 battery_status = build_string ("medium");
7697 battery_status_symbol = empty_unibyte_string;
7700 if (system_status.BatteryLifePercent > 100)
7701 load_percentage = build_string ("N/A");
7702 else
7704 char buffer[16];
7705 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
7706 load_percentage = build_string (buffer);
7709 if (seconds_left < 0)
7710 seconds = minutes = hours = remain = build_string ("N/A");
7711 else
7713 long m;
7714 float h;
7715 char buffer[16];
7716 snprintf (buffer, 16, "%ld", seconds_left);
7717 seconds = build_string (buffer);
7719 m = seconds_left / 60;
7720 snprintf (buffer, 16, "%ld", m);
7721 minutes = build_string (buffer);
7723 h = seconds_left / 3600.0;
7724 snprintf (buffer, 16, "%3.1f", h);
7725 hours = build_string (buffer);
7727 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
7728 remain = build_string (buffer);
7731 status = listn (CONSTYPE_HEAP, 8,
7732 Fcons (make_number ('L'), line_status),
7733 Fcons (make_number ('B'), battery_status),
7734 Fcons (make_number ('b'), battery_status_symbol),
7735 Fcons (make_number ('p'), load_percentage),
7736 Fcons (make_number ('s'), seconds),
7737 Fcons (make_number ('m'), minutes),
7738 Fcons (make_number ('h'), hours),
7739 Fcons (make_number ('t'), remain));
7741 return status;
7745 #ifdef WINDOWSNT
7746 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
7747 doc: /* Return storage information about the file system FILENAME is on.
7748 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7749 storage of the file system, FREE is the free storage, and AVAIL is the
7750 storage available to a non-superuser. All 3 numbers are in bytes.
7751 If the underlying system call fails, value is nil. */)
7752 (Lisp_Object filename)
7754 Lisp_Object encoded, value;
7756 CHECK_STRING (filename);
7757 filename = Fexpand_file_name (filename, Qnil);
7758 encoded = ENCODE_FILE (filename);
7760 value = Qnil;
7762 /* Determining the required information on Windows turns out, sadly,
7763 to be more involved than one would hope. The original Windows API
7764 call for this will return bogus information on some systems, but we
7765 must dynamically probe for the replacement api, since that was
7766 added rather late on. */
7768 HMODULE hKernel = GetModuleHandle ("kernel32");
7769 BOOL (WINAPI *pfn_GetDiskFreeSpaceExW)
7770 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7771 = GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7772 BOOL (WINAPI *pfn_GetDiskFreeSpaceExA)
7773 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7774 = GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
7775 bool have_pfn_GetDiskFreeSpaceEx =
7776 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
7777 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
7779 /* On Windows, we may need to specify the root directory of the
7780 volume holding FILENAME. */
7781 char rootname[MAX_UTF8_PATH];
7782 wchar_t rootname_w[MAX_PATH];
7783 char rootname_a[MAX_PATH];
7784 char *name = SDATA (encoded);
7785 BOOL result;
7787 /* find the root name of the volume if given */
7788 if (isalpha (name[0]) && name[1] == ':')
7790 rootname[0] = name[0];
7791 rootname[1] = name[1];
7792 rootname[2] = '\\';
7793 rootname[3] = 0;
7795 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7797 char *str = rootname;
7798 int slashes = 4;
7801 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7802 break;
7803 *str++ = *name++;
7805 while ( *name );
7807 *str++ = '\\';
7808 *str = 0;
7811 if (w32_unicode_filenames)
7812 filename_to_utf16 (rootname, rootname_w);
7813 else
7814 filename_to_ansi (rootname, rootname_a);
7816 if (have_pfn_GetDiskFreeSpaceEx)
7818 /* Unsigned large integers cannot be cast to double, so
7819 use signed ones instead. */
7820 LARGE_INTEGER availbytes;
7821 LARGE_INTEGER freebytes;
7822 LARGE_INTEGER totalbytes;
7824 if (w32_unicode_filenames)
7825 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7826 (ULARGE_INTEGER *)&availbytes,
7827 (ULARGE_INTEGER *)&totalbytes,
7828 (ULARGE_INTEGER *)&freebytes);
7829 else
7830 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7831 (ULARGE_INTEGER *)&availbytes,
7832 (ULARGE_INTEGER *)&totalbytes,
7833 (ULARGE_INTEGER *)&freebytes);
7834 if (result)
7835 value = list3 (make_float ((double) totalbytes.QuadPart),
7836 make_float ((double) freebytes.QuadPart),
7837 make_float ((double) availbytes.QuadPart));
7839 else
7841 DWORD sectors_per_cluster;
7842 DWORD bytes_per_sector;
7843 DWORD free_clusters;
7844 DWORD total_clusters;
7846 if (w32_unicode_filenames)
7847 result = GetDiskFreeSpaceW (rootname_w,
7848 &sectors_per_cluster,
7849 &bytes_per_sector,
7850 &free_clusters,
7851 &total_clusters);
7852 else
7853 result = GetDiskFreeSpaceA (rootname_a,
7854 &sectors_per_cluster,
7855 &bytes_per_sector,
7856 &free_clusters,
7857 &total_clusters);
7858 if (result)
7859 value = list3 (make_float ((double) total_clusters
7860 * sectors_per_cluster * bytes_per_sector),
7861 make_float ((double) free_clusters
7862 * sectors_per_cluster * bytes_per_sector),
7863 make_float ((double) free_clusters
7864 * sectors_per_cluster * bytes_per_sector));
7868 return value;
7870 #endif /* WINDOWSNT */
7873 #ifdef WINDOWSNT
7874 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7875 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
7876 (void)
7878 static char pname_buf[256];
7879 int err;
7880 HANDLE hPrn;
7881 PRINTER_INFO_2W *ppi2w = NULL;
7882 PRINTER_INFO_2A *ppi2a = NULL;
7883 DWORD dwNeeded = 0, dwReturned = 0;
7884 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7885 char port_name[MAX_UTF8_PATH];
7887 /* Retrieve the default string from Win.ini (the registry).
7888 * String will be in form "printername,drivername,portname".
7889 * This is the most portable way to get the default printer. */
7890 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7891 return Qnil;
7892 /* printername precedes first "," character */
7893 strtok (pname_buf, ",");
7894 /* We want to know more than the printer name */
7895 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7896 return Qnil;
7897 /* GetPrinterW is not supported by unicows.dll. */
7898 if (w32_unicode_filenames && os_subtype != OS_9X)
7899 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7900 else
7901 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
7902 if (dwNeeded == 0)
7904 ClosePrinter (hPrn);
7905 return Qnil;
7907 /* Call GetPrinter again with big enough memory block. */
7908 if (w32_unicode_filenames && os_subtype != OS_9X)
7910 /* Allocate memory for the PRINTER_INFO_2 struct. */
7911 ppi2w = xmalloc (dwNeeded);
7912 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
7913 ClosePrinter (hPrn);
7914 if (!err)
7916 xfree (ppi2w);
7917 return Qnil;
7920 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7921 && ppi2w->pServerName)
7923 filename_from_utf16 (ppi2w->pServerName, server_name);
7924 filename_from_utf16 (ppi2w->pShareName, share_name);
7926 else
7928 server_name[0] = '\0';
7929 filename_from_utf16 (ppi2w->pPortName, port_name);
7932 else
7934 ppi2a = xmalloc (dwNeeded);
7935 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7936 ClosePrinter (hPrn);
7937 if (!err)
7939 xfree (ppi2a);
7940 return Qnil;
7943 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7944 && ppi2a->pServerName)
7946 filename_from_ansi (ppi2a->pServerName, server_name);
7947 filename_from_ansi (ppi2a->pShareName, share_name);
7949 else
7951 server_name[0] = '\0';
7952 filename_from_ansi (ppi2a->pPortName, port_name);
7956 if (server_name[0])
7958 /* a remote printer */
7959 if (server_name[0] == '\\')
7960 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7961 share_name);
7962 else
7963 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7964 share_name);
7965 pname_buf[sizeof (pname_buf) - 1] = '\0';
7967 else
7969 /* a local printer */
7970 strncpy (pname_buf, port_name, sizeof (pname_buf));
7971 pname_buf[sizeof (pname_buf) - 1] = '\0';
7972 /* `pPortName' can include several ports, delimited by ','.
7973 * we only use the first one. */
7974 strtok (pname_buf, ",");
7977 return DECODE_FILE (build_unibyte_string (pname_buf));
7979 #endif /* WINDOWSNT */
7982 /* Equivalent of strerror for W32 error codes. */
7983 char *
7984 w32_strerror (int error_no)
7986 static char buf[500];
7987 DWORD ret;
7989 if (error_no == 0)
7990 error_no = GetLastError ();
7992 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7993 FORMAT_MESSAGE_IGNORE_INSERTS,
7994 NULL,
7995 error_no,
7996 0, /* choose most suitable language */
7997 buf, sizeof (buf), NULL);
7999 while (ret > 0 && (buf[ret - 1] == '\n' ||
8000 buf[ret - 1] == '\r' ))
8001 --ret;
8002 buf[ret] = '\0';
8003 if (!ret)
8004 sprintf (buf, "w32 error %u", error_no);
8006 return buf;
8009 /* For convenience when debugging. (You cannot call GetLastError
8010 directly from GDB: it will crash, because it uses the __stdcall
8011 calling convention, not the _cdecl convention assumed by GDB.) */
8012 DWORD
8013 w32_last_error (void)
8015 return GetLastError ();
8018 /* Cache information describing the NT system for later use. */
8019 void
8020 cache_system_info (void)
8022 union
8024 struct info
8026 char major;
8027 char minor;
8028 short platform;
8029 } info;
8030 DWORD data;
8031 } version;
8033 /* Cache the module handle of Emacs itself. */
8034 hinst = GetModuleHandle (NULL);
8036 /* Cache the version of the operating system. */
8037 version.data = GetVersion ();
8038 w32_major_version = version.info.major;
8039 w32_minor_version = version.info.minor;
8041 if (version.info.platform & 0x8000)
8042 os_subtype = OS_9X;
8043 else
8044 os_subtype = OS_NT;
8046 /* Cache page size, allocation unit, processor type, etc. */
8047 GetSystemInfo (&sysinfo_cache);
8048 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
8050 /* Cache os info. */
8051 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
8052 GetVersionEx (&osinfo_cache);
8054 w32_build_number = osinfo_cache.dwBuildNumber;
8055 if (os_subtype == OS_9X)
8056 w32_build_number &= 0xffff;
8058 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
8061 #ifdef EMACSDEBUG
8062 void
8063 _DebPrint (const char *fmt, ...)
8065 char buf[1024];
8066 va_list args;
8068 va_start (args, fmt);
8069 vsprintf (buf, fmt, args);
8070 va_end (args);
8071 #if CYGWIN
8072 fprintf (stderr, "%s", buf);
8073 #endif
8074 OutputDebugString (buf);
8076 #endif
8079 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
8081 int cur_state = (GetKeyState (vk_code) & 1);
8083 if (NILP (new_state)
8084 || (NUMBERP (new_state)
8085 && ((XUINT (new_state)) & 1) != cur_state))
8087 #ifdef WINDOWSNT
8088 faked_key = vk_code;
8089 #endif /* WINDOWSNT */
8091 keybd_event ((BYTE) vk_code,
8092 (BYTE) MapVirtualKey (vk_code, 0),
8093 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8094 keybd_event ((BYTE) vk_code,
8095 (BYTE) MapVirtualKey (vk_code, 0),
8096 KEYEVENTF_EXTENDEDKEY | 0, 0);
8097 keybd_event ((BYTE) vk_code,
8098 (BYTE) MapVirtualKey (vk_code, 0),
8099 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8100 cur_state = !cur_state;
8103 return cur_state;
8106 /* Translate console modifiers to emacs modifiers.
8107 German keyboard support (Kai Morgan Zeise 2/18/95). */
8109 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
8111 int retval = 0;
8113 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
8114 pressed, first remove those modifiers. */
8115 if (!NILP (Vw32_recognize_altgr)
8116 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8117 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8118 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
8120 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
8121 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
8123 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8125 retval |= ctrl_modifier;
8126 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8127 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8128 retval |= meta_modifier;
8131 if (mods & LEFT_WIN_PRESSED)
8132 retval |= w32_key_to_modifier (VK_LWIN);
8133 if (mods & RIGHT_WIN_PRESSED)
8134 retval |= w32_key_to_modifier (VK_RWIN);
8135 if (mods & APPS_PRESSED)
8136 retval |= w32_key_to_modifier (VK_APPS);
8137 if (mods & SCROLLLOCK_ON)
8138 retval |= w32_key_to_modifier (VK_SCROLL);
8140 /* Just in case someone wanted the original behavior, make it
8141 optional by setting w32-capslock-is-shiftlock to t. */
8142 if (NILP (Vw32_capslock_is_shiftlock)
8143 /* Keys that should _not_ be affected by CapsLock. */
8144 && ( (key == VK_BACK)
8145 || (key == VK_TAB)
8146 || (key == VK_CLEAR)
8147 || (key == VK_RETURN)
8148 || (key == VK_ESCAPE)
8149 || ((key >= VK_SPACE) && (key <= VK_HELP))
8150 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
8151 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
8154 /* Only consider shift state. */
8155 if ((mods & SHIFT_PRESSED) != 0)
8156 retval |= shift_modifier;
8158 else
8160 /* Ignore CapsLock state if not enabled. */
8161 if (NILP (Vw32_enable_caps_lock))
8162 mods &= ~CAPSLOCK_ON;
8163 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
8164 retval |= shift_modifier;
8167 return retval;
8170 /* The return code indicates key code size. cpID is the codepage to
8171 use for translation to Unicode; -1 means use the current console
8172 input codepage. */
8174 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
8176 unsigned int key_code = event->wVirtualKeyCode;
8177 unsigned int mods = event->dwControlKeyState;
8178 BYTE keystate[256];
8179 static BYTE ansi_code[4];
8180 static int isdead = 0;
8182 if (isdead == 2)
8184 event->uChar.AsciiChar = ansi_code[2];
8185 isdead = 0;
8186 return 1;
8188 if (event->uChar.AsciiChar != 0)
8189 return 1;
8191 memset (keystate, 0, sizeof (keystate));
8192 keystate[key_code] = 0x80;
8193 if (mods & SHIFT_PRESSED)
8194 keystate[VK_SHIFT] = 0x80;
8195 if (mods & CAPSLOCK_ON)
8196 keystate[VK_CAPITAL] = 1;
8197 /* If we recognize right-alt and left-ctrl as AltGr, set the key
8198 states accordingly before invoking ToAscii. */
8199 if (!NILP (Vw32_recognize_altgr)
8200 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
8202 keystate[VK_CONTROL] = 0x80;
8203 keystate[VK_LCONTROL] = 0x80;
8204 keystate[VK_MENU] = 0x80;
8205 keystate[VK_RMENU] = 0x80;
8208 #if 0
8209 /* Because of an OS bug, ToAscii corrupts the stack when called to
8210 convert a dead key in console mode on NT4. Unfortunately, trying
8211 to check for dead keys using MapVirtualKey doesn't work either -
8212 these functions apparently use internal information about keyboard
8213 layout which doesn't get properly updated in console programs when
8214 changing layout (though apparently it gets partly updated,
8215 otherwise ToAscii wouldn't crash). */
8216 if (is_dead_key (event->wVirtualKeyCode))
8217 return 0;
8218 #endif
8220 /* On NT, call ToUnicode instead and then convert to the current
8221 console input codepage. */
8222 if (os_subtype == OS_NT)
8224 WCHAR buf[128];
8226 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
8227 keystate, buf, 128, 0);
8228 if (isdead > 0)
8230 /* When we are called from the GUI message processing code,
8231 we are passed the current keyboard codepage, a positive
8232 number, to use below. */
8233 if (cpId == -1)
8234 cpId = GetConsoleCP ();
8236 event->uChar.UnicodeChar = buf[isdead - 1];
8237 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8238 ansi_code, 4, NULL, NULL);
8240 else
8241 isdead = 0;
8243 else
8245 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8246 keystate, (LPWORD) ansi_code, 0);
8249 if (isdead == 0)
8250 return 0;
8251 event->uChar.AsciiChar = ansi_code[0];
8252 return isdead;
8256 void
8257 w32_sys_ring_bell (struct frame *f)
8259 if (sound_type == 0xFFFFFFFF)
8261 Beep (666, 100);
8263 else if (sound_type == MB_EMACS_SILENT)
8265 /* Do nothing. */
8267 else
8268 MessageBeep (sound_type);
8271 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
8272 0, 0, 0,
8273 doc: /* Return non-nil when a menu-bar menu is being used.
8274 Internal use only. */)
8275 (void)
8277 return menubar_in_use ? Qt : Qnil;
8281 /***********************************************************************
8282 Initialization
8283 ***********************************************************************/
8285 /* Keep this list in the same order as frame_parms in frame.c.
8286 Use 0 for unsupported frame parameters. */
8288 frame_parm_handler w32_frame_parm_handlers[] =
8290 x_set_autoraise,
8291 x_set_autolower,
8292 x_set_background_color,
8293 x_set_border_color,
8294 x_set_border_width,
8295 x_set_cursor_color,
8296 x_set_cursor_type,
8297 x_set_font,
8298 x_set_foreground_color,
8299 x_set_icon_name,
8300 x_set_icon_type,
8301 x_set_internal_border_width,
8302 x_set_right_divider_width,
8303 x_set_bottom_divider_width,
8304 x_set_menu_bar_lines,
8305 x_set_mouse_color,
8306 x_explicitly_set_name,
8307 x_set_scroll_bar_width,
8308 x_set_scroll_bar_height,
8309 x_set_title,
8310 x_set_unsplittable,
8311 x_set_vertical_scroll_bars,
8312 x_set_horizontal_scroll_bars,
8313 x_set_visibility,
8314 x_set_tool_bar_lines,
8315 0, /* x_set_scroll_bar_foreground, */
8316 0, /* x_set_scroll_bar_background, */
8317 x_set_screen_gamma,
8318 x_set_line_spacing,
8319 x_set_left_fringe,
8320 x_set_right_fringe,
8321 0, /* x_set_wait_for_wm, */
8322 x_set_fullscreen,
8323 x_set_font_backend,
8324 x_set_alpha,
8325 0, /* x_set_sticky */
8326 0, /* x_set_tool_bar_position */
8329 void
8330 syms_of_w32fns (void)
8332 globals_of_w32fns ();
8333 track_mouse_window = NULL;
8335 w32_visible_system_caret_hwnd = NULL;
8337 DEFSYM (Qundefined_color, "undefined-color");
8338 DEFSYM (Qcancel_timer, "cancel-timer");
8339 DEFSYM (Qhyper, "hyper");
8340 DEFSYM (Qsuper, "super");
8341 DEFSYM (Qmeta, "meta");
8342 DEFSYM (Qalt, "alt");
8343 DEFSYM (Qctrl, "ctrl");
8344 DEFSYM (Qcontrol, "control");
8345 DEFSYM (Qshift, "shift");
8346 DEFSYM (Qfont_param, "font-parameter");
8347 DEFSYM (Qgeometry, "geometry");
8348 DEFSYM (Qworkarea, "workarea");
8349 DEFSYM (Qmm_size, "mm-size");
8350 DEFSYM (Qframes, "frames");
8351 DEFSYM (Qtip_frame, "tip-frame");
8352 DEFSYM (Qunicode_sip, "unicode-sip");
8354 /* Symbols used elsewhere, but only in MS-Windows-specific code. */
8355 DEFSYM (Qgnutls_dll, "gnutls");
8356 DEFSYM (Qlibxml2_dll, "libxml2");
8357 DEFSYM (Qserif, "serif");
8358 DEFSYM (Qzlib_dll, "zlib");
8360 Fput (Qundefined_color, Qerror_conditions,
8361 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8362 Fput (Qundefined_color, Qerror_message,
8363 build_pure_c_string ("Undefined color"));
8365 staticpro (&w32_grabbed_keys);
8366 w32_grabbed_keys = Qnil;
8368 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8369 doc: /* An array of color name mappings for Windows. */);
8370 Vw32_color_map = Qnil;
8372 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8373 doc: /* Non-nil if Alt key presses are passed on to Windows.
8374 When non-nil, for example, Alt pressed and released and then space will
8375 open the System menu. When nil, Emacs processes the Alt key events, and
8376 then silently swallows them. */);
8377 Vw32_pass_alt_to_system = Qnil;
8379 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8380 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8381 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8382 Vw32_alt_is_meta = Qt;
8384 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8385 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8386 w32_quit_key = 0;
8388 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8389 Vw32_pass_lwindow_to_system,
8390 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8392 When non-nil, the Start menu is opened by tapping the key.
8393 If you set this to nil, the left \"Windows\" key is processed by Emacs
8394 according to the value of `w32-lwindow-modifier', which see.
8396 Note that some combinations of the left \"Windows\" key with other keys are
8397 caught by Windows at low level, and so binding them in Emacs will have no
8398 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8399 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8400 the doc string of `w32-phantom-key-code'. */);
8401 Vw32_pass_lwindow_to_system = Qt;
8403 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8404 Vw32_pass_rwindow_to_system,
8405 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8407 When non-nil, the Start menu is opened by tapping the key.
8408 If you set this to nil, the right \"Windows\" key is processed by Emacs
8409 according to the value of `w32-rwindow-modifier', which see.
8411 Note that some combinations of the right \"Windows\" key with other keys are
8412 caught by Windows at low level, and so binding them in Emacs will have no
8413 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8414 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8415 the doc string of `w32-phantom-key-code'. */);
8416 Vw32_pass_rwindow_to_system = Qt;
8418 DEFVAR_LISP ("w32-phantom-key-code",
8419 Vw32_phantom_key_code,
8420 doc: /* Virtual key code used to generate \"phantom\" key presses.
8421 Value is a number between 0 and 255.
8423 Phantom key presses are generated in order to stop the system from
8424 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8425 `w32-pass-rwindow-to-system' is nil. */);
8426 /* Although 255 is technically not a valid key code, it works and
8427 means that this hack won't interfere with any real key code. */
8428 XSETINT (Vw32_phantom_key_code, 255);
8430 DEFVAR_LISP ("w32-enable-num-lock",
8431 Vw32_enable_num_lock,
8432 doc: /* If non-nil, the Num Lock key acts normally.
8433 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8434 Vw32_enable_num_lock = Qt;
8436 DEFVAR_LISP ("w32-enable-caps-lock",
8437 Vw32_enable_caps_lock,
8438 doc: /* If non-nil, the Caps Lock key acts normally.
8439 Set to nil to handle Caps Lock as the `capslock' key. */);
8440 Vw32_enable_caps_lock = Qt;
8442 DEFVAR_LISP ("w32-scroll-lock-modifier",
8443 Vw32_scroll_lock_modifier,
8444 doc: /* Modifier to use for the Scroll Lock ON state.
8445 The value can be hyper, super, meta, alt, control or shift for the
8446 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8447 Any other value will cause the Scroll Lock key to be ignored. */);
8448 Vw32_scroll_lock_modifier = Qnil;
8450 DEFVAR_LISP ("w32-lwindow-modifier",
8451 Vw32_lwindow_modifier,
8452 doc: /* Modifier to use for the left \"Windows\" key.
8453 The value can be hyper, super, meta, alt, control or shift for the
8454 respective modifier, or nil to appear as the `lwindow' key.
8455 Any other value will cause the key to be ignored. */);
8456 Vw32_lwindow_modifier = Qnil;
8458 DEFVAR_LISP ("w32-rwindow-modifier",
8459 Vw32_rwindow_modifier,
8460 doc: /* Modifier to use for the right \"Windows\" key.
8461 The value can be hyper, super, meta, alt, control or shift for the
8462 respective modifier, or nil to appear as the `rwindow' key.
8463 Any other value will cause the key to be ignored. */);
8464 Vw32_rwindow_modifier = Qnil;
8466 DEFVAR_LISP ("w32-apps-modifier",
8467 Vw32_apps_modifier,
8468 doc: /* Modifier to use for the \"Apps\" key.
8469 The value can be hyper, super, meta, alt, control or shift for the
8470 respective modifier, or nil to appear as the `apps' key.
8471 Any other value will cause the key to be ignored. */);
8472 Vw32_apps_modifier = Qnil;
8474 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
8475 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8476 w32_enable_synthesized_fonts = 0;
8478 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
8479 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8480 Vw32_enable_palette = Qt;
8482 DEFVAR_INT ("w32-mouse-button-tolerance",
8483 w32_mouse_button_tolerance,
8484 doc: /* Analogue of double click interval for faking middle mouse events.
8485 The value is the minimum time in milliseconds that must elapse between
8486 left and right button down events before they are considered distinct events.
8487 If both mouse buttons are depressed within this interval, a middle mouse
8488 button down event is generated instead. */);
8489 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8491 DEFVAR_INT ("w32-mouse-move-interval",
8492 w32_mouse_move_interval,
8493 doc: /* Minimum interval between mouse move events.
8494 The value is the minimum time in milliseconds that must elapse between
8495 successive mouse move (or scroll bar drag) events before they are
8496 reported as lisp events. */);
8497 w32_mouse_move_interval = 0;
8499 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8500 w32_pass_extra_mouse_buttons_to_system,
8501 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8502 Recent versions of Windows support mice with up to five buttons.
8503 Since most applications don't support these extra buttons, most mouse
8504 drivers will allow you to map them to functions at the system level.
8505 If this variable is non-nil, Emacs will pass them on, allowing the
8506 system to handle them. */);
8507 w32_pass_extra_mouse_buttons_to_system = 0;
8509 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8510 w32_pass_multimedia_buttons_to_system,
8511 doc: /* If non-nil, media buttons are passed to Windows.
8512 Some modern keyboards contain buttons for controlling media players, web
8513 browsers and other applications. Generally these buttons are handled on a
8514 system wide basis, but by setting this to nil they are made available
8515 to Emacs for binding. Depending on your keyboard, additional keys that
8516 may be available are:
8518 browser-back, browser-forward, browser-refresh, browser-stop,
8519 browser-search, browser-favorites, browser-home,
8520 mail, mail-reply, mail-forward, mail-send,
8521 app-1, app-2,
8522 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8523 spell-check, correction-list, toggle-dictate-command,
8524 media-next, media-previous, media-stop, media-play-pause, media-select,
8525 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8526 media-channel-up, media-channel-down,
8527 volume-mute, volume-up, volume-down,
8528 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8529 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8530 w32_pass_multimedia_buttons_to_system = 1;
8532 #if 0 /* TODO: Mouse cursor customization. */
8533 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
8534 doc: /* The shape of the pointer when over text.
8535 Changing the value does not affect existing frames
8536 unless you set the mouse color. */);
8537 Vx_pointer_shape = Qnil;
8539 Vx_nontext_pointer_shape = Qnil;
8541 Vx_mode_pointer_shape = Qnil;
8543 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
8544 doc: /* The shape of the pointer when Emacs is busy.
8545 This variable takes effect when you create a new frame
8546 or when you set the mouse color. */);
8547 Vx_hourglass_pointer_shape = Qnil;
8549 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8550 Vx_sensitive_text_pointer_shape,
8551 doc: /* The shape of the pointer when over mouse-sensitive text.
8552 This variable takes effect when you create a new frame
8553 or when you set the mouse color. */);
8554 Vx_sensitive_text_pointer_shape = Qnil;
8556 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8557 Vx_window_horizontal_drag_shape,
8558 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8559 This variable takes effect when you create a new frame
8560 or when you set the mouse color. */);
8561 Vx_window_horizontal_drag_shape = Qnil;
8563 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8564 Vx_window_vertical_drag_shape,
8565 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8566 This variable takes effect when you create a new frame
8567 or when you set the mouse color. */);
8568 Vx_window_vertical_drag_shape = Qnil;
8569 #endif
8571 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
8572 doc: /* A string indicating the foreground color of the cursor box. */);
8573 Vx_cursor_fore_pixel = Qnil;
8575 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
8576 doc: /* Maximum size for tooltips.
8577 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8578 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8580 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
8581 doc: /* Non-nil if no window manager is in use.
8582 Emacs doesn't try to figure this out; this is always nil
8583 unless you set it to something else. */);
8584 /* We don't have any way to find this out, so set it to nil
8585 and maybe the user would like to set it to t. */
8586 Vx_no_window_manager = Qnil;
8588 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8589 Vx_pixel_size_width_font_regexp,
8590 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8592 Since Emacs gets width of a font matching with this regexp from
8593 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8594 such a font. This is especially effective for such large fonts as
8595 Chinese, Japanese, and Korean. */);
8596 Vx_pixel_size_width_font_regexp = Qnil;
8598 DEFVAR_LISP ("w32-bdf-filename-alist",
8599 Vw32_bdf_filename_alist,
8600 doc: /* List of bdf fonts and their corresponding filenames. */);
8601 Vw32_bdf_filename_alist = Qnil;
8603 DEFVAR_BOOL ("w32-strict-fontnames",
8604 w32_strict_fontnames,
8605 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8606 Default is nil, which allows old fontnames that are not XLFD compliant,
8607 and allows third-party CJK display to work by specifying false charset
8608 fields to trick Emacs into translating to Big5, SJIS etc.
8609 Setting this to t will prevent wrong fonts being selected when
8610 fontsets are automatically created. */);
8611 w32_strict_fontnames = 0;
8613 DEFVAR_BOOL ("w32-strict-painting",
8614 w32_strict_painting,
8615 doc: /* Non-nil means use strict rules for repainting frames.
8616 Set this to nil to get the old behavior for repainting; this should
8617 only be necessary if the default setting causes problems. */);
8618 w32_strict_painting = 1;
8620 #if 0 /* TODO: Port to W32 */
8621 defsubr (&Sx_change_window_property);
8622 defsubr (&Sx_delete_window_property);
8623 defsubr (&Sx_window_property);
8624 #endif
8625 defsubr (&Sxw_display_color_p);
8626 defsubr (&Sx_display_grayscale_p);
8627 defsubr (&Sxw_color_defined_p);
8628 defsubr (&Sxw_color_values);
8629 defsubr (&Sx_server_max_request_size);
8630 defsubr (&Sx_server_vendor);
8631 defsubr (&Sx_server_version);
8632 defsubr (&Sx_display_pixel_width);
8633 defsubr (&Sx_display_pixel_height);
8634 defsubr (&Sx_display_mm_width);
8635 defsubr (&Sx_display_mm_height);
8636 defsubr (&Sx_display_screens);
8637 defsubr (&Sx_display_planes);
8638 defsubr (&Sx_display_color_cells);
8639 defsubr (&Sx_display_visual_class);
8640 defsubr (&Sx_display_backing_store);
8641 defsubr (&Sx_display_save_under);
8642 defsubr (&Sx_create_frame);
8643 defsubr (&Sx_open_connection);
8644 defsubr (&Sx_close_connection);
8645 defsubr (&Sx_display_list);
8646 defsubr (&Sx_frame_geometry);
8647 defsubr (&Sx_synchronize);
8649 /* W32 specific functions */
8651 defsubr (&Sw32_define_rgb_color);
8652 defsubr (&Sw32_default_color_map);
8653 defsubr (&Sw32_display_monitor_attributes_list);
8654 defsubr (&Sw32_send_sys_command);
8655 defsubr (&Sw32_shell_execute);
8656 defsubr (&Sw32_register_hot_key);
8657 defsubr (&Sw32_unregister_hot_key);
8658 defsubr (&Sw32_registered_hot_keys);
8659 defsubr (&Sw32_reconstruct_hot_key);
8660 defsubr (&Sw32_toggle_lock_key);
8661 defsubr (&Sw32_window_exists_p);
8662 defsubr (&Sw32_frame_rect);
8663 defsubr (&Sw32_frame_menu_bar_size);
8664 defsubr (&Sw32_battery_status);
8665 defsubr (&Sw32__menu_bar_in_use);
8667 #ifdef WINDOWSNT
8668 defsubr (&Sfile_system_info);
8669 defsubr (&Sdefault_printer_name);
8670 #endif
8672 defsubr (&Sset_message_beep);
8673 defsubr (&Sx_show_tip);
8674 defsubr (&Sx_hide_tip);
8675 tip_timer = Qnil;
8676 staticpro (&tip_timer);
8677 tip_frame = Qnil;
8678 staticpro (&tip_frame);
8680 last_show_tip_args = Qnil;
8681 staticpro (&last_show_tip_args);
8683 defsubr (&Sx_file_dialog);
8684 #ifdef WINDOWSNT
8685 defsubr (&Ssystem_move_file_to_trash);
8686 #endif
8691 /* Crashing and reporting backtrace. */
8693 #ifndef CYGWIN
8694 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8695 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8696 #endif
8697 static DWORD except_code;
8698 static PVOID except_addr;
8700 #ifndef CYGWIN
8701 /* This handler records the exception code and the address where it
8702 was triggered so that this info could be included in the backtrace.
8703 Without that, the backtrace in some cases has no information
8704 whatsoever about the offending code, and looks as if the top-level
8705 exception handler in the MinGW startup code di the one that
8706 crashed. */
8707 static LONG CALLBACK
8708 my_exception_handler (EXCEPTION_POINTERS * exception_data)
8710 except_code = exception_data->ExceptionRecord->ExceptionCode;
8711 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8713 if (prev_exception_handler)
8714 return prev_exception_handler (exception_data);
8715 return EXCEPTION_EXECUTE_HANDLER;
8717 #endif
8719 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8720 PULONG);
8722 #define BACKTRACE_LIMIT_MAX 62
8725 w32_backtrace (void **buffer, int limit)
8727 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8728 HMODULE hm_kernel32 = NULL;
8730 if (!s_pfn_CaptureStackBackTrace)
8732 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8733 s_pfn_CaptureStackBackTrace =
8734 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8735 "RtlCaptureStackBackTrace");
8737 if (s_pfn_CaptureStackBackTrace)
8738 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8739 buffer, NULL);
8740 return 0;
8743 void
8744 emacs_abort (void)
8746 int button;
8747 button = MessageBox (NULL,
8748 "A fatal error has occurred!\n\n"
8749 "Would you like to attach a debugger?\n\n"
8750 "Select:\n"
8751 "YES -- to debug Emacs, or\n"
8752 "NO -- to abort Emacs and produce a backtrace\n"
8753 " (emacs_backtrace.txt in current directory)."
8754 #if __GNUC__
8755 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8756 "\"continue\" inside GDB before clicking YES.)"
8757 #endif
8758 , "Emacs Abort Dialog",
8759 MB_ICONEXCLAMATION | MB_TASKMODAL
8760 | MB_SETFOREGROUND | MB_YESNO);
8761 switch (button)
8763 case IDYES:
8764 DebugBreak ();
8765 exit (2); /* tell the compiler we will never return */
8766 case IDNO:
8767 default:
8769 void *stack[BACKTRACE_LIMIT_MAX + 1];
8770 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8772 if (i)
8774 int errfile_fd = -1;
8775 int j;
8776 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
8777 /* The type below should really be 'void *', but
8778 INT_BUFSIZE_BOUND cannot handle that without
8779 triggering compiler warnings (under certain
8780 pedantic warning switches), it wants an
8781 integer type. */
8782 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
8783 #ifdef CYGWIN
8784 int stderr_fd = 2;
8785 #else
8786 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
8787 int stderr_fd = -1;
8789 if (errout && errout != INVALID_HANDLE_VALUE)
8790 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
8791 #endif
8793 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8794 but not on Windows 7. addr2line doesn't mind a missing
8795 "0x", but will be confused by an extra one. */
8796 if (except_addr)
8797 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8798 except_code, except_addr);
8799 if (stderr_fd >= 0)
8801 if (except_addr)
8802 write (stderr_fd, buf, strlen (buf));
8803 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8805 #ifdef CYGWIN
8806 #define _open open
8807 #endif
8808 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8809 if (errfile_fd >= 0)
8811 lseek (errfile_fd, 0L, SEEK_END);
8812 if (except_addr)
8813 write (errfile_fd, buf, strlen (buf));
8814 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8817 for (j = 0; j < i; j++)
8819 /* stack[] gives the return addresses, whereas we want
8820 the address of the call, so decrease each address
8821 by approximate size of 1 CALL instruction. */
8822 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
8823 if (stderr_fd >= 0)
8824 write (stderr_fd, buf, strlen (buf));
8825 if (errfile_fd >= 0)
8826 write (errfile_fd, buf, strlen (buf));
8828 if (i == BACKTRACE_LIMIT_MAX)
8830 if (stderr_fd >= 0)
8831 write (stderr_fd, "...\r\n", 5);
8832 if (errfile_fd >= 0)
8833 write (errfile_fd, "...\r\n", 5);
8835 if (errfile_fd >= 0)
8836 close (errfile_fd);
8838 abort ();
8839 break;
8846 /* Initialization. */
8849 globals_of_w32fns is used to initialize those global variables that
8850 must always be initialized on startup even when the global variable
8851 initialized is non zero (see the function main in emacs.c).
8852 globals_of_w32fns is called from syms_of_w32fns when the global
8853 variable initialized is 0 and directly from main when initialized
8854 is non zero.
8856 void
8857 globals_of_w32fns (void)
8859 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8861 TrackMouseEvent not available in all versions of Windows, so must load
8862 it dynamically. Do it once, here, instead of every time it is used.
8864 track_mouse_event_fn = (TrackMouseEvent_Proc)
8865 GetProcAddress (user32_lib, "TrackMouseEvent");
8867 monitor_from_point_fn = (MonitorFromPoint_Proc)
8868 GetProcAddress (user32_lib, "MonitorFromPoint");
8869 get_monitor_info_fn = (GetMonitorInfo_Proc)
8870 GetProcAddress (user32_lib, "GetMonitorInfoA");
8871 monitor_from_window_fn = (MonitorFromWindow_Proc)
8872 GetProcAddress (user32_lib, "MonitorFromWindow");
8873 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8874 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8877 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8878 get_composition_string_fn = (ImmGetCompositionString_Proc)
8879 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8880 get_ime_context_fn = (ImmGetContext_Proc)
8881 GetProcAddress (imm32_lib, "ImmGetContext");
8882 release_ime_context_fn = (ImmReleaseContext_Proc)
8883 GetProcAddress (imm32_lib, "ImmReleaseContext");
8884 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8885 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8888 except_code = 0;
8889 except_addr = 0;
8890 #ifndef CYGWIN
8891 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8892 #endif
8894 DEFVAR_INT ("w32-ansi-code-page",
8895 w32_ansi_code_page,
8896 doc: /* The ANSI code page used by the system. */);
8897 w32_ansi_code_page = GetACP ();
8899 if (os_subtype == OS_NT)
8900 w32_unicode_gui = 1;
8901 else
8902 w32_unicode_gui = 0;
8904 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8905 InitCommonControls ();
8907 syms_of_w32uniscribe ();
8910 #ifdef NTGUI_UNICODE
8912 Lisp_Object
8913 ntgui_encode_system (Lisp_Object str)
8915 Lisp_Object encoded;
8916 to_unicode (str, &encoded);
8917 return encoded;
8920 #endif /* NTGUI_UNICODE */