Try non-scaled xld fonts first, and scaled if that failed.
[emacs.git] / src / w32fns.c
blob08000d87d381471fa70631ea049144e975d2f906
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 "lisp.h"
33 #include "w32term.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "character.h"
37 #include "buffer.h"
38 #include "intervals.h"
39 #include "dispextern.h"
40 #include "keyboard.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "charset.h"
44 #include "coding.h"
45 #include "ccl.h"
46 #include "fontset.h"
47 #include "systime.h"
48 #include "termhooks.h"
50 #include "w32common.h"
52 #ifdef WINDOWSNT
53 #include "w32heap.h"
54 #include <mbstring.h>
55 #endif /* WINDOWSNT */
57 #if CYGWIN
58 #include "cygw32.h"
59 #else
60 #include "w32.h"
61 #endif
63 #include "bitmaps/gray.xbm"
65 #include <commctrl.h>
66 #include <commdlg.h>
67 #include <shellapi.h>
68 #include <ctype.h>
69 #include <winspool.h>
70 #include <objbase.h>
72 #include <dlgs.h>
73 #include <imm.h>
75 #include "font.h"
76 #include "w32font.h"
78 #ifndef FOF_NO_CONNECTED_ELEMENTS
79 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
80 #endif
82 void syms_of_w32fns (void);
83 void globals_of_w32fns (void);
85 extern void free_frame_menubar (struct frame *);
86 extern int w32_console_toggle_lock_key (int, Lisp_Object);
87 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
88 extern void w32_free_menu_strings (HWND);
89 extern const char *map_w32_filename (const char *, const char **);
90 extern char * w32_strerror (int error_no);
92 #ifndef IDC_HAND
93 #define IDC_HAND MAKEINTRESOURCE(32649)
94 #endif
96 /* Prefix for system colors. */
97 #define SYSTEM_COLOR_PREFIX "System"
98 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
100 /* State variables for emulating a three button mouse. */
101 #define LMOUSE 1
102 #define MMOUSE 2
103 #define RMOUSE 4
105 static int button_state = 0;
106 static W32Msg saved_mouse_button_msg;
107 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
108 static W32Msg saved_mouse_move_msg;
109 static unsigned mouse_move_timer = 0;
111 /* Window that is tracking the mouse. */
112 static HWND track_mouse_window;
114 /* Multi-monitor API definitions that are not pulled from the headers
115 since we are compiling for NT 4. */
116 #ifndef MONITOR_DEFAULT_TO_NEAREST
117 #define MONITOR_DEFAULT_TO_NEAREST 2
118 #endif
119 #ifndef MONITORINFOF_PRIMARY
120 #define MONITORINFOF_PRIMARY 1
121 #endif
122 #ifndef SM_XVIRTUALSCREEN
123 #define SM_XVIRTUALSCREEN 76
124 #endif
125 #ifndef SM_YVIRTUALSCREEN
126 #define SM_YVIRTUALSCREEN 77
127 #endif
128 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
129 To avoid a compile error on one or the other, redefine with a new name. */
130 struct MONITOR_INFO
132 DWORD cbSize;
133 RECT rcMonitor;
134 RECT rcWork;
135 DWORD dwFlags;
138 #ifndef CCHDEVICENAME
139 #define CCHDEVICENAME 32
140 #endif
141 struct MONITOR_INFO_EX
143 DWORD cbSize;
144 RECT rcMonitor;
145 RECT rcWork;
146 DWORD dwFlags;
147 char szDevice[CCHDEVICENAME];
150 /* Reportedly, MSVC does not have this in its headers. */
151 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
152 DECLARE_HANDLE(HMONITOR);
153 #endif
155 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
156 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
157 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
158 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
159 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
160 typedef HWND (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
161 typedef HWND (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
162 IN COMPOSITIONFORM *form);
163 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
164 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
165 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
166 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
167 (IN HWND hwnd, IN DWORD dwFlags);
168 typedef BOOL CALLBACK (* MonitorEnum_Proc)
169 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
170 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
171 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
173 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
174 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
175 ImmGetContext_Proc get_ime_context_fn = NULL;
176 ImmReleaseContext_Proc release_ime_context_fn = NULL;
177 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
178 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
179 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
180 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
181 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
183 #ifdef NTGUI_UNICODE
184 #define unicode_append_menu AppendMenuW
185 #else /* !NTGUI_UNICODE */
186 extern AppendMenuW_Proc unicode_append_menu;
187 #endif /* NTGUI_UNICODE */
189 /* Flag to selectively ignore WM_IME_CHAR messages. */
190 static int ignore_ime_char = 0;
192 /* W95 mousewheel handler */
193 unsigned int msh_mousewheel = 0;
195 /* Timers */
196 #define MOUSE_BUTTON_ID 1
197 #define MOUSE_MOVE_ID 2
198 #define MENU_FREE_ID 3
199 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
200 is received. */
201 #define MENU_FREE_DELAY 1000
202 static unsigned menu_free_timer = 0;
204 #ifdef GLYPH_DEBUG
205 static int image_cache_refcount, dpyinfo_refcount;
206 #endif
208 static HWND w32_visible_system_caret_hwnd;
210 static int w32_unicode_gui;
212 /* From w32menu.c */
213 extern HMENU current_popup_menu;
214 int menubar_in_use = 0;
216 /* From w32uniscribe.c */
217 extern void syms_of_w32uniscribe (void);
218 extern int uniscribe_available;
220 #ifdef WINDOWSNT
221 /* From w32inevt.c */
222 extern int faked_key;
223 #endif /* WINDOWSNT */
225 /* This gives us the page size and the size of the allocation unit on NT. */
226 SYSTEM_INFO sysinfo_cache;
228 /* This gives us version, build, and platform identification. */
229 OSVERSIONINFO osinfo_cache;
231 DWORD_PTR syspage_mask = 0;
233 /* The major and minor versions of NT. */
234 int w32_major_version;
235 int w32_minor_version;
236 int w32_build_number;
238 /* Distinguish between Windows NT and Windows 95. */
239 int os_subtype;
241 #ifdef HAVE_NTGUI
242 HINSTANCE hinst = NULL;
243 #endif
245 static unsigned int sound_type = 0xFFFFFFFF;
246 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
248 /* Let the user specify a display with a frame.
249 nil stands for the selected frame--or, if that is not a w32 frame,
250 the first display on the list. */
252 struct w32_display_info *
253 check_x_display_info (Lisp_Object object)
255 if (NILP (object))
257 struct frame *sf = XFRAME (selected_frame);
259 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
260 return FRAME_DISPLAY_INFO (sf);
261 else
262 return &one_w32_display_info;
264 else if (TERMINALP (object))
266 struct terminal *t = decode_live_terminal (object);
268 if (t->type != output_w32)
269 error ("Terminal %d is not a W32 display", t->id);
271 return t->display_info.w32;
273 else if (STRINGP (object))
274 return x_display_info_for_name (object);
275 else
277 struct frame *f;
279 CHECK_LIVE_FRAME (object);
280 f = XFRAME (object);
281 if (! FRAME_W32_P (f))
282 error ("Non-W32 frame used");
283 return FRAME_DISPLAY_INFO (f);
287 /* Return the Emacs frame-object corresponding to an w32 window.
288 It could be the frame's main window or an icon window. */
290 struct frame *
291 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
293 Lisp_Object tail, frame;
294 struct frame *f;
296 FOR_EACH_FRAME (tail, frame)
298 f = XFRAME (frame);
299 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
300 continue;
302 if (FRAME_W32_WINDOW (f) == wdesc)
303 return f;
305 return 0;
309 static Lisp_Object unwind_create_frame (Lisp_Object);
310 static void unwind_create_tip_frame (Lisp_Object);
311 static void my_create_window (struct frame *);
312 static void my_create_tip_window (struct frame *);
314 /* TODO: Native Input Method support; see x_create_im. */
315 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
316 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
317 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
318 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
319 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
320 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
321 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
322 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
323 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
324 void x_set_menu_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
325 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
326 void x_set_tool_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
327 void x_set_internal_border_width (struct frame *f, Lisp_Object, Lisp_Object);
330 /* Store the screen positions of frame F into XPTR and YPTR.
331 These are the positions of the containing window manager window,
332 not Emacs's own window. */
334 void
335 x_real_positions (struct frame *f, int *xptr, int *yptr)
337 POINT pt;
338 RECT rect;
340 /* Get the bounds of the WM window. */
341 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
343 pt.x = 0;
344 pt.y = 0;
346 /* Convert (0, 0) in the client area to screen co-ordinates. */
347 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
349 /* Remember x_pixels_diff and y_pixels_diff. */
350 f->x_pixels_diff = pt.x - rect.left;
351 f->y_pixels_diff = pt.y - rect.top;
353 *xptr = rect.left;
354 *yptr = rect.top;
357 /* Returns the window rectangle appropriate for the given fullscreen mode.
358 The normal rect parameter was the window's rectangle prior to entering
359 fullscreen mode. If multiple monitor support is available, the nearest
360 monitor to the window is chosen. */
362 void
363 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
365 struct MONITOR_INFO mi = { sizeof(mi) };
366 if (monitor_from_window_fn && get_monitor_info_fn)
368 HMONITOR monitor =
369 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
370 get_monitor_info_fn (monitor, &mi);
372 else
374 mi.rcMonitor.left = 0;
375 mi.rcMonitor.top = 0;
376 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
377 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
378 mi.rcWork.left = 0;
379 mi.rcWork.top = 0;
380 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
381 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
384 switch (fsmode)
386 case FULLSCREEN_BOTH:
387 rect->left = mi.rcMonitor.left;
388 rect->top = mi.rcMonitor.top;
389 rect->right = mi.rcMonitor.right;
390 rect->bottom = mi.rcMonitor.bottom;
391 break;
392 case FULLSCREEN_WIDTH:
393 rect->left = mi.rcWork.left;
394 rect->top = normal.top;
395 rect->right = mi.rcWork.right;
396 rect->bottom = normal.bottom;
397 break;
398 case FULLSCREEN_HEIGHT:
399 rect->left = normal.left;
400 rect->top = mi.rcWork.top;
401 rect->right = normal.right;
402 rect->bottom = mi.rcWork.bottom;
403 break;
404 default:
405 *rect = normal;
406 break;
412 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
413 Sw32_define_rgb_color, 4, 4, 0,
414 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
415 This adds or updates a named color to `w32-color-map', making it
416 available for use. The original entry's RGB ref is returned, or nil
417 if the entry is new. */)
418 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
420 Lisp_Object rgb;
421 Lisp_Object oldrgb = Qnil;
422 Lisp_Object entry;
424 CHECK_NUMBER (red);
425 CHECK_NUMBER (green);
426 CHECK_NUMBER (blue);
427 CHECK_STRING (name);
429 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
431 block_input ();
433 /* replace existing entry in w32-color-map or add new entry. */
434 entry = Fassoc (name, Vw32_color_map);
435 if (NILP (entry))
437 entry = Fcons (name, rgb);
438 Vw32_color_map = Fcons (entry, Vw32_color_map);
440 else
442 oldrgb = Fcdr (entry);
443 Fsetcdr (entry, rgb);
446 unblock_input ();
448 return (oldrgb);
451 /* The default colors for the w32 color map */
452 typedef struct colormap_t
454 char *name;
455 COLORREF colorref;
456 } colormap_t;
458 colormap_t w32_color_map[] =
460 {"snow" , PALETTERGB (255,250,250)},
461 {"ghost white" , PALETTERGB (248,248,255)},
462 {"GhostWhite" , PALETTERGB (248,248,255)},
463 {"white smoke" , PALETTERGB (245,245,245)},
464 {"WhiteSmoke" , PALETTERGB (245,245,245)},
465 {"gainsboro" , PALETTERGB (220,220,220)},
466 {"floral white" , PALETTERGB (255,250,240)},
467 {"FloralWhite" , PALETTERGB (255,250,240)},
468 {"old lace" , PALETTERGB (253,245,230)},
469 {"OldLace" , PALETTERGB (253,245,230)},
470 {"linen" , PALETTERGB (250,240,230)},
471 {"antique white" , PALETTERGB (250,235,215)},
472 {"AntiqueWhite" , PALETTERGB (250,235,215)},
473 {"papaya whip" , PALETTERGB (255,239,213)},
474 {"PapayaWhip" , PALETTERGB (255,239,213)},
475 {"blanched almond" , PALETTERGB (255,235,205)},
476 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
477 {"bisque" , PALETTERGB (255,228,196)},
478 {"peach puff" , PALETTERGB (255,218,185)},
479 {"PeachPuff" , PALETTERGB (255,218,185)},
480 {"navajo white" , PALETTERGB (255,222,173)},
481 {"NavajoWhite" , PALETTERGB (255,222,173)},
482 {"moccasin" , PALETTERGB (255,228,181)},
483 {"cornsilk" , PALETTERGB (255,248,220)},
484 {"ivory" , PALETTERGB (255,255,240)},
485 {"lemon chiffon" , PALETTERGB (255,250,205)},
486 {"LemonChiffon" , PALETTERGB (255,250,205)},
487 {"seashell" , PALETTERGB (255,245,238)},
488 {"honeydew" , PALETTERGB (240,255,240)},
489 {"mint cream" , PALETTERGB (245,255,250)},
490 {"MintCream" , PALETTERGB (245,255,250)},
491 {"azure" , PALETTERGB (240,255,255)},
492 {"alice blue" , PALETTERGB (240,248,255)},
493 {"AliceBlue" , PALETTERGB (240,248,255)},
494 {"lavender" , PALETTERGB (230,230,250)},
495 {"lavender blush" , PALETTERGB (255,240,245)},
496 {"LavenderBlush" , PALETTERGB (255,240,245)},
497 {"misty rose" , PALETTERGB (255,228,225)},
498 {"MistyRose" , PALETTERGB (255,228,225)},
499 {"white" , PALETTERGB (255,255,255)},
500 {"black" , PALETTERGB ( 0, 0, 0)},
501 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
502 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
503 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
504 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
505 {"dim gray" , PALETTERGB (105,105,105)},
506 {"DimGray" , PALETTERGB (105,105,105)},
507 {"dim grey" , PALETTERGB (105,105,105)},
508 {"DimGrey" , PALETTERGB (105,105,105)},
509 {"slate gray" , PALETTERGB (112,128,144)},
510 {"SlateGray" , PALETTERGB (112,128,144)},
511 {"slate grey" , PALETTERGB (112,128,144)},
512 {"SlateGrey" , PALETTERGB (112,128,144)},
513 {"light slate gray" , PALETTERGB (119,136,153)},
514 {"LightSlateGray" , PALETTERGB (119,136,153)},
515 {"light slate grey" , PALETTERGB (119,136,153)},
516 {"LightSlateGrey" , PALETTERGB (119,136,153)},
517 {"gray" , PALETTERGB (190,190,190)},
518 {"grey" , PALETTERGB (190,190,190)},
519 {"light grey" , PALETTERGB (211,211,211)},
520 {"LightGrey" , PALETTERGB (211,211,211)},
521 {"light gray" , PALETTERGB (211,211,211)},
522 {"LightGray" , PALETTERGB (211,211,211)},
523 {"midnight blue" , PALETTERGB ( 25, 25,112)},
524 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
525 {"navy" , PALETTERGB ( 0, 0,128)},
526 {"navy blue" , PALETTERGB ( 0, 0,128)},
527 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
528 {"cornflower blue" , PALETTERGB (100,149,237)},
529 {"CornflowerBlue" , PALETTERGB (100,149,237)},
530 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
531 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
532 {"slate blue" , PALETTERGB (106, 90,205)},
533 {"SlateBlue" , PALETTERGB (106, 90,205)},
534 {"medium slate blue" , PALETTERGB (123,104,238)},
535 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
536 {"light slate blue" , PALETTERGB (132,112,255)},
537 {"LightSlateBlue" , PALETTERGB (132,112,255)},
538 {"medium blue" , PALETTERGB ( 0, 0,205)},
539 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
540 {"royal blue" , PALETTERGB ( 65,105,225)},
541 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
542 {"blue" , PALETTERGB ( 0, 0,255)},
543 {"dodger blue" , PALETTERGB ( 30,144,255)},
544 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
545 {"deep sky blue" , PALETTERGB ( 0,191,255)},
546 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
547 {"sky blue" , PALETTERGB (135,206,235)},
548 {"SkyBlue" , PALETTERGB (135,206,235)},
549 {"light sky blue" , PALETTERGB (135,206,250)},
550 {"LightSkyBlue" , PALETTERGB (135,206,250)},
551 {"steel blue" , PALETTERGB ( 70,130,180)},
552 {"SteelBlue" , PALETTERGB ( 70,130,180)},
553 {"light steel blue" , PALETTERGB (176,196,222)},
554 {"LightSteelBlue" , PALETTERGB (176,196,222)},
555 {"light blue" , PALETTERGB (173,216,230)},
556 {"LightBlue" , PALETTERGB (173,216,230)},
557 {"powder blue" , PALETTERGB (176,224,230)},
558 {"PowderBlue" , PALETTERGB (176,224,230)},
559 {"pale turquoise" , PALETTERGB (175,238,238)},
560 {"PaleTurquoise" , PALETTERGB (175,238,238)},
561 {"dark turquoise" , PALETTERGB ( 0,206,209)},
562 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
563 {"medium turquoise" , PALETTERGB ( 72,209,204)},
564 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
565 {"turquoise" , PALETTERGB ( 64,224,208)},
566 {"cyan" , PALETTERGB ( 0,255,255)},
567 {"light cyan" , PALETTERGB (224,255,255)},
568 {"LightCyan" , PALETTERGB (224,255,255)},
569 {"cadet blue" , PALETTERGB ( 95,158,160)},
570 {"CadetBlue" , PALETTERGB ( 95,158,160)},
571 {"medium aquamarine" , PALETTERGB (102,205,170)},
572 {"MediumAquamarine" , PALETTERGB (102,205,170)},
573 {"aquamarine" , PALETTERGB (127,255,212)},
574 {"dark green" , PALETTERGB ( 0,100, 0)},
575 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
576 {"dark olive green" , PALETTERGB ( 85,107, 47)},
577 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
578 {"dark sea green" , PALETTERGB (143,188,143)},
579 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
580 {"sea green" , PALETTERGB ( 46,139, 87)},
581 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
582 {"medium sea green" , PALETTERGB ( 60,179,113)},
583 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
584 {"light sea green" , PALETTERGB ( 32,178,170)},
585 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
586 {"pale green" , PALETTERGB (152,251,152)},
587 {"PaleGreen" , PALETTERGB (152,251,152)},
588 {"spring green" , PALETTERGB ( 0,255,127)},
589 {"SpringGreen" , PALETTERGB ( 0,255,127)},
590 {"lawn green" , PALETTERGB (124,252, 0)},
591 {"LawnGreen" , PALETTERGB (124,252, 0)},
592 {"green" , PALETTERGB ( 0,255, 0)},
593 {"chartreuse" , PALETTERGB (127,255, 0)},
594 {"medium spring green" , PALETTERGB ( 0,250,154)},
595 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
596 {"green yellow" , PALETTERGB (173,255, 47)},
597 {"GreenYellow" , PALETTERGB (173,255, 47)},
598 {"lime green" , PALETTERGB ( 50,205, 50)},
599 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
600 {"yellow green" , PALETTERGB (154,205, 50)},
601 {"YellowGreen" , PALETTERGB (154,205, 50)},
602 {"forest green" , PALETTERGB ( 34,139, 34)},
603 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
604 {"olive drab" , PALETTERGB (107,142, 35)},
605 {"OliveDrab" , PALETTERGB (107,142, 35)},
606 {"dark khaki" , PALETTERGB (189,183,107)},
607 {"DarkKhaki" , PALETTERGB (189,183,107)},
608 {"khaki" , PALETTERGB (240,230,140)},
609 {"pale goldenrod" , PALETTERGB (238,232,170)},
610 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
611 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
612 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
613 {"light yellow" , PALETTERGB (255,255,224)},
614 {"LightYellow" , PALETTERGB (255,255,224)},
615 {"yellow" , PALETTERGB (255,255, 0)},
616 {"gold" , PALETTERGB (255,215, 0)},
617 {"light goldenrod" , PALETTERGB (238,221,130)},
618 {"LightGoldenrod" , PALETTERGB (238,221,130)},
619 {"goldenrod" , PALETTERGB (218,165, 32)},
620 {"dark goldenrod" , PALETTERGB (184,134, 11)},
621 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
622 {"rosy brown" , PALETTERGB (188,143,143)},
623 {"RosyBrown" , PALETTERGB (188,143,143)},
624 {"indian red" , PALETTERGB (205, 92, 92)},
625 {"IndianRed" , PALETTERGB (205, 92, 92)},
626 {"saddle brown" , PALETTERGB (139, 69, 19)},
627 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
628 {"sienna" , PALETTERGB (160, 82, 45)},
629 {"peru" , PALETTERGB (205,133, 63)},
630 {"burlywood" , PALETTERGB (222,184,135)},
631 {"beige" , PALETTERGB (245,245,220)},
632 {"wheat" , PALETTERGB (245,222,179)},
633 {"sandy brown" , PALETTERGB (244,164, 96)},
634 {"SandyBrown" , PALETTERGB (244,164, 96)},
635 {"tan" , PALETTERGB (210,180,140)},
636 {"chocolate" , PALETTERGB (210,105, 30)},
637 {"firebrick" , PALETTERGB (178,34, 34)},
638 {"brown" , PALETTERGB (165,42, 42)},
639 {"dark salmon" , PALETTERGB (233,150,122)},
640 {"DarkSalmon" , PALETTERGB (233,150,122)},
641 {"salmon" , PALETTERGB (250,128,114)},
642 {"light salmon" , PALETTERGB (255,160,122)},
643 {"LightSalmon" , PALETTERGB (255,160,122)},
644 {"orange" , PALETTERGB (255,165, 0)},
645 {"dark orange" , PALETTERGB (255,140, 0)},
646 {"DarkOrange" , PALETTERGB (255,140, 0)},
647 {"coral" , PALETTERGB (255,127, 80)},
648 {"light coral" , PALETTERGB (240,128,128)},
649 {"LightCoral" , PALETTERGB (240,128,128)},
650 {"tomato" , PALETTERGB (255, 99, 71)},
651 {"orange red" , PALETTERGB (255, 69, 0)},
652 {"OrangeRed" , PALETTERGB (255, 69, 0)},
653 {"red" , PALETTERGB (255, 0, 0)},
654 {"hot pink" , PALETTERGB (255,105,180)},
655 {"HotPink" , PALETTERGB (255,105,180)},
656 {"deep pink" , PALETTERGB (255, 20,147)},
657 {"DeepPink" , PALETTERGB (255, 20,147)},
658 {"pink" , PALETTERGB (255,192,203)},
659 {"light pink" , PALETTERGB (255,182,193)},
660 {"LightPink" , PALETTERGB (255,182,193)},
661 {"pale violet red" , PALETTERGB (219,112,147)},
662 {"PaleVioletRed" , PALETTERGB (219,112,147)},
663 {"maroon" , PALETTERGB (176, 48, 96)},
664 {"medium violet red" , PALETTERGB (199, 21,133)},
665 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
666 {"violet red" , PALETTERGB (208, 32,144)},
667 {"VioletRed" , PALETTERGB (208, 32,144)},
668 {"magenta" , PALETTERGB (255, 0,255)},
669 {"violet" , PALETTERGB (238,130,238)},
670 {"plum" , PALETTERGB (221,160,221)},
671 {"orchid" , PALETTERGB (218,112,214)},
672 {"medium orchid" , PALETTERGB (186, 85,211)},
673 {"MediumOrchid" , PALETTERGB (186, 85,211)},
674 {"dark orchid" , PALETTERGB (153, 50,204)},
675 {"DarkOrchid" , PALETTERGB (153, 50,204)},
676 {"dark violet" , PALETTERGB (148, 0,211)},
677 {"DarkViolet" , PALETTERGB (148, 0,211)},
678 {"blue violet" , PALETTERGB (138, 43,226)},
679 {"BlueViolet" , PALETTERGB (138, 43,226)},
680 {"purple" , PALETTERGB (160, 32,240)},
681 {"medium purple" , PALETTERGB (147,112,219)},
682 {"MediumPurple" , PALETTERGB (147,112,219)},
683 {"thistle" , PALETTERGB (216,191,216)},
684 {"gray0" , PALETTERGB ( 0, 0, 0)},
685 {"grey0" , PALETTERGB ( 0, 0, 0)},
686 {"dark grey" , PALETTERGB (169,169,169)},
687 {"DarkGrey" , PALETTERGB (169,169,169)},
688 {"dark gray" , PALETTERGB (169,169,169)},
689 {"DarkGray" , PALETTERGB (169,169,169)},
690 {"dark blue" , PALETTERGB ( 0, 0,139)},
691 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
692 {"dark cyan" , PALETTERGB ( 0,139,139)},
693 {"DarkCyan" , PALETTERGB ( 0,139,139)},
694 {"dark magenta" , PALETTERGB (139, 0,139)},
695 {"DarkMagenta" , PALETTERGB (139, 0,139)},
696 {"dark red" , PALETTERGB (139, 0, 0)},
697 {"DarkRed" , PALETTERGB (139, 0, 0)},
698 {"light green" , PALETTERGB (144,238,144)},
699 {"LightGreen" , PALETTERGB (144,238,144)},
702 static Lisp_Object
703 w32_default_color_map (void)
705 int i;
706 colormap_t *pc = w32_color_map;
707 Lisp_Object cmap;
709 block_input ();
711 cmap = Qnil;
713 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
714 cmap = Fcons (Fcons (build_string (pc->name),
715 make_number (pc->colorref)),
716 cmap);
718 unblock_input ();
720 return (cmap);
723 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
724 0, 0, 0, doc: /* Return the default color map. */)
725 (void)
727 return w32_default_color_map ();
730 static Lisp_Object
731 w32_color_map_lookup (const char *colorname)
733 Lisp_Object tail, ret = Qnil;
735 block_input ();
737 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
739 register Lisp_Object elt, tem;
741 elt = XCAR (tail);
742 if (!CONSP (elt)) continue;
744 tem = XCAR (elt);
746 if (lstrcmpi (SDATA (tem), colorname) == 0)
748 ret = Fcdr (elt);
749 break;
752 QUIT;
755 unblock_input ();
757 return ret;
761 static void
762 add_system_logical_colors_to_map (Lisp_Object *system_colors)
764 HKEY colors_key;
766 /* Other registry operations are done with input blocked. */
767 block_input ();
769 /* Look for "Control Panel/Colors" under User and Machine registry
770 settings. */
771 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
772 KEY_READ, &colors_key) == ERROR_SUCCESS
773 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
774 KEY_READ, &colors_key) == ERROR_SUCCESS)
776 /* List all keys. */
777 char color_buffer[64];
778 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
779 int index = 0;
780 DWORD name_size, color_size;
781 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
783 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
784 color_size = sizeof (color_buffer);
786 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
788 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
789 NULL, NULL, color_buffer, &color_size)
790 == ERROR_SUCCESS)
792 int r, g, b;
793 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
794 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
795 make_number (RGB (r, g, b))),
796 *system_colors);
798 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
799 color_size = sizeof (color_buffer);
800 index++;
802 RegCloseKey (colors_key);
805 unblock_input ();
809 static Lisp_Object
810 x_to_w32_color (const char * colorname)
812 register Lisp_Object ret = Qnil;
814 block_input ();
816 if (colorname[0] == '#')
818 /* Could be an old-style RGB Device specification. */
819 int size = strlen (colorname + 1);
820 char *color = alloca (size + 1);
822 strcpy (color, colorname + 1);
823 if (size == 3 || size == 6 || size == 9 || size == 12)
825 UINT colorval;
826 int i, pos;
827 pos = 0;
828 size /= 3;
829 colorval = 0;
831 for (i = 0; i < 3; i++)
833 char *end;
834 char t;
835 unsigned long value;
837 /* The check for 'x' in the following conditional takes into
838 account the fact that strtol allows a "0x" in front of
839 our numbers, and we don't. */
840 if (!isxdigit (color[0]) || color[1] == 'x')
841 break;
842 t = color[size];
843 color[size] = '\0';
844 value = strtoul (color, &end, 16);
845 color[size] = t;
846 if (errno == ERANGE || end - color != size)
847 break;
848 switch (size)
850 case 1:
851 value = value * 0x10;
852 break;
853 case 2:
854 break;
855 case 3:
856 value /= 0x10;
857 break;
858 case 4:
859 value /= 0x100;
860 break;
862 colorval |= (value << pos);
863 pos += 0x8;
864 if (i == 2)
866 unblock_input ();
867 XSETINT (ret, colorval);
868 return ret;
870 color = end;
874 else if (strnicmp (colorname, "rgb:", 4) == 0)
876 const char *color;
877 UINT colorval;
878 int i, pos;
879 pos = 0;
881 colorval = 0;
882 color = colorname + 4;
883 for (i = 0; i < 3; i++)
885 char *end;
886 unsigned long value;
888 /* The check for 'x' in the following conditional takes into
889 account the fact that strtol allows a "0x" in front of
890 our numbers, and we don't. */
891 if (!isxdigit (color[0]) || color[1] == 'x')
892 break;
893 value = strtoul (color, &end, 16);
894 if (errno == ERANGE)
895 break;
896 switch (end - color)
898 case 1:
899 value = value * 0x10 + value;
900 break;
901 case 2:
902 break;
903 case 3:
904 value /= 0x10;
905 break;
906 case 4:
907 value /= 0x100;
908 break;
909 default:
910 value = ULONG_MAX;
912 if (value == ULONG_MAX)
913 break;
914 colorval |= (value << pos);
915 pos += 0x8;
916 if (i == 2)
918 if (*end != '\0')
919 break;
920 unblock_input ();
921 XSETINT (ret, colorval);
922 return ret;
924 if (*end != '/')
925 break;
926 color = end + 1;
929 else if (strnicmp (colorname, "rgbi:", 5) == 0)
931 /* This is an RGB Intensity specification. */
932 const char *color;
933 UINT colorval;
934 int i, pos;
935 pos = 0;
937 colorval = 0;
938 color = colorname + 5;
939 for (i = 0; i < 3; i++)
941 char *end;
942 double value;
943 UINT val;
945 value = strtod (color, &end);
946 if (errno == ERANGE)
947 break;
948 if (value < 0.0 || value > 1.0)
949 break;
950 val = (UINT)(0x100 * value);
951 /* We used 0x100 instead of 0xFF to give a continuous
952 range between 0.0 and 1.0 inclusive. The next statement
953 fixes the 1.0 case. */
954 if (val == 0x100)
955 val = 0xFF;
956 colorval |= (val << pos);
957 pos += 0x8;
958 if (i == 2)
960 if (*end != '\0')
961 break;
962 unblock_input ();
963 XSETINT (ret, colorval);
964 return ret;
966 if (*end != '/')
967 break;
968 color = end + 1;
971 /* I am not going to attempt to handle any of the CIE color schemes
972 or TekHVC, since I don't know the algorithms for conversion to
973 RGB. */
975 /* If we fail to lookup the color name in w32_color_map, then check the
976 colorname to see if it can be crudely approximated: If the X color
977 ends in a number (e.g., "darkseagreen2"), strip the number and
978 return the result of looking up the base color name. */
979 ret = w32_color_map_lookup (colorname);
980 if (NILP (ret))
982 int len = strlen (colorname);
984 if (isdigit (colorname[len - 1]))
986 char *ptr, *approx = alloca (len + 1);
988 strcpy (approx, colorname);
989 ptr = &approx[len - 1];
990 while (ptr > approx && isdigit (*ptr))
991 *ptr-- = '\0';
993 ret = w32_color_map_lookup (approx);
997 unblock_input ();
998 return ret;
1001 void
1002 w32_regenerate_palette (struct frame *f)
1004 struct w32_palette_entry * list;
1005 LOGPALETTE * log_palette;
1006 HPALETTE new_palette;
1007 int i;
1009 /* don't bother trying to create palette if not supported */
1010 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1011 return;
1013 log_palette = (LOGPALETTE *)
1014 alloca (sizeof (LOGPALETTE) +
1015 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1016 log_palette->palVersion = 0x300;
1017 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1019 list = FRAME_DISPLAY_INFO (f)->color_list;
1020 for (i = 0;
1021 i < FRAME_DISPLAY_INFO (f)->num_colors;
1022 i++, list = list->next)
1023 log_palette->palPalEntry[i] = list->entry;
1025 new_palette = CreatePalette (log_palette);
1027 enter_crit ();
1029 if (FRAME_DISPLAY_INFO (f)->palette)
1030 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1031 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1033 /* Realize display palette and garbage all frames. */
1034 release_frame_dc (f, get_frame_dc (f));
1036 leave_crit ();
1039 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1040 #define SET_W32_COLOR(pe, color) \
1041 do \
1043 pe.peRed = GetRValue (color); \
1044 pe.peGreen = GetGValue (color); \
1045 pe.peBlue = GetBValue (color); \
1046 pe.peFlags = 0; \
1047 } while (0)
1049 #if 0
1050 /* Keep these around in case we ever want to track color usage. */
1051 void
1052 w32_map_color (struct frame *f, COLORREF color)
1054 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1056 if (NILP (Vw32_enable_palette))
1057 return;
1059 /* check if color is already mapped */
1060 while (list)
1062 if (W32_COLOR (list->entry) == color)
1064 ++list->refcount;
1065 return;
1067 list = list->next;
1070 /* not already mapped, so add to list and recreate Windows palette */
1071 list = xmalloc (sizeof (struct w32_palette_entry));
1072 SET_W32_COLOR (list->entry, color);
1073 list->refcount = 1;
1074 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1075 FRAME_DISPLAY_INFO (f)->color_list = list;
1076 FRAME_DISPLAY_INFO (f)->num_colors++;
1078 /* set flag that palette must be regenerated */
1079 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1082 void
1083 w32_unmap_color (struct frame *f, COLORREF color)
1085 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1086 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1088 if (NILP (Vw32_enable_palette))
1089 return;
1091 /* check if color is already mapped */
1092 while (list)
1094 if (W32_COLOR (list->entry) == color)
1096 if (--list->refcount == 0)
1098 *prev = list->next;
1099 xfree (list);
1100 FRAME_DISPLAY_INFO (f)->num_colors--;
1101 break;
1103 else
1104 return;
1106 prev = &list->next;
1107 list = list->next;
1110 /* set flag that palette must be regenerated */
1111 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1113 #endif
1116 /* Gamma-correct COLOR on frame F. */
1118 void
1119 gamma_correct (struct frame *f, COLORREF *color)
1121 if (f->gamma)
1123 *color = PALETTERGB (
1124 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1125 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1126 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1131 /* Decide if color named COLOR is valid for the display associated with
1132 the selected frame; if so, return the rgb values in COLOR_DEF.
1133 If ALLOC is nonzero, allocate a new colormap cell. */
1136 w32_defined_color (struct frame *f, const char *color, XColor *color_def,
1137 bool alloc_p)
1139 register Lisp_Object tem;
1140 COLORREF w32_color_ref;
1142 tem = x_to_w32_color (color);
1144 if (!NILP (tem))
1146 if (f)
1148 /* Apply gamma correction. */
1149 w32_color_ref = XUINT (tem);
1150 gamma_correct (f, &w32_color_ref);
1151 XSETINT (tem, w32_color_ref);
1154 /* Map this color to the palette if it is enabled. */
1155 if (!NILP (Vw32_enable_palette))
1157 struct w32_palette_entry * entry =
1158 one_w32_display_info.color_list;
1159 struct w32_palette_entry ** prev =
1160 &one_w32_display_info.color_list;
1162 /* check if color is already mapped */
1163 while (entry)
1165 if (W32_COLOR (entry->entry) == XUINT (tem))
1166 break;
1167 prev = &entry->next;
1168 entry = entry->next;
1171 if (entry == NULL && alloc_p)
1173 /* not already mapped, so add to list */
1174 entry = xmalloc (sizeof (struct w32_palette_entry));
1175 SET_W32_COLOR (entry->entry, XUINT (tem));
1176 entry->next = NULL;
1177 *prev = entry;
1178 one_w32_display_info.num_colors++;
1180 /* set flag that palette must be regenerated */
1181 one_w32_display_info.regen_palette = TRUE;
1184 /* Ensure COLORREF value is snapped to nearest color in (default)
1185 palette by simulating the PALETTERGB macro. This works whether
1186 or not the display device has a palette. */
1187 w32_color_ref = XUINT (tem) | 0x2000000;
1189 color_def->pixel = w32_color_ref;
1190 color_def->red = GetRValue (w32_color_ref) * 256;
1191 color_def->green = GetGValue (w32_color_ref) * 256;
1192 color_def->blue = GetBValue (w32_color_ref) * 256;
1194 return 1;
1196 else
1198 return 0;
1202 /* Given a string ARG naming a color, compute a pixel value from it
1203 suitable for screen F.
1204 If F is not a color screen, return DEF (default) regardless of what
1205 ARG says. */
1208 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1210 XColor cdef;
1212 CHECK_STRING (arg);
1214 if (strcmp (SDATA (arg), "black") == 0)
1215 return BLACK_PIX_DEFAULT (f);
1216 else if (strcmp (SDATA (arg), "white") == 0)
1217 return WHITE_PIX_DEFAULT (f);
1219 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1220 return def;
1222 /* w32_defined_color is responsible for coping with failures
1223 by looking for a near-miss. */
1224 if (w32_defined_color (f, SDATA (arg), &cdef, true))
1225 return cdef.pixel;
1227 /* defined_color failed; return an ultimate default. */
1228 return def;
1233 /* Functions called only from `x_set_frame_param'
1234 to set individual parameters.
1236 If FRAME_W32_WINDOW (f) is 0,
1237 the frame is being created and its window does not exist yet.
1238 In that case, just record the parameter's new value
1239 in the standard place; do not attempt to change the window. */
1241 void
1242 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1244 struct w32_output *x = f->output_data.w32;
1245 PIX_TYPE fg, old_fg;
1247 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1248 old_fg = FRAME_FOREGROUND_PIXEL (f);
1249 FRAME_FOREGROUND_PIXEL (f) = fg;
1251 if (FRAME_W32_WINDOW (f) != 0)
1253 if (x->cursor_pixel == old_fg)
1255 x->cursor_pixel = fg;
1256 x->cursor_gc->background = fg;
1259 update_face_from_frame_parameter (f, Qforeground_color, arg);
1260 if (FRAME_VISIBLE_P (f))
1261 redraw_frame (f);
1265 void
1266 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1268 FRAME_BACKGROUND_PIXEL (f)
1269 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1271 if (FRAME_W32_WINDOW (f) != 0)
1273 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1274 FRAME_BACKGROUND_PIXEL (f));
1276 update_face_from_frame_parameter (f, Qbackground_color, arg);
1278 if (FRAME_VISIBLE_P (f))
1279 redraw_frame (f);
1283 void
1284 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1286 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1287 int count;
1288 int mask_color;
1290 if (!EQ (Qnil, arg))
1291 f->output_data.w32->mouse_pixel
1292 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1293 mask_color = FRAME_BACKGROUND_PIXEL (f);
1295 /* Don't let pointers be invisible. */
1296 if (mask_color == f->output_data.w32->mouse_pixel
1297 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1298 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1300 #if 0 /* TODO : Mouse cursor customization. */
1301 block_input ();
1303 /* It's not okay to crash if the user selects a screwy cursor. */
1304 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1306 if (!EQ (Qnil, Vx_pointer_shape))
1308 CHECK_NUMBER (Vx_pointer_shape);
1309 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1311 else
1312 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1313 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1315 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1317 CHECK_NUMBER (Vx_nontext_pointer_shape);
1318 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1319 XINT (Vx_nontext_pointer_shape));
1321 else
1322 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1323 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1325 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1327 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1328 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1329 XINT (Vx_hourglass_pointer_shape));
1331 else
1332 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1333 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1335 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1336 if (!EQ (Qnil, Vx_mode_pointer_shape))
1338 CHECK_NUMBER (Vx_mode_pointer_shape);
1339 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1340 XINT (Vx_mode_pointer_shape));
1342 else
1343 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1344 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1346 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1348 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1349 hand_cursor
1350 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1351 XINT (Vx_sensitive_text_pointer_shape));
1353 else
1354 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1356 if (!NILP (Vx_window_horizontal_drag_shape))
1358 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1359 horizontal_drag_cursor
1360 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1361 XINT (Vx_window_horizontal_drag_shape));
1363 else
1364 horizontal_drag_cursor
1365 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1367 if (!NILP (Vx_window_vertical_drag_shape))
1369 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1370 vertical_drag_cursor
1371 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1372 XINT (Vx_window_vertical_drag_shape));
1374 else
1375 vertical_drag_cursor
1376 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1378 /* Check and report errors with the above calls. */
1379 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1380 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1383 XColor fore_color, back_color;
1385 fore_color.pixel = f->output_data.w32->mouse_pixel;
1386 back_color.pixel = mask_color;
1387 XQueryColor (FRAME_W32_DISPLAY (f),
1388 DefaultColormap (FRAME_W32_DISPLAY (f),
1389 DefaultScreen (FRAME_W32_DISPLAY (f))),
1390 &fore_color);
1391 XQueryColor (FRAME_W32_DISPLAY (f),
1392 DefaultColormap (FRAME_W32_DISPLAY (f),
1393 DefaultScreen (FRAME_W32_DISPLAY (f))),
1394 &back_color);
1395 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1396 &fore_color, &back_color);
1397 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1398 &fore_color, &back_color);
1399 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1400 &fore_color, &back_color);
1401 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1402 &fore_color, &back_color);
1403 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1404 &fore_color, &back_color);
1407 if (FRAME_W32_WINDOW (f) != 0)
1408 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1410 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1411 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1412 f->output_data.w32->text_cursor = cursor;
1414 if (nontext_cursor != f->output_data.w32->nontext_cursor
1415 && f->output_data.w32->nontext_cursor != 0)
1416 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1417 f->output_data.w32->nontext_cursor = nontext_cursor;
1419 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1420 && f->output_data.w32->hourglass_cursor != 0)
1421 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1422 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1424 if (mode_cursor != f->output_data.w32->modeline_cursor
1425 && f->output_data.w32->modeline_cursor != 0)
1426 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1427 f->output_data.w32->modeline_cursor = mode_cursor;
1429 if (hand_cursor != f->output_data.w32->hand_cursor
1430 && f->output_data.w32->hand_cursor != 0)
1431 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1432 f->output_data.w32->hand_cursor = hand_cursor;
1434 XFlush (FRAME_W32_DISPLAY (f));
1435 unblock_input ();
1437 update_face_from_frame_parameter (f, Qmouse_color, arg);
1438 #endif /* TODO */
1441 void
1442 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1444 unsigned long fore_pixel, pixel;
1446 if (!NILP (Vx_cursor_fore_pixel))
1447 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1448 WHITE_PIX_DEFAULT (f));
1449 else
1450 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1452 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1454 /* Make sure that the cursor color differs from the background color. */
1455 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1457 pixel = f->output_data.w32->mouse_pixel;
1458 if (pixel == fore_pixel)
1459 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1462 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1463 f->output_data.w32->cursor_pixel = pixel;
1465 if (FRAME_W32_WINDOW (f) != 0)
1467 block_input ();
1468 /* Update frame's cursor_gc. */
1469 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1470 f->output_data.w32->cursor_gc->background = pixel;
1472 unblock_input ();
1474 if (FRAME_VISIBLE_P (f))
1476 x_update_cursor (f, 0);
1477 x_update_cursor (f, 1);
1481 update_face_from_frame_parameter (f, Qcursor_color, arg);
1484 /* Set the border-color of frame F to pixel value PIX.
1485 Note that this does not fully take effect if done before
1486 F has a window. */
1488 void
1489 x_set_border_pixel (struct frame *f, int pix)
1492 f->output_data.w32->border_pixel = pix;
1494 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1496 if (FRAME_VISIBLE_P (f))
1497 redraw_frame (f);
1501 /* Set the border-color of frame F to value described by ARG.
1502 ARG can be a string naming a color.
1503 The border-color is used for the border that is drawn by the server.
1504 Note that this does not fully take effect if done before
1505 F has a window; it must be redone when the window is created. */
1507 void
1508 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1510 int pix;
1512 CHECK_STRING (arg);
1513 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1514 x_set_border_pixel (f, pix);
1515 update_face_from_frame_parameter (f, Qborder_color, arg);
1519 void
1520 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1522 set_frame_cursor_types (f, arg);
1525 void
1526 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1528 bool result;
1530 if (NILP (arg) && NILP (oldval))
1531 return;
1533 if (STRINGP (arg) && STRINGP (oldval)
1534 && EQ (Fstring_equal (oldval, arg), Qt))
1535 return;
1537 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1538 return;
1540 block_input ();
1542 result = x_bitmap_icon (f, arg);
1543 if (result)
1545 unblock_input ();
1546 error ("No icon window available");
1549 unblock_input ();
1552 void
1553 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1555 if (STRINGP (arg))
1557 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1558 return;
1560 else if (!NILP (arg) || NILP (oldval))
1561 return;
1563 fset_icon_name (f, arg);
1565 #if 0
1566 if (f->output_data.w32->icon_bitmap != 0)
1567 return;
1569 block_input ();
1571 result = x_text_icon (f,
1572 SSDATA ((!NILP (f->icon_name)
1573 ? f->icon_name
1574 : !NILP (f->title)
1575 ? f->title
1576 : f->name)));
1578 if (result)
1580 unblock_input ();
1581 error ("No icon window available");
1584 /* If the window was unmapped (and its icon was mapped),
1585 the new icon is not mapped, so map the window in its stead. */
1586 if (FRAME_VISIBLE_P (f))
1588 #ifdef USE_X_TOOLKIT
1589 XtPopup (f->output_data.w32->widget, XtGrabNone);
1590 #endif
1591 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1594 XFlush (FRAME_W32_DISPLAY (f));
1595 unblock_input ();
1596 #endif
1599 void
1600 x_clear_under_internal_border (struct frame *f)
1602 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1604 /* Clear border if it's larger than before. */
1605 if (border != 0)
1607 HDC hdc = get_frame_dc (f);
1608 int width = FRAME_PIXEL_WIDTH (f);
1609 int height = FRAME_PIXEL_HEIGHT (f);
1611 block_input ();
1612 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1613 w32_clear_area (f, hdc, 0, 0, border, height);
1614 w32_clear_area (f, hdc, width - border, 0, border, height);
1615 w32_clear_area (f, hdc, 0, height - border, width, border);
1616 release_frame_dc (f, hdc);
1617 unblock_input ();
1622 void
1623 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1625 int border;
1627 CHECK_TYPE_RANGED_INTEGER (int, arg);
1628 border = max (XINT (arg), 0);
1630 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1632 FRAME_INTERNAL_BORDER_WIDTH (f) = border;
1634 if (FRAME_X_WINDOW (f) != 0)
1636 adjust_frame_size (f, -1, -1, 3, false, Qinternal_border_width);
1638 if (FRAME_VISIBLE_P (f))
1639 x_clear_under_internal_border (f);
1645 void
1646 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1648 int nlines;
1650 /* Right now, menu bars don't work properly in minibuf-only frames;
1651 most of the commands try to apply themselves to the minibuffer
1652 frame itself, and get an error because you can't switch buffers
1653 in or split the minibuffer window. */
1654 if (FRAME_MINIBUF_ONLY_P (f))
1655 return;
1657 if (INTEGERP (value))
1658 nlines = XINT (value);
1659 else
1660 nlines = 0;
1662 FRAME_MENU_BAR_LINES (f) = 0;
1663 FRAME_MENU_BAR_HEIGHT (f) = 0;
1664 if (nlines)
1666 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1667 windows_or_buffers_changed = 23;
1669 else
1671 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1672 free_frame_menubar (f);
1673 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1675 /* Adjust the frame size so that the client (text) dimensions
1676 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1677 set correctly. Note that we resize twice: The first time upon
1678 a request from the window manager who wants to keep the height
1679 of the outer rectangle (including decorations) unchanged, and a
1680 second time because we want to keep the height of the inner
1681 rectangle (without the decorations unchanged). */
1682 adjust_frame_size (f, -1, -1, 2, true, Qmenu_bar_lines);
1684 /* Not sure whether this is needed. */
1685 x_clear_under_internal_border (f);
1690 /* Set the number of lines used for the tool bar of frame F to VALUE.
1691 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1692 the old number of tool bar lines (and is unused). This function may
1693 change the height of all windows on frame F to match the new tool bar
1694 height. By design, the frame's height doesn't change (but maybe it
1695 should if we don't get enough space otherwise). */
1697 void
1698 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1700 int nlines;
1702 /* Treat tool bars like menu bars. */
1703 if (FRAME_MINIBUF_ONLY_P (f))
1704 return;
1706 /* Use VALUE only if an integer >= 0. */
1707 if (INTEGERP (value) && XINT (value) >= 0)
1708 nlines = XFASTINT (value);
1709 else
1710 nlines = 0;
1712 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1716 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1717 void
1718 x_change_tool_bar_height (struct frame *f, int height)
1720 Lisp_Object frame;
1721 int unit = FRAME_LINE_HEIGHT (f);
1722 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1723 int lines = (height + unit - 1) / unit;
1724 int old_text_height = FRAME_TEXT_HEIGHT (f);
1725 Lisp_Object fullscreen;
1727 /* Make sure we redisplay all windows in this frame. */
1728 windows_or_buffers_changed = 23;
1730 /* Recalculate tool bar and frame text sizes. */
1731 FRAME_TOOL_BAR_HEIGHT (f) = height;
1732 FRAME_TOOL_BAR_LINES (f) = lines;
1733 /* Store `tool-bar-lines' and `height' frame parameters. */
1734 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1735 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1737 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1739 clear_frame (f);
1740 clear_current_matrices (f);
1743 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1744 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1746 /* Recalculate toolbar height. */
1747 f->n_tool_bar_rows = 0;
1749 adjust_frame_size (f, -1, -1,
1750 ((!f->tool_bar_redisplayed_once
1751 && (NILP (fullscreen =
1752 get_frame_param (f, Qfullscreen))
1753 || EQ (fullscreen, Qfullwidth))) ? 1
1754 : (old_height == 0 || height == 0) ? 2
1755 : 4),
1756 false, Qtool_bar_lines);
1758 /* adjust_frame_size might not have done anything, garbage frame
1759 here. */
1760 adjust_frame_glyphs (f);
1761 SET_FRAME_GARBAGED (f);
1762 if (FRAME_X_WINDOW (f))
1763 x_clear_under_internal_border (f);
1766 static void
1767 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1769 if (FRAME_W32_WINDOW (f))
1771 block_input ();
1772 #ifdef __CYGWIN__
1773 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1774 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1775 #else
1776 /* The frame's title many times shows the name of the file
1777 visited in the selected window's buffer, so it makes sense to
1778 support non-ASCII characters outside of the current system
1779 codepage in the title. */
1780 if (w32_unicode_filenames)
1782 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1783 wchar_t *title_w;
1784 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1785 -1, NULL, 0);
1787 if (tlen > 0)
1789 /* Windows truncates the title text beyond what fits on
1790 a single line, so we can limit the length to some
1791 reasonably large value, and use alloca. */
1792 if (tlen > 10000)
1793 tlen = 10000;
1794 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1795 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1796 title_w, tlen);
1797 title_w[tlen] = L'\0';
1798 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1800 else /* Conversion to UTF-16 failed, so we punt. */
1801 SetWindowTextA (FRAME_W32_WINDOW (f),
1802 SSDATA (ENCODE_SYSTEM (name)));
1804 else
1805 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1806 #endif
1807 unblock_input ();
1811 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1812 w32_id_name.
1814 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1815 name; if NAME is a string, set F's name to NAME and set
1816 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1818 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1819 suggesting a new name, which lisp code should override; if
1820 F->explicit_name is set, ignore the new name; otherwise, set it. */
1822 void
1823 x_set_name (struct frame *f, Lisp_Object name, bool explicit)
1825 /* Make sure that requests from lisp code override requests from
1826 Emacs redisplay code. */
1827 if (explicit)
1829 /* If we're switching from explicit to implicit, we had better
1830 update the mode lines and thereby update the title. */
1831 if (f->explicit_name && NILP (name))
1832 update_mode_lines = 25;
1834 f->explicit_name = ! NILP (name);
1836 else if (f->explicit_name)
1837 return;
1839 /* If NAME is nil, set the name to the w32_id_name. */
1840 if (NILP (name))
1842 /* Check for no change needed in this very common case
1843 before we do any consing. */
1844 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1845 SDATA (f->name)))
1846 return;
1847 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1849 else
1850 CHECK_STRING (name);
1852 /* Don't change the name if it's already NAME. */
1853 if (! NILP (Fstring_equal (name, f->name)))
1854 return;
1856 fset_name (f, name);
1858 /* For setting the frame title, the title parameter should override
1859 the name parameter. */
1860 if (! NILP (f->title))
1861 name = f->title;
1863 w32_set_title_bar_text (f, name);
1866 /* This function should be called when the user's lisp code has
1867 specified a name for the frame; the name will override any set by the
1868 redisplay code. */
1869 void
1870 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1872 x_set_name (f, arg, true);
1875 /* This function should be called by Emacs redisplay code to set the
1876 name; names set this way will never override names set by the user's
1877 lisp code. */
1878 void
1879 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1881 x_set_name (f, arg, false);
1884 /* Change the title of frame F to NAME.
1885 If NAME is nil, use the frame name as the title. */
1887 void
1888 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1890 /* Don't change the title if it's already NAME. */
1891 if (EQ (name, f->title))
1892 return;
1894 update_mode_lines = 26;
1896 fset_title (f, name);
1898 if (NILP (name))
1899 name = f->name;
1901 w32_set_title_bar_text (f, name);
1904 void
1905 x_set_scroll_bar_default_width (struct frame *f)
1907 int unit = FRAME_COLUMN_WIDTH (f);
1909 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1910 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1911 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1915 void
1916 x_set_scroll_bar_default_height (struct frame *f)
1918 int unit = FRAME_LINE_HEIGHT (f);
1920 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
1921 FRAME_CONFIG_SCROLL_BAR_LINES (f)
1922 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
1925 /* Subroutines for creating a frame. */
1927 Cursor
1928 w32_load_cursor (LPCTSTR name)
1930 /* Try first to load cursor from application resource. */
1931 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1932 name, IMAGE_CURSOR, 0, 0,
1933 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1934 if (!cursor)
1936 /* Then try to load a shared predefined cursor. */
1937 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1938 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1940 return cursor;
1943 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1945 #define INIT_WINDOW_CLASS(WC) \
1946 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1947 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1948 (WC).cbClsExtra = 0; \
1949 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1950 (WC).hInstance = hinst; \
1951 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1952 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1953 (WC).hbrBackground = NULL; \
1954 (WC).lpszMenuName = NULL; \
1956 static BOOL
1957 w32_init_class (HINSTANCE hinst)
1959 if (w32_unicode_gui)
1961 WNDCLASSW uwc;
1962 INIT_WINDOW_CLASS(uwc);
1963 uwc.lpszClassName = L"Emacs";
1965 return RegisterClassW (&uwc);
1967 else
1969 WNDCLASS wc;
1970 INIT_WINDOW_CLASS(wc);
1971 wc.lpszClassName = EMACS_CLASS;
1973 return RegisterClassA (&wc);
1977 static HWND
1978 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
1980 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1981 /* Position and size of scroll bar. */
1982 bar->left, bar->top, bar->width, bar->height,
1983 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1986 static HWND
1987 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
1989 return CreateWindow ("SCROLLBAR", "", SBS_HORZ | WS_CHILD | WS_VISIBLE,
1990 /* Position and size of scroll bar. */
1991 bar->left, bar->top, bar->width, bar->height,
1992 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1995 static void
1996 w32_createwindow (struct frame *f, int *coords)
1998 HWND hwnd;
1999 RECT rect;
2000 int top;
2001 int left;
2003 rect.left = rect.top = 0;
2004 rect.right = FRAME_PIXEL_WIDTH (f);
2005 rect.bottom = FRAME_PIXEL_HEIGHT (f);
2007 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
2008 FRAME_EXTERNAL_MENU_BAR (f));
2010 /* Do first time app init */
2012 w32_init_class (hinst);
2014 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
2016 left = f->left_pos;
2017 top = f->top_pos;
2019 else
2021 left = coords[0];
2022 top = coords[1];
2025 FRAME_W32_WINDOW (f) = hwnd
2026 = CreateWindow (EMACS_CLASS,
2027 f->namebuf,
2028 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
2029 left, top,
2030 rect.right - rect.left, rect.bottom - rect.top,
2031 NULL,
2032 NULL,
2033 hinst,
2034 NULL);
2036 if (hwnd)
2038 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2039 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2040 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2041 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2042 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2043 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2045 /* Enable drag-n-drop. */
2046 DragAcceptFiles (hwnd, TRUE);
2048 /* Do this to discard the default setting specified by our parent. */
2049 ShowWindow (hwnd, SW_HIDE);
2051 /* Update frame positions. */
2052 GetWindowRect (hwnd, &rect);
2053 f->left_pos = rect.left;
2054 f->top_pos = rect.top;
2058 static void
2059 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2061 wmsg->msg.hwnd = hwnd;
2062 wmsg->msg.message = msg;
2063 wmsg->msg.wParam = wParam;
2064 wmsg->msg.lParam = lParam;
2065 wmsg->msg.time = GetMessageTime ();
2067 post_msg (wmsg);
2070 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2071 between left and right keys as advertised. We test for this
2072 support dynamically, and set a flag when the support is absent. If
2073 absent, we keep track of the left and right control and alt keys
2074 ourselves. This is particularly necessary on keyboards that rely
2075 upon the AltGr key, which is represented as having the left control
2076 and right alt keys pressed. For these keyboards, we need to know
2077 when the left alt key has been pressed in addition to the AltGr key
2078 so that we can properly support M-AltGr-key sequences (such as M-@
2079 on Swedish keyboards). */
2081 #define EMACS_LCONTROL 0
2082 #define EMACS_RCONTROL 1
2083 #define EMACS_LMENU 2
2084 #define EMACS_RMENU 3
2086 static int modifiers[4];
2087 static int modifiers_recorded;
2088 static int modifier_key_support_tested;
2090 static void
2091 test_modifier_support (unsigned int wparam)
2093 unsigned int l, r;
2095 if (wparam != VK_CONTROL && wparam != VK_MENU)
2096 return;
2097 if (wparam == VK_CONTROL)
2099 l = VK_LCONTROL;
2100 r = VK_RCONTROL;
2102 else
2104 l = VK_LMENU;
2105 r = VK_RMENU;
2107 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2108 modifiers_recorded = 1;
2109 else
2110 modifiers_recorded = 0;
2111 modifier_key_support_tested = 1;
2114 static void
2115 record_keydown (unsigned int wparam, unsigned int lparam)
2117 int i;
2119 if (!modifier_key_support_tested)
2120 test_modifier_support (wparam);
2122 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2123 return;
2125 if (wparam == VK_CONTROL)
2126 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2127 else
2128 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2130 modifiers[i] = 1;
2133 static void
2134 record_keyup (unsigned int wparam, unsigned int lparam)
2136 int i;
2138 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2139 return;
2141 if (wparam == VK_CONTROL)
2142 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2143 else
2144 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2146 modifiers[i] = 0;
2149 /* Emacs can lose focus while a modifier key has been pressed. When
2150 it regains focus, be conservative and clear all modifiers since
2151 we cannot reconstruct the left and right modifier state. */
2152 static void
2153 reset_modifiers (void)
2155 SHORT ctrl, alt;
2157 if (GetFocus () == NULL)
2158 /* Emacs doesn't have keyboard focus. Do nothing. */
2159 return;
2161 ctrl = GetAsyncKeyState (VK_CONTROL);
2162 alt = GetAsyncKeyState (VK_MENU);
2164 if (!(ctrl & 0x08000))
2165 /* Clear any recorded control modifier state. */
2166 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2168 if (!(alt & 0x08000))
2169 /* Clear any recorded alt modifier state. */
2170 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2172 /* Update the state of all modifier keys, because modifiers used in
2173 hot-key combinations can get stuck on if Emacs loses focus as a
2174 result of a hot-key being pressed. */
2176 BYTE keystate[256];
2178 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2180 memset (keystate, 0, sizeof (keystate));
2181 GetKeyboardState (keystate);
2182 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2183 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2184 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2185 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2186 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2187 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2188 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2189 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2190 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2191 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2192 SetKeyboardState (keystate);
2196 /* Synchronize modifier state with what is reported with the current
2197 keystroke. Even if we cannot distinguish between left and right
2198 modifier keys, we know that, if no modifiers are set, then neither
2199 the left or right modifier should be set. */
2200 static void
2201 sync_modifiers (void)
2203 if (!modifiers_recorded)
2204 return;
2206 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2207 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2209 if (!(GetKeyState (VK_MENU) & 0x8000))
2210 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2213 static int
2214 modifier_set (int vkey)
2216 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2217 toggle keys is not an omission! If you want to add it, you will
2218 have to make changes in the default sub-case of the WM_KEYDOWN
2219 switch, because if the NUMLOCK modifier is set, the code there
2220 will directly convert any key that looks like an ASCII letter,
2221 and also downcase those that look like upper-case ASCII. */
2222 if (vkey == VK_CAPITAL)
2224 if (NILP (Vw32_enable_caps_lock))
2225 return 0;
2226 else
2227 return (GetKeyState (vkey) & 0x1);
2229 if (vkey == VK_SCROLL)
2231 if (NILP (Vw32_scroll_lock_modifier)
2232 /* w32-scroll-lock-modifier can be any non-nil value that is
2233 not one of the modifiers, in which case it shall be ignored. */
2234 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2235 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2236 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2237 || EQ (Vw32_scroll_lock_modifier, Qalt)
2238 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2239 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2240 return 0;
2241 else
2242 return (GetKeyState (vkey) & 0x1);
2245 if (!modifiers_recorded)
2246 return (GetKeyState (vkey) & 0x8000);
2248 switch (vkey)
2250 case VK_LCONTROL:
2251 return modifiers[EMACS_LCONTROL];
2252 case VK_RCONTROL:
2253 return modifiers[EMACS_RCONTROL];
2254 case VK_LMENU:
2255 return modifiers[EMACS_LMENU];
2256 case VK_RMENU:
2257 return modifiers[EMACS_RMENU];
2259 return (GetKeyState (vkey) & 0x8000);
2262 /* Convert between the modifier bits W32 uses and the modifier bits
2263 Emacs uses. */
2265 unsigned int
2266 w32_key_to_modifier (int key)
2268 Lisp_Object key_mapping;
2270 switch (key)
2272 case VK_LWIN:
2273 key_mapping = Vw32_lwindow_modifier;
2274 break;
2275 case VK_RWIN:
2276 key_mapping = Vw32_rwindow_modifier;
2277 break;
2278 case VK_APPS:
2279 key_mapping = Vw32_apps_modifier;
2280 break;
2281 case VK_SCROLL:
2282 key_mapping = Vw32_scroll_lock_modifier;
2283 break;
2284 default:
2285 key_mapping = Qnil;
2288 /* NB. This code runs in the input thread, asynchronously to the lisp
2289 thread, so we must be careful to ensure access to lisp data is
2290 thread-safe. The following code is safe because the modifier
2291 variable values are updated atomically from lisp and symbols are
2292 not relocated by GC. Also, we don't have to worry about seeing GC
2293 markbits here. */
2294 if (EQ (key_mapping, Qhyper))
2295 return hyper_modifier;
2296 if (EQ (key_mapping, Qsuper))
2297 return super_modifier;
2298 if (EQ (key_mapping, Qmeta))
2299 return meta_modifier;
2300 if (EQ (key_mapping, Qalt))
2301 return alt_modifier;
2302 if (EQ (key_mapping, Qctrl))
2303 return ctrl_modifier;
2304 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2305 return ctrl_modifier;
2306 if (EQ (key_mapping, Qshift))
2307 return shift_modifier;
2309 /* Don't generate any modifier if not explicitly requested. */
2310 return 0;
2313 static unsigned int
2314 w32_get_modifiers (void)
2316 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2317 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2318 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2319 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2320 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2321 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2322 (modifier_set (VK_MENU) ?
2323 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2326 /* We map the VK_* modifiers into console modifier constants
2327 so that we can use the same routines to handle both console
2328 and window input. */
2330 static int
2331 construct_console_modifiers (void)
2333 int mods;
2335 mods = 0;
2336 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2337 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2338 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2339 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2340 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2341 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2342 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2343 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2344 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2345 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2346 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2348 return mods;
2351 static int
2352 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2354 int mods;
2356 /* Convert to emacs modifiers. */
2357 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2359 return mods;
2362 unsigned int
2363 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2365 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2366 return virt_key;
2368 if (virt_key == VK_RETURN)
2369 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2371 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2372 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2374 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2375 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2377 if (virt_key == VK_CLEAR)
2378 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2380 return virt_key;
2383 /* List of special key combinations which w32 would normally capture,
2384 but Emacs should grab instead. Not directly visible to lisp, to
2385 simplify synchronization. Each item is an integer encoding a virtual
2386 key code and modifier combination to capture. */
2387 static Lisp_Object w32_grabbed_keys;
2389 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2390 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2391 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2392 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2394 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2395 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2396 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2398 /* Register hot-keys for reserved key combinations when Emacs has
2399 keyboard focus, since this is the only way Emacs can receive key
2400 combinations like Alt-Tab which are used by the system. */
2402 static void
2403 register_hot_keys (HWND hwnd)
2405 Lisp_Object keylist;
2407 /* Use CONSP, since we are called asynchronously. */
2408 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2410 Lisp_Object key = XCAR (keylist);
2412 /* Deleted entries get set to nil. */
2413 if (!INTEGERP (key))
2414 continue;
2416 RegisterHotKey (hwnd, HOTKEY_ID (key),
2417 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2421 static void
2422 unregister_hot_keys (HWND hwnd)
2424 Lisp_Object keylist;
2426 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2428 Lisp_Object key = XCAR (keylist);
2430 if (!INTEGERP (key))
2431 continue;
2433 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2437 #if EMACSDEBUG
2438 const char*
2439 w32_name_of_message (UINT msg)
2441 unsigned i;
2442 static char buf[64];
2443 static const struct {
2444 UINT msg;
2445 const char* name;
2446 } msgnames[] = {
2447 #define M(msg) { msg, # msg }
2448 M (WM_PAINT),
2449 M (WM_TIMER),
2450 M (WM_USER),
2451 M (WM_MOUSEMOVE),
2452 M (WM_LBUTTONUP),
2453 M (WM_KEYDOWN),
2454 M (WM_EMACS_KILL),
2455 M (WM_EMACS_CREATEWINDOW),
2456 M (WM_EMACS_DONE),
2457 M (WM_EMACS_CREATEVSCROLLBAR),
2458 M (WM_EMACS_CREATEHSCROLLBAR),
2459 M (WM_EMACS_SHOWWINDOW),
2460 M (WM_EMACS_SETWINDOWPOS),
2461 M (WM_EMACS_DESTROYWINDOW),
2462 M (WM_EMACS_TRACKPOPUPMENU),
2463 M (WM_EMACS_SETFOCUS),
2464 M (WM_EMACS_SETFOREGROUND),
2465 M (WM_EMACS_SETLOCALE),
2466 M (WM_EMACS_SETKEYBOARDLAYOUT),
2467 M (WM_EMACS_REGISTER_HOT_KEY),
2468 M (WM_EMACS_UNREGISTER_HOT_KEY),
2469 M (WM_EMACS_TOGGLE_LOCK_KEY),
2470 M (WM_EMACS_TRACK_CARET),
2471 M (WM_EMACS_DESTROY_CARET),
2472 M (WM_EMACS_SHOW_CARET),
2473 M (WM_EMACS_HIDE_CARET),
2474 M (WM_EMACS_SETCURSOR),
2475 M (WM_EMACS_SHOWCURSOR),
2476 M (WM_EMACS_PAINT),
2477 M (WM_CHAR),
2478 #undef M
2479 { 0, 0 }
2482 for (i = 0; msgnames[i].name; ++i)
2483 if (msgnames[i].msg == msg)
2484 return msgnames[i].name;
2486 sprintf (buf, "message 0x%04x", (unsigned)msg);
2487 return buf;
2489 #endif /* EMACSDEBUG */
2491 /* Here's an overview of how Emacs input works in GUI sessions on
2492 MS-Windows. (For description of non-GUI input, see the commentary
2493 before w32_console_read_socket in w32inevt.c.)
2495 System messages are read and processed by w32_msg_pump below. This
2496 function runs in a separate thread. It handles a small number of
2497 custom WM_EMACS_* messages (posted by the main thread, look for
2498 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2499 is the main window procedure for the entire Emacs application.
2501 w32_wnd_proc also runs in the same separate input thread. It
2502 handles some messages, mostly those that need GDI calls, by itself.
2503 For the others, it calls my_post_msg, which inserts the messages
2504 into the input queue serviced by w32_read_socket.
2506 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2507 called synchronously from keyboard.c when it is known or suspected
2508 that some input is available. w32_read_socket either handles
2509 messages immediately, or converts them into Emacs input events and
2510 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2511 them and process them when read_char and its callers require
2512 input.
2514 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2515 select(2) takes the place of w32_read_socket.
2519 /* Main message dispatch loop. */
2521 static void
2522 w32_msg_pump (deferred_msg * msg_buf)
2524 MSG msg;
2525 WPARAM result;
2526 HWND focus_window;
2528 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2530 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2533 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2534 /* w32_name_of_message (msg.message), msg.time)); */
2536 if (msg.hwnd == NULL)
2538 switch (msg.message)
2540 case WM_NULL:
2541 /* Produced by complete_deferred_msg; just ignore. */
2542 break;
2543 case WM_EMACS_CREATEWINDOW:
2544 /* Initialize COM for this window. Even though we don't use it,
2545 some third party shell extensions can cause it to be used in
2546 system dialogs, which causes a crash if it is not initialized.
2547 This is a known bug in Windows, which was fixed long ago, but
2548 the patch for XP is not publicly available until XP SP3,
2549 and older versions will never be patched. */
2550 CoInitialize (NULL);
2551 w32_createwindow ((struct frame *) msg.wParam,
2552 (int *) msg.lParam);
2553 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2554 emacs_abort ();
2555 break;
2556 case WM_EMACS_SETLOCALE:
2557 SetThreadLocale (msg.wParam);
2558 /* Reply is not expected. */
2559 break;
2560 case WM_EMACS_SETKEYBOARDLAYOUT:
2561 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2562 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2563 result, 0))
2564 emacs_abort ();
2565 break;
2566 case WM_EMACS_REGISTER_HOT_KEY:
2567 focus_window = GetFocus ();
2568 if (focus_window != NULL)
2569 RegisterHotKey (focus_window,
2570 RAW_HOTKEY_ID (msg.wParam),
2571 RAW_HOTKEY_MODIFIERS (msg.wParam),
2572 RAW_HOTKEY_VK_CODE (msg.wParam));
2573 /* Reply is not expected. */
2574 break;
2575 case WM_EMACS_UNREGISTER_HOT_KEY:
2576 focus_window = GetFocus ();
2577 if (focus_window != NULL)
2578 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2579 /* Mark item as erased. NB: this code must be
2580 thread-safe. The next line is okay because the cons
2581 cell is never made into garbage and is not relocated by
2582 GC. */
2583 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
2584 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2585 emacs_abort ();
2586 break;
2587 case WM_EMACS_TOGGLE_LOCK_KEY:
2589 int vk_code = (int) msg.wParam;
2590 int cur_state = (GetKeyState (vk_code) & 1);
2591 int new_state = msg.lParam;
2593 if (new_state == -1
2594 || ((new_state & 1) != cur_state))
2596 one_w32_display_info.faked_key = vk_code;
2598 keybd_event ((BYTE) vk_code,
2599 (BYTE) MapVirtualKey (vk_code, 0),
2600 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2601 keybd_event ((BYTE) vk_code,
2602 (BYTE) MapVirtualKey (vk_code, 0),
2603 KEYEVENTF_EXTENDEDKEY | 0, 0);
2604 keybd_event ((BYTE) vk_code,
2605 (BYTE) MapVirtualKey (vk_code, 0),
2606 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2607 cur_state = !cur_state;
2609 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2610 cur_state, 0))
2611 emacs_abort ();
2613 break;
2614 #ifdef MSG_DEBUG
2615 /* Broadcast messages make it here, so you need to be looking
2616 for something in particular for this to be useful. */
2617 default:
2618 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2619 #endif
2622 else
2624 if (w32_unicode_gui)
2625 DispatchMessageW (&msg);
2626 else
2627 DispatchMessageA (&msg);
2630 /* Exit nested loop when our deferred message has completed. */
2631 if (msg_buf->completed)
2632 break;
2636 deferred_msg * deferred_msg_head;
2638 static deferred_msg *
2639 find_deferred_msg (HWND hwnd, UINT msg)
2641 deferred_msg * item;
2643 /* Don't actually need synchronization for read access, since
2644 modification of single pointer is always atomic. */
2645 /* enter_crit (); */
2647 for (item = deferred_msg_head; item != NULL; item = item->next)
2648 if (item->w32msg.msg.hwnd == hwnd
2649 && item->w32msg.msg.message == msg)
2650 break;
2652 /* leave_crit (); */
2654 return item;
2657 static LRESULT
2658 send_deferred_msg (deferred_msg * msg_buf,
2659 HWND hwnd,
2660 UINT msg,
2661 WPARAM wParam,
2662 LPARAM lParam)
2664 /* Only input thread can send deferred messages. */
2665 if (GetCurrentThreadId () != dwWindowsThreadId)
2666 emacs_abort ();
2668 /* It is an error to send a message that is already deferred. */
2669 if (find_deferred_msg (hwnd, msg) != NULL)
2670 emacs_abort ();
2672 /* Enforced synchronization is not needed because this is the only
2673 function that alters deferred_msg_head, and the following critical
2674 section is guaranteed to only be serially reentered (since only the
2675 input thread can call us). */
2677 /* enter_crit (); */
2679 msg_buf->completed = 0;
2680 msg_buf->next = deferred_msg_head;
2681 deferred_msg_head = msg_buf;
2682 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2684 /* leave_crit (); */
2686 /* Start a new nested message loop to process other messages until
2687 this one is completed. */
2688 w32_msg_pump (msg_buf);
2690 deferred_msg_head = msg_buf->next;
2692 return msg_buf->result;
2695 void
2696 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2698 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2700 if (msg_buf == NULL)
2701 /* Message may have been canceled, so don't abort. */
2702 return;
2704 msg_buf->result = result;
2705 msg_buf->completed = 1;
2707 /* Ensure input thread is woken so it notices the completion. */
2708 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2711 static void
2712 cancel_all_deferred_msgs (void)
2714 deferred_msg * item;
2716 /* Don't actually need synchronization for read access, since
2717 modification of single pointer is always atomic. */
2718 /* enter_crit (); */
2720 for (item = deferred_msg_head; item != NULL; item = item->next)
2722 item->result = 0;
2723 item->completed = 1;
2726 /* leave_crit (); */
2728 /* Ensure input thread is woken so it notices the completion. */
2729 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2732 DWORD WINAPI
2733 w32_msg_worker (void *arg)
2735 MSG msg;
2736 deferred_msg dummy_buf;
2738 /* Ensure our message queue is created */
2740 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2742 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2743 emacs_abort ();
2745 memset (&dummy_buf, 0, sizeof (dummy_buf));
2746 dummy_buf.w32msg.msg.hwnd = NULL;
2747 dummy_buf.w32msg.msg.message = WM_NULL;
2749 /* This is the initial message loop which should only exit when the
2750 application quits. */
2751 w32_msg_pump (&dummy_buf);
2753 return 0;
2756 static void
2757 signal_user_input (void)
2759 /* Interrupt any lisp that wants to be interrupted by input. */
2760 if (!NILP (Vthrow_on_input))
2762 Vquit_flag = Vthrow_on_input;
2763 /* Doing a QUIT from this thread is a bad idea, since this
2764 unwinds the stack of the Lisp thread, and the Windows runtime
2765 rightfully barfs. Disabled. */
2766 #if 0
2767 /* If we're inside a function that wants immediate quits,
2768 do it now. */
2769 if (immediate_quit && NILP (Vinhibit_quit))
2771 immediate_quit = 0;
2772 QUIT;
2774 #endif
2779 static void
2780 post_character_message (HWND hwnd, UINT msg,
2781 WPARAM wParam, LPARAM lParam,
2782 DWORD modifiers)
2784 W32Msg wmsg;
2786 wmsg.dwModifiers = modifiers;
2788 /* Detect quit_char and set quit-flag directly. Note that we
2789 still need to post a message to ensure the main thread will be
2790 woken up if blocked in sys_select, but we do NOT want to post
2791 the quit_char message itself (because it will usually be as if
2792 the user had typed quit_char twice). Instead, we post a dummy
2793 message that has no particular effect. */
2795 int c = wParam;
2796 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2797 c = make_ctrl_char (c) & 0377;
2798 if (c == quit_char
2799 || (wmsg.dwModifiers == 0
2800 && w32_quit_key && wParam == w32_quit_key))
2802 Vquit_flag = Qt;
2804 /* The choice of message is somewhat arbitrary, as long as
2805 the main thread handler just ignores it. */
2806 msg = WM_NULL;
2808 /* Interrupt any blocking system calls. */
2809 signal_quit ();
2811 /* As a safety precaution, forcibly complete any deferred
2812 messages. This is a kludge, but I don't see any particularly
2813 clean way to handle the situation where a deferred message is
2814 "dropped" in the lisp thread, and will thus never be
2815 completed, eg. by the user trying to activate the menubar
2816 when the lisp thread is busy, and then typing C-g when the
2817 menubar doesn't open promptly (with the result that the
2818 menubar never responds at all because the deferred
2819 WM_INITMENU message is never completed). Another problem
2820 situation is when the lisp thread calls SendMessage (to send
2821 a window manager command) when a message has been deferred;
2822 the lisp thread gets blocked indefinitely waiting for the
2823 deferred message to be completed, which itself is waiting for
2824 the lisp thread to respond.
2826 Note that we don't want to block the input thread waiting for
2827 a response from the lisp thread (although that would at least
2828 solve the deadlock problem above), because we want to be able
2829 to receive C-g to interrupt the lisp thread. */
2830 cancel_all_deferred_msgs ();
2832 else
2833 signal_user_input ();
2836 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2839 /* Main window procedure */
2841 static LRESULT CALLBACK
2842 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2844 struct frame *f;
2845 struct w32_display_info *dpyinfo = &one_w32_display_info;
2846 W32Msg wmsg;
2847 int windows_translate;
2848 int key;
2850 /* Note that it is okay to call x_window_to_frame, even though we are
2851 not running in the main lisp thread, because frame deletion
2852 requires the lisp thread to synchronize with this thread. Thus, if
2853 a frame struct is returned, it can be used without concern that the
2854 lisp thread might make it disappear while we are using it.
2856 NB. Walking the frame list in this thread is safe (as long as
2857 writes of Lisp_Object slots are atomic, which they are on Windows).
2858 Although delete-frame can destructively modify the frame list while
2859 we are walking it, a garbage collection cannot occur until after
2860 delete-frame has synchronized with this thread.
2862 It is also safe to use functions that make GDI calls, such as
2863 w32_clear_rect, because these functions must obtain a DC handle
2864 from the frame struct using get_frame_dc which is thread-aware. */
2866 switch (msg)
2868 case WM_ERASEBKGND:
2869 f = x_window_to_frame (dpyinfo, hwnd);
2870 if (f)
2872 HDC hdc = get_frame_dc (f);
2873 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2874 w32_clear_rect (f, hdc, &wmsg.rect);
2875 release_frame_dc (f, hdc);
2877 #if defined (W32_DEBUG_DISPLAY)
2878 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2880 wmsg.rect.left, wmsg.rect.top,
2881 wmsg.rect.right, wmsg.rect.bottom));
2882 #endif /* W32_DEBUG_DISPLAY */
2884 return 1;
2885 case WM_PALETTECHANGED:
2886 /* ignore our own changes */
2887 if ((HWND)wParam != hwnd)
2889 f = x_window_to_frame (dpyinfo, hwnd);
2890 if (f)
2891 /* get_frame_dc will realize our palette and force all
2892 frames to be redrawn if needed. */
2893 release_frame_dc (f, get_frame_dc (f));
2895 return 0;
2896 case WM_PAINT:
2898 PAINTSTRUCT paintStruct;
2899 RECT update_rect;
2900 memset (&update_rect, 0, sizeof (update_rect));
2902 f = x_window_to_frame (dpyinfo, hwnd);
2903 if (f == 0)
2905 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2906 return 0;
2909 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2910 fails. Apparently this can happen under some
2911 circumstances. */
2912 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2914 enter_crit ();
2915 BeginPaint (hwnd, &paintStruct);
2917 /* The rectangles returned by GetUpdateRect and BeginPaint
2918 do not always match. Play it safe by assuming both areas
2919 are invalid. */
2920 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2922 #if defined (W32_DEBUG_DISPLAY)
2923 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2925 wmsg.rect.left, wmsg.rect.top,
2926 wmsg.rect.right, wmsg.rect.bottom));
2927 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2928 update_rect.left, update_rect.top,
2929 update_rect.right, update_rect.bottom));
2930 #endif
2931 EndPaint (hwnd, &paintStruct);
2932 leave_crit ();
2934 /* Change the message type to prevent Windows from
2935 combining WM_PAINT messages in the Lisp thread's queue,
2936 since Windows assumes that each message queue is
2937 dedicated to one frame and does not bother checking
2938 that hwnd matches before combining them. */
2939 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
2941 return 0;
2944 /* If GetUpdateRect returns 0 (meaning there is no update
2945 region), assume the whole window needs to be repainted. */
2946 GetClientRect (hwnd, &wmsg.rect);
2947 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2948 return 0;
2951 case WM_INPUTLANGCHANGE:
2952 /* Inform lisp thread of keyboard layout changes. */
2953 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2955 /* Clear dead keys in the keyboard state; for simplicity only
2956 preserve modifier key states. */
2958 int i;
2959 BYTE keystate[256];
2961 GetKeyboardState (keystate);
2962 for (i = 0; i < 256; i++)
2963 if (1
2964 && i != VK_SHIFT
2965 && i != VK_LSHIFT
2966 && i != VK_RSHIFT
2967 && i != VK_CAPITAL
2968 && i != VK_NUMLOCK
2969 && i != VK_SCROLL
2970 && i != VK_CONTROL
2971 && i != VK_LCONTROL
2972 && i != VK_RCONTROL
2973 && i != VK_MENU
2974 && i != VK_LMENU
2975 && i != VK_RMENU
2976 && i != VK_LWIN
2977 && i != VK_RWIN)
2978 keystate[i] = 0;
2979 SetKeyboardState (keystate);
2981 goto dflt;
2983 case WM_HOTKEY:
2984 /* Synchronize hot keys with normal input. */
2985 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2986 return (0);
2988 case WM_KEYUP:
2989 case WM_SYSKEYUP:
2990 record_keyup (wParam, lParam);
2991 goto dflt;
2993 case WM_KEYDOWN:
2994 case WM_SYSKEYDOWN:
2995 /* Ignore keystrokes we fake ourself; see below. */
2996 if (dpyinfo->faked_key == wParam)
2998 dpyinfo->faked_key = 0;
2999 /* Make sure TranslateMessage sees them though (as long as
3000 they don't produce WM_CHAR messages). This ensures that
3001 indicator lights are toggled promptly on Windows 9x, for
3002 example. */
3003 if (wParam < 256 && lispy_function_keys[wParam])
3005 windows_translate = 1;
3006 goto translate;
3008 return 0;
3011 /* Synchronize modifiers with current keystroke. */
3012 sync_modifiers ();
3013 record_keydown (wParam, lParam);
3014 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
3016 windows_translate = 0;
3018 switch (wParam)
3020 case VK_LWIN:
3021 if (NILP (Vw32_pass_lwindow_to_system))
3023 /* Prevent system from acting on keyup (which opens the
3024 Start menu if no other key was pressed) by simulating a
3025 press of Space which we will ignore. */
3026 if (GetAsyncKeyState (wParam) & 1)
3028 if (NUMBERP (Vw32_phantom_key_code))
3029 key = XUINT (Vw32_phantom_key_code) & 255;
3030 else
3031 key = VK_SPACE;
3032 dpyinfo->faked_key = key;
3033 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3036 if (!NILP (Vw32_lwindow_modifier))
3037 return 0;
3038 break;
3039 case VK_RWIN:
3040 if (NILP (Vw32_pass_rwindow_to_system))
3042 if (GetAsyncKeyState (wParam) & 1)
3044 if (NUMBERP (Vw32_phantom_key_code))
3045 key = XUINT (Vw32_phantom_key_code) & 255;
3046 else
3047 key = VK_SPACE;
3048 dpyinfo->faked_key = key;
3049 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3052 if (!NILP (Vw32_rwindow_modifier))
3053 return 0;
3054 break;
3055 case VK_APPS:
3056 if (!NILP (Vw32_apps_modifier))
3057 return 0;
3058 break;
3059 case VK_MENU:
3060 if (NILP (Vw32_pass_alt_to_system))
3061 /* Prevent DefWindowProc from activating the menu bar if an
3062 Alt key is pressed and released by itself. */
3063 return 0;
3064 windows_translate = 1;
3065 break;
3066 case VK_CAPITAL:
3067 /* Decide whether to treat as modifier or function key. */
3068 if (NILP (Vw32_enable_caps_lock))
3069 goto disable_lock_key;
3070 windows_translate = 1;
3071 break;
3072 case VK_NUMLOCK:
3073 /* Decide whether to treat as modifier or function key. */
3074 if (NILP (Vw32_enable_num_lock))
3075 goto disable_lock_key;
3076 windows_translate = 1;
3077 break;
3078 case VK_SCROLL:
3079 /* Decide whether to treat as modifier or function key. */
3080 if (NILP (Vw32_scroll_lock_modifier))
3081 goto disable_lock_key;
3082 windows_translate = 1;
3083 break;
3084 disable_lock_key:
3085 /* Ensure the appropriate lock key state (and indicator light)
3086 remains in the same state. We do this by faking another
3087 press of the relevant key. Apparently, this really is the
3088 only way to toggle the state of the indicator lights. */
3089 dpyinfo->faked_key = wParam;
3090 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3091 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3092 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3093 KEYEVENTF_EXTENDEDKEY | 0, 0);
3094 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3095 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3096 /* Ensure indicator lights are updated promptly on Windows 9x
3097 (TranslateMessage apparently does this), after forwarding
3098 input event. */
3099 post_character_message (hwnd, msg, wParam, lParam,
3100 w32_get_key_modifiers (wParam, lParam));
3101 windows_translate = 1;
3102 break;
3103 case VK_CONTROL:
3104 case VK_SHIFT:
3105 case VK_PROCESSKEY: /* Generated by IME. */
3106 windows_translate = 1;
3107 break;
3108 case VK_CANCEL:
3109 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3110 which is confusing for purposes of key binding; convert
3111 VK_CANCEL events into VK_PAUSE events. */
3112 wParam = VK_PAUSE;
3113 break;
3114 case VK_PAUSE:
3115 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3116 for purposes of key binding; convert these back into
3117 VK_NUMLOCK events, at least when we want to see NumLock key
3118 presses. (Note that there is never any possibility that
3119 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3120 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3121 wParam = VK_NUMLOCK;
3122 break;
3123 default:
3124 /* If not defined as a function key, change it to a WM_CHAR message. */
3125 if (wParam > 255 || !lispy_function_keys[wParam])
3127 DWORD modifiers = construct_console_modifiers ();
3129 if (!NILP (Vw32_recognize_altgr)
3130 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3132 /* Always let TranslateMessage handle AltGr key chords;
3133 for some reason, ToAscii doesn't always process AltGr
3134 chords correctly. */
3135 windows_translate = 1;
3137 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3139 /* Handle key chords including any modifiers other
3140 than shift directly, in order to preserve as much
3141 modifier information as possible. */
3142 if ('A' <= wParam && wParam <= 'Z')
3144 /* Don't translate modified alphabetic keystrokes,
3145 so the user doesn't need to constantly switch
3146 layout to type control or meta keystrokes when
3147 the normal layout translates alphabetic
3148 characters to non-ascii characters. */
3149 if (!modifier_set (VK_SHIFT))
3150 wParam += ('a' - 'A');
3151 msg = WM_CHAR;
3153 else
3155 /* Try to handle other keystrokes by determining the
3156 base character (ie. translating the base key plus
3157 shift modifier). */
3158 int add;
3159 KEY_EVENT_RECORD key;
3161 key.bKeyDown = TRUE;
3162 key.wRepeatCount = 1;
3163 key.wVirtualKeyCode = wParam;
3164 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3165 key.uChar.AsciiChar = 0;
3166 key.dwControlKeyState = modifiers;
3168 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3169 /* 0 means an unrecognized keycode, negative means
3170 dead key. Ignore both. */
3171 while (--add >= 0)
3173 /* Forward asciified character sequence. */
3174 post_character_message
3175 (hwnd, WM_CHAR,
3176 (unsigned char) key.uChar.AsciiChar, lParam,
3177 w32_get_key_modifiers (wParam, lParam));
3178 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3180 return 0;
3183 else
3185 /* Let TranslateMessage handle everything else. */
3186 windows_translate = 1;
3191 translate:
3192 if (windows_translate)
3194 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3195 windows_msg.time = GetMessageTime ();
3196 TranslateMessage (&windows_msg);
3197 goto dflt;
3200 /* Fall through */
3202 case WM_SYSCHAR:
3203 case WM_CHAR:
3204 if (wParam > 255 )
3206 W32Msg wmsg;
3208 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3209 signal_user_input ();
3210 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3213 else
3214 post_character_message (hwnd, msg, wParam, lParam,
3215 w32_get_key_modifiers (wParam, lParam));
3216 break;
3218 case WM_UNICHAR:
3219 /* WM_UNICHAR looks promising from the docs, but the exact
3220 circumstances in which TranslateMessage sends it is one of those
3221 Microsoft secret API things that EU and US courts are supposed
3222 to have put a stop to already. Spy++ shows it being sent to Notepad
3223 and other MS apps, but never to Emacs.
3225 Some third party IMEs send it in accordance with the official
3226 documentation though, so handle it here.
3228 UNICODE_NOCHAR is used to test for support for this message.
3229 TRUE indicates that the message is supported. */
3230 if (wParam == UNICODE_NOCHAR)
3231 return TRUE;
3234 W32Msg wmsg;
3235 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3236 signal_user_input ();
3237 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3239 break;
3241 case WM_IME_CHAR:
3242 /* If we can't get the IME result as Unicode, use default processing,
3243 which will at least allow characters decodable in the system locale
3244 get through. */
3245 if (!get_composition_string_fn)
3246 goto dflt;
3248 else if (!ignore_ime_char)
3250 wchar_t * buffer;
3251 int size, i;
3252 W32Msg wmsg;
3253 HIMC context = get_ime_context_fn (hwnd);
3254 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3255 /* Get buffer size. */
3256 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3257 buffer = alloca (size);
3258 size = get_composition_string_fn (context, GCS_RESULTSTR,
3259 buffer, size);
3260 release_ime_context_fn (hwnd, context);
3262 signal_user_input ();
3263 for (i = 0; i < size / sizeof (wchar_t); i++)
3265 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3266 lParam);
3268 /* Ignore the messages for the rest of the
3269 characters in the string that was output above. */
3270 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3272 else
3273 ignore_ime_char--;
3275 break;
3277 case WM_IME_STARTCOMPOSITION:
3278 if (!set_ime_composition_window_fn)
3279 goto dflt;
3280 else
3282 COMPOSITIONFORM form;
3283 HIMC context;
3284 struct window *w;
3286 /* Implementation note: The code below does something that
3287 one shouldn't do: it accesses the window object from a
3288 separate thread, while the main (a.k.a. "Lisp") thread
3289 runs and can legitimately delete and even GC it. That is
3290 why we are extra careful not to futz with a window that
3291 is different from the one recorded when the system caret
3292 coordinates were last modified. That is also why we are
3293 careful not to move the IME window if the window
3294 described by W was deleted, as indicated by its buffer
3295 field being reset to nil. */
3296 f = x_window_to_frame (dpyinfo, hwnd);
3297 if (!(f && FRAME_LIVE_P (f)))
3298 break;
3299 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3300 /* Punt if someone changed the frame's selected window
3301 behind our back. */
3302 if (w != w32_system_caret_window)
3303 break;
3305 form.dwStyle = CFS_RECT;
3306 form.ptCurrentPos.x = w32_system_caret_x;
3307 form.ptCurrentPos.y = w32_system_caret_y;
3309 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3310 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3311 + w32_system_caret_hdr_height);
3312 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3313 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3314 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3315 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3316 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3317 - w32_system_caret_mode_height);
3319 /* Punt if the window was deleted behind our back. */
3320 if (!BUFFERP (w->contents))
3321 break;
3323 context = get_ime_context_fn (hwnd);
3325 if (!context)
3326 break;
3328 set_ime_composition_window_fn (context, &form);
3329 release_ime_context_fn (hwnd, context);
3331 break;
3333 case WM_IME_ENDCOMPOSITION:
3334 ignore_ime_char = 0;
3335 goto dflt;
3337 /* Simulate middle mouse button events when left and right buttons
3338 are used together, but only if user has two button mouse. */
3339 case WM_LBUTTONDOWN:
3340 case WM_RBUTTONDOWN:
3341 if (w32_num_mouse_buttons > 2)
3342 goto handle_plain_button;
3345 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3346 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3348 if (button_state & this)
3349 return 0;
3351 if (button_state == 0)
3352 SetCapture (hwnd);
3354 button_state |= this;
3356 if (button_state & other)
3358 if (mouse_button_timer)
3360 KillTimer (hwnd, mouse_button_timer);
3361 mouse_button_timer = 0;
3363 /* Generate middle mouse event instead. */
3364 msg = WM_MBUTTONDOWN;
3365 button_state |= MMOUSE;
3367 else if (button_state & MMOUSE)
3369 /* Ignore button event if we've already generated a
3370 middle mouse down event. This happens if the
3371 user releases and press one of the two buttons
3372 after we've faked a middle mouse event. */
3373 return 0;
3375 else
3377 /* Flush out saved message. */
3378 post_msg (&saved_mouse_button_msg);
3380 wmsg.dwModifiers = w32_get_modifiers ();
3381 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3382 signal_user_input ();
3384 /* Clear message buffer. */
3385 saved_mouse_button_msg.msg.hwnd = 0;
3387 else
3389 /* Hold onto message for now. */
3390 mouse_button_timer =
3391 SetTimer (hwnd, MOUSE_BUTTON_ID,
3392 w32_mouse_button_tolerance, NULL);
3393 saved_mouse_button_msg.msg.hwnd = hwnd;
3394 saved_mouse_button_msg.msg.message = msg;
3395 saved_mouse_button_msg.msg.wParam = wParam;
3396 saved_mouse_button_msg.msg.lParam = lParam;
3397 saved_mouse_button_msg.msg.time = GetMessageTime ();
3398 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3401 return 0;
3403 case WM_LBUTTONUP:
3404 case WM_RBUTTONUP:
3405 if (w32_num_mouse_buttons > 2)
3406 goto handle_plain_button;
3409 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3410 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3412 if ((button_state & this) == 0)
3413 return 0;
3415 button_state &= ~this;
3417 if (button_state & MMOUSE)
3419 /* Only generate event when second button is released. */
3420 if ((button_state & other) == 0)
3422 msg = WM_MBUTTONUP;
3423 button_state &= ~MMOUSE;
3425 if (button_state) emacs_abort ();
3427 else
3428 return 0;
3430 else
3432 /* Flush out saved message if necessary. */
3433 if (saved_mouse_button_msg.msg.hwnd)
3435 post_msg (&saved_mouse_button_msg);
3438 wmsg.dwModifiers = w32_get_modifiers ();
3439 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3440 signal_user_input ();
3442 /* Always clear message buffer and cancel timer. */
3443 saved_mouse_button_msg.msg.hwnd = 0;
3444 KillTimer (hwnd, mouse_button_timer);
3445 mouse_button_timer = 0;
3447 if (button_state == 0)
3448 ReleaseCapture ();
3450 return 0;
3452 case WM_XBUTTONDOWN:
3453 case WM_XBUTTONUP:
3454 if (w32_pass_extra_mouse_buttons_to_system)
3455 goto dflt;
3456 /* else fall through and process them. */
3457 case WM_MBUTTONDOWN:
3458 case WM_MBUTTONUP:
3459 handle_plain_button:
3461 BOOL up;
3462 int button;
3464 /* Ignore middle and extra buttons as long as the menu is active. */
3465 f = x_window_to_frame (dpyinfo, hwnd);
3466 if (f && f->output_data.w32->menubar_active)
3467 return 0;
3469 if (parse_button (msg, HIWORD (wParam), &button, &up))
3471 if (up) ReleaseCapture ();
3472 else SetCapture (hwnd);
3473 button = (button == 0) ? LMOUSE :
3474 ((button == 1) ? MMOUSE : RMOUSE);
3475 if (up)
3476 button_state &= ~button;
3477 else
3478 button_state |= button;
3482 wmsg.dwModifiers = w32_get_modifiers ();
3483 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3484 signal_user_input ();
3486 /* Need to return true for XBUTTON messages, false for others,
3487 to indicate that we processed the message. */
3488 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3490 case WM_MOUSEMOVE:
3491 /* Ignore mouse movements as long as the menu is active. These
3492 movements are processed by the window manager anyway, and
3493 it's wrong to handle them as if they happened on the
3494 underlying frame. */
3495 f = x_window_to_frame (dpyinfo, hwnd);
3496 if (f && f->output_data.w32->menubar_active)
3497 return 0;
3499 /* If the mouse has just moved into the frame, start tracking
3500 it, so we will be notified when it leaves the frame. Mouse
3501 tracking only works under W98 and NT4 and later. On earlier
3502 versions, there is no way of telling when the mouse leaves the
3503 frame, so we just have to put up with help-echo and mouse
3504 highlighting remaining while the frame is not active. */
3505 if (track_mouse_event_fn && !track_mouse_window
3506 /* If the menu bar is active, turning on tracking of mouse
3507 movement events might send these events to the tooltip
3508 frame, if the user happens to move the mouse pointer over
3509 the tooltip. But since we don't process events for
3510 tooltip frames, this causes Windows to present a
3511 hourglass cursor, which is ugly and unexpected. So don't
3512 enable tracking mouse events in this case; they will be
3513 restarted when the menu pops down. (Confusingly, the
3514 menubar_active member of f->output_data.w32, tested
3515 above, is only set when a menu was popped up _not_ from
3516 the frame's menu bar, but via x-popup-menu.) */
3517 && !menubar_in_use)
3519 TRACKMOUSEEVENT tme;
3520 tme.cbSize = sizeof (tme);
3521 tme.dwFlags = TME_LEAVE;
3522 tme.hwndTrack = hwnd;
3523 tme.dwHoverTime = HOVER_DEFAULT;
3525 track_mouse_event_fn (&tme);
3526 track_mouse_window = hwnd;
3528 case WM_HSCROLL:
3529 case WM_VSCROLL:
3530 if (w32_mouse_move_interval <= 0
3531 || (msg == WM_MOUSEMOVE && button_state == 0))
3533 wmsg.dwModifiers = w32_get_modifiers ();
3534 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3535 return 0;
3538 /* Hang onto mouse move and scroll messages for a bit, to avoid
3539 sending such events to Emacs faster than it can process them.
3540 If we get more events before the timer from the first message
3541 expires, we just replace the first message. */
3543 if (saved_mouse_move_msg.msg.hwnd == 0)
3544 mouse_move_timer =
3545 SetTimer (hwnd, MOUSE_MOVE_ID,
3546 w32_mouse_move_interval, NULL);
3548 /* Hold onto message for now. */
3549 saved_mouse_move_msg.msg.hwnd = hwnd;
3550 saved_mouse_move_msg.msg.message = msg;
3551 saved_mouse_move_msg.msg.wParam = wParam;
3552 saved_mouse_move_msg.msg.lParam = lParam;
3553 saved_mouse_move_msg.msg.time = GetMessageTime ();
3554 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3556 return 0;
3558 case WM_MOUSEWHEEL:
3559 case WM_DROPFILES:
3560 wmsg.dwModifiers = w32_get_modifiers ();
3561 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3562 signal_user_input ();
3563 return 0;
3565 case WM_APPCOMMAND:
3566 if (w32_pass_multimedia_buttons_to_system)
3567 goto dflt;
3568 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3569 case WM_MOUSEHWHEEL:
3570 wmsg.dwModifiers = w32_get_modifiers ();
3571 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3572 signal_user_input ();
3573 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3574 handled, to prevent the system trying to handle it by faking
3575 scroll bar events. */
3576 return 1;
3578 case WM_TIMER:
3579 /* Flush out saved messages if necessary. */
3580 if (wParam == mouse_button_timer)
3582 if (saved_mouse_button_msg.msg.hwnd)
3584 post_msg (&saved_mouse_button_msg);
3585 signal_user_input ();
3586 saved_mouse_button_msg.msg.hwnd = 0;
3588 KillTimer (hwnd, mouse_button_timer);
3589 mouse_button_timer = 0;
3591 else if (wParam == mouse_move_timer)
3593 if (saved_mouse_move_msg.msg.hwnd)
3595 post_msg (&saved_mouse_move_msg);
3596 saved_mouse_move_msg.msg.hwnd = 0;
3598 KillTimer (hwnd, mouse_move_timer);
3599 mouse_move_timer = 0;
3601 else if (wParam == menu_free_timer)
3603 KillTimer (hwnd, menu_free_timer);
3604 menu_free_timer = 0;
3605 f = x_window_to_frame (dpyinfo, hwnd);
3606 /* If a popup menu is active, don't wipe its strings. */
3607 if (menubar_in_use
3608 && current_popup_menu == NULL)
3610 /* Free memory used by owner-drawn and help-echo strings. */
3611 w32_free_menu_strings (hwnd);
3612 if (f)
3613 f->output_data.w32->menubar_active = 0;
3614 menubar_in_use = 0;
3617 return 0;
3619 case WM_NCACTIVATE:
3620 /* Windows doesn't send us focus messages when putting up and
3621 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3622 The only indication we get that something happened is receiving
3623 this message afterwards. So this is a good time to reset our
3624 keyboard modifiers' state. */
3625 reset_modifiers ();
3626 goto dflt;
3628 case WM_INITMENU:
3629 button_state = 0;
3630 ReleaseCapture ();
3631 /* We must ensure menu bar is fully constructed and up to date
3632 before allowing user interaction with it. To achieve this
3633 we send this message to the lisp thread and wait for a
3634 reply (whose value is not actually needed) to indicate that
3635 the menu bar is now ready for use, so we can now return.
3637 To remain responsive in the meantime, we enter a nested message
3638 loop that can process all other messages.
3640 However, we skip all this if the message results from calling
3641 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3642 thread a message because it is blocked on us at this point. We
3643 set menubar_active before calling TrackPopupMenu to indicate
3644 this (there is no possibility of confusion with real menubar
3645 being active). */
3647 f = x_window_to_frame (dpyinfo, hwnd);
3648 if (f
3649 && (f->output_data.w32->menubar_active
3650 /* We can receive this message even in the absence of a
3651 menubar (ie. when the system menu is activated) - in this
3652 case we do NOT want to forward the message, otherwise it
3653 will cause the menubar to suddenly appear when the user
3654 had requested it to be turned off! */
3655 || f->output_data.w32->menubar_widget == NULL))
3656 return 0;
3659 deferred_msg msg_buf;
3661 /* Detect if message has already been deferred; in this case
3662 we cannot return any sensible value to ignore this. */
3663 if (find_deferred_msg (hwnd, msg) != NULL)
3664 emacs_abort ();
3666 menubar_in_use = 1;
3668 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3671 case WM_EXITMENULOOP:
3672 f = x_window_to_frame (dpyinfo, hwnd);
3674 /* If a menu is still active, check again after a short delay,
3675 since Windows often (always?) sends the WM_EXITMENULOOP
3676 before the corresponding WM_COMMAND message.
3677 Don't do this if a popup menu is active, since it is only
3678 menubar menus that require cleaning up in this way.
3680 if (f && menubar_in_use && current_popup_menu == NULL)
3681 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3683 /* If hourglass cursor should be displayed, display it now. */
3684 if (f && f->output_data.w32->hourglass_p)
3685 SetCursor (f->output_data.w32->hourglass_cursor);
3687 goto dflt;
3689 case WM_MENUSELECT:
3690 /* Direct handling of help_echo in menus. Should be safe now
3691 that we generate the help_echo by placing a help event in the
3692 keyboard buffer. */
3694 HMENU menu = (HMENU) lParam;
3695 UINT menu_item = (UINT) LOWORD (wParam);
3696 UINT flags = (UINT) HIWORD (wParam);
3698 w32_menu_display_help (hwnd, menu, menu_item, flags);
3700 return 0;
3702 case WM_MEASUREITEM:
3703 f = x_window_to_frame (dpyinfo, hwnd);
3704 if (f)
3706 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3708 if (pMis->CtlType == ODT_MENU)
3710 /* Work out dimensions for popup menu titles. */
3711 char * title = (char *) pMis->itemData;
3712 HDC hdc = GetDC (hwnd);
3713 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3714 LOGFONT menu_logfont;
3715 HFONT old_font;
3716 SIZE size;
3718 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3719 menu_logfont.lfWeight = FW_BOLD;
3720 menu_font = CreateFontIndirect (&menu_logfont);
3721 old_font = SelectObject (hdc, menu_font);
3723 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3724 if (title)
3726 if (unicode_append_menu)
3727 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3728 wcslen ((WCHAR *) title),
3729 &size);
3730 else
3731 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3733 pMis->itemWidth = size.cx;
3734 if (pMis->itemHeight < size.cy)
3735 pMis->itemHeight = size.cy;
3737 else
3738 pMis->itemWidth = 0;
3740 SelectObject (hdc, old_font);
3741 DeleteObject (menu_font);
3742 ReleaseDC (hwnd, hdc);
3743 return TRUE;
3746 return 0;
3748 case WM_DRAWITEM:
3749 f = x_window_to_frame (dpyinfo, hwnd);
3750 if (f)
3752 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3754 if (pDis->CtlType == ODT_MENU)
3756 /* Draw popup menu title. */
3757 char * title = (char *) pDis->itemData;
3758 if (title)
3760 HDC hdc = pDis->hDC;
3761 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3762 LOGFONT menu_logfont;
3763 HFONT old_font;
3765 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3766 menu_logfont.lfWeight = FW_BOLD;
3767 menu_font = CreateFontIndirect (&menu_logfont);
3768 old_font = SelectObject (hdc, menu_font);
3770 /* Always draw title as if not selected. */
3771 if (unicode_append_menu)
3772 ExtTextOutW (hdc,
3773 pDis->rcItem.left
3774 + GetSystemMetrics (SM_CXMENUCHECK),
3775 pDis->rcItem.top,
3776 ETO_OPAQUE, &pDis->rcItem,
3777 (WCHAR *) title,
3778 wcslen ((WCHAR *) title), NULL);
3779 else
3780 ExtTextOut (hdc,
3781 pDis->rcItem.left
3782 + GetSystemMetrics (SM_CXMENUCHECK),
3783 pDis->rcItem.top,
3784 ETO_OPAQUE, &pDis->rcItem,
3785 title, strlen (title), NULL);
3787 SelectObject (hdc, old_font);
3788 DeleteObject (menu_font);
3790 return TRUE;
3793 return 0;
3795 #if 0
3796 /* Still not right - can't distinguish between clicks in the
3797 client area of the frame from clicks forwarded from the scroll
3798 bars - may have to hook WM_NCHITTEST to remember the mouse
3799 position and then check if it is in the client area ourselves. */
3800 case WM_MOUSEACTIVATE:
3801 /* Discard the mouse click that activates a frame, allowing the
3802 user to click anywhere without changing point (or worse!).
3803 Don't eat mouse clicks on scrollbars though!! */
3804 if (LOWORD (lParam) == HTCLIENT )
3805 return MA_ACTIVATEANDEAT;
3806 goto dflt;
3807 #endif
3809 case WM_MOUSELEAVE:
3810 /* No longer tracking mouse. */
3811 track_mouse_window = NULL;
3813 case WM_ACTIVATEAPP:
3814 case WM_ACTIVATE:
3815 case WM_WINDOWPOSCHANGED:
3816 case WM_SHOWWINDOW:
3817 /* Inform lisp thread that a frame might have just been obscured
3818 or exposed, so should recheck visibility of all frames. */
3819 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3820 goto dflt;
3822 case WM_SETFOCUS:
3823 dpyinfo->faked_key = 0;
3824 reset_modifiers ();
3825 register_hot_keys (hwnd);
3826 goto command;
3827 case WM_KILLFOCUS:
3828 unregister_hot_keys (hwnd);
3829 button_state = 0;
3830 ReleaseCapture ();
3831 /* Relinquish the system caret. */
3832 if (w32_system_caret_hwnd)
3834 w32_visible_system_caret_hwnd = NULL;
3835 w32_system_caret_hwnd = NULL;
3836 DestroyCaret ();
3838 goto command;
3839 case WM_COMMAND:
3840 menubar_in_use = 0;
3841 f = x_window_to_frame (dpyinfo, hwnd);
3842 if (f && HIWORD (wParam) == 0)
3844 if (menu_free_timer)
3846 KillTimer (hwnd, menu_free_timer);
3847 menu_free_timer = 0;
3850 case WM_MOVE:
3851 case WM_SIZE:
3852 command:
3853 wmsg.dwModifiers = w32_get_modifiers ();
3854 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3855 goto dflt;
3857 case WM_DESTROY:
3858 CoUninitialize ();
3859 return 0;
3861 case WM_CLOSE:
3862 wmsg.dwModifiers = w32_get_modifiers ();
3863 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3864 return 0;
3866 case WM_WINDOWPOSCHANGING:
3867 /* Don't restrict the sizing of any kind of frames. If the window
3868 manager doesn't, there's no reason to do it ourselves. */
3869 #if 0
3870 if (frame_resize_pixelwise || hwnd == tip_window)
3871 #endif
3872 return 0;
3874 #if 0
3875 /* Don't restrict the sizing of fullscreened frames, allowing them to be
3876 flush with the sides of the screen. */
3877 f = x_window_to_frame (dpyinfo, hwnd);
3878 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
3879 return 0;
3882 WINDOWPLACEMENT wp;
3883 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3885 wp.length = sizeof (WINDOWPLACEMENT);
3886 GetWindowPlacement (hwnd, &wp);
3888 if (wp.showCmd != SW_SHOWMAXIMIZED && wp.showCmd != SW_SHOWMINIMIZED
3889 && (lppos->flags & SWP_NOSIZE) == 0)
3891 RECT rect;
3892 int wdiff;
3893 int hdiff;
3894 DWORD font_width;
3895 DWORD line_height;
3896 DWORD internal_border;
3897 DWORD vscrollbar_extra;
3898 DWORD hscrollbar_extra;
3899 RECT wr;
3901 wp.length = sizeof (wp);
3902 GetWindowRect (hwnd, &wr);
3904 enter_crit ();
3906 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3907 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3908 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3909 vscrollbar_extra = GetWindowLong (hwnd, WND_VSCROLLBAR_INDEX);
3910 hscrollbar_extra = GetWindowLong (hwnd, WND_HSCROLLBAR_INDEX);
3912 leave_crit ();
3914 memset (&rect, 0, sizeof (rect));
3915 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3916 GetMenu (hwnd) != NULL);
3918 /* Force width and height of client area to be exact
3919 multiples of the character cell dimensions. */
3920 wdiff = (lppos->cx - (rect.right - rect.left)
3921 - 2 * internal_border - vscrollbar_extra)
3922 % font_width;
3923 hdiff = (lppos->cy - (rect.bottom - rect.top)
3924 - 2 * internal_border - hscrollbar_extra)
3925 % line_height;
3927 if (wdiff || hdiff)
3929 /* For right/bottom sizing we can just fix the sizes.
3930 However for top/left sizing we will need to fix the X
3931 and Y positions as well. */
3933 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3934 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3936 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3937 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3939 if (wp.showCmd != SW_SHOWMAXIMIZED
3940 && (lppos->flags & SWP_NOMOVE) == 0)
3942 if (lppos->x != wr.left || lppos->y != wr.top)
3944 lppos->x += wdiff;
3945 lppos->y += hdiff;
3947 else
3949 lppos->flags |= SWP_NOMOVE;
3953 return 0;
3958 goto dflt;
3959 #endif
3961 case WM_GETMINMAXINFO:
3962 /* Hack to allow resizing the Emacs frame above the screen size.
3963 Note that Windows 9x limits coordinates to 16-bits. */
3964 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3965 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3966 return 0;
3968 case WM_SETCURSOR:
3969 if (LOWORD (lParam) == HTCLIENT)
3971 f = x_window_to_frame (dpyinfo, hwnd);
3972 if (f && f->output_data.w32->hourglass_p
3973 && !menubar_in_use && !current_popup_menu)
3974 SetCursor (f->output_data.w32->hourglass_cursor);
3975 else if (f)
3976 SetCursor (f->output_data.w32->current_cursor);
3977 return 0;
3979 goto dflt;
3981 case WM_EMACS_SETCURSOR:
3983 Cursor cursor = (Cursor) wParam;
3984 f = x_window_to_frame (dpyinfo, hwnd);
3985 if (f && cursor)
3987 f->output_data.w32->current_cursor = cursor;
3988 if (!f->output_data.w32->hourglass_p)
3989 SetCursor (cursor);
3991 return 0;
3994 case WM_EMACS_SHOWCURSOR:
3996 ShowCursor ((BOOL) wParam);
3998 return 0;
4001 case WM_EMACS_CREATEVSCROLLBAR:
4002 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
4003 (struct scroll_bar *) lParam);
4005 case WM_EMACS_CREATEHSCROLLBAR:
4006 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
4007 (struct scroll_bar *) lParam);
4009 case WM_EMACS_SHOWWINDOW:
4010 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
4012 case WM_EMACS_BRINGTOTOP:
4013 case WM_EMACS_SETFOREGROUND:
4015 HWND foreground_window;
4016 DWORD foreground_thread, retval;
4018 /* On NT 5.0, and apparently Windows 98, it is necessary to
4019 attach to the thread that currently has focus in order to
4020 pull the focus away from it. */
4021 foreground_window = GetForegroundWindow ();
4022 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
4023 if (!foreground_window
4024 || foreground_thread == GetCurrentThreadId ()
4025 || !AttachThreadInput (GetCurrentThreadId (),
4026 foreground_thread, TRUE))
4027 foreground_thread = 0;
4029 retval = SetForegroundWindow ((HWND) wParam);
4030 if (msg == WM_EMACS_BRINGTOTOP)
4031 retval = BringWindowToTop ((HWND) wParam);
4033 /* Detach from the previous foreground thread. */
4034 if (foreground_thread)
4035 AttachThreadInput (GetCurrentThreadId (),
4036 foreground_thread, FALSE);
4038 return retval;
4041 case WM_EMACS_SETWINDOWPOS:
4043 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4044 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4045 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4048 case WM_EMACS_DESTROYWINDOW:
4049 DragAcceptFiles ((HWND) wParam, FALSE);
4050 return DestroyWindow ((HWND) wParam);
4052 case WM_EMACS_HIDE_CARET:
4053 return HideCaret (hwnd);
4055 case WM_EMACS_SHOW_CARET:
4056 return ShowCaret (hwnd);
4058 case WM_EMACS_DESTROY_CARET:
4059 w32_system_caret_hwnd = NULL;
4060 w32_visible_system_caret_hwnd = NULL;
4061 return DestroyCaret ();
4063 case WM_EMACS_TRACK_CARET:
4064 /* If there is currently no system caret, create one. */
4065 if (w32_system_caret_hwnd == NULL)
4067 /* Use the default caret width, and avoid changing it
4068 unnecessarily, as it confuses screen reader software. */
4069 w32_system_caret_hwnd = hwnd;
4070 CreateCaret (hwnd, NULL, 0,
4071 w32_system_caret_height);
4074 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4075 return 0;
4076 /* Ensure visible caret gets turned on when requested. */
4077 else if (w32_use_visible_system_caret
4078 && w32_visible_system_caret_hwnd != hwnd)
4080 w32_visible_system_caret_hwnd = hwnd;
4081 return ShowCaret (hwnd);
4083 /* Ensure visible caret gets turned off when requested. */
4084 else if (!w32_use_visible_system_caret
4085 && w32_visible_system_caret_hwnd)
4087 w32_visible_system_caret_hwnd = NULL;
4088 return HideCaret (hwnd);
4090 else
4091 return 1;
4093 case WM_EMACS_TRACKPOPUPMENU:
4095 UINT flags;
4096 POINT *pos;
4097 int retval;
4098 pos = (POINT *)lParam;
4099 flags = TPM_CENTERALIGN;
4100 if (button_state & LMOUSE)
4101 flags |= TPM_LEFTBUTTON;
4102 else if (button_state & RMOUSE)
4103 flags |= TPM_RIGHTBUTTON;
4105 /* Remember we did a SetCapture on the initial mouse down event,
4106 so for safety, we make sure the capture is canceled now. */
4107 ReleaseCapture ();
4108 button_state = 0;
4110 /* Use menubar_active to indicate that WM_INITMENU is from
4111 TrackPopupMenu below, and should be ignored. */
4112 f = x_window_to_frame (dpyinfo, hwnd);
4113 if (f)
4114 f->output_data.w32->menubar_active = 1;
4116 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4117 0, hwnd, NULL))
4119 MSG amsg;
4120 /* Eat any mouse messages during popupmenu */
4121 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4122 PM_REMOVE));
4123 /* Get the menu selection, if any */
4124 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4126 retval = LOWORD (amsg.wParam);
4128 else
4130 retval = 0;
4133 else
4135 retval = -1;
4138 return retval;
4140 case WM_EMACS_FILENOTIFY:
4141 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4142 return 1;
4144 default:
4145 /* Check for messages registered at runtime. */
4146 if (msg == msh_mousewheel)
4148 wmsg.dwModifiers = w32_get_modifiers ();
4149 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4150 signal_user_input ();
4151 return 0;
4154 dflt:
4155 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4158 /* The most common default return code for handled messages is 0. */
4159 return 0;
4162 static void
4163 my_create_window (struct frame * f)
4165 MSG msg;
4166 static int coords[2];
4167 Lisp_Object left, top;
4168 struct w32_display_info *dpyinfo = &one_w32_display_info;
4170 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
4171 anything that is not a number and is not Qunbound. */
4172 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
4173 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
4174 if (EQ (left, Qunbound))
4175 coords[0] = CW_USEDEFAULT;
4176 else
4177 coords[0] = XINT (left);
4178 if (EQ (top, Qunbound))
4179 coords[1] = CW_USEDEFAULT;
4180 else
4181 coords[1] = XINT (top);
4183 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
4184 (WPARAM)f, (LPARAM)coords))
4185 emacs_abort ();
4186 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4190 /* Create a tooltip window. Unlike my_create_window, we do not do this
4191 indirectly via the Window thread, as we do not need to process Window
4192 messages for the tooltip. Creating tooltips indirectly also creates
4193 deadlocks when tooltips are created for menu items. */
4194 static void
4195 my_create_tip_window (struct frame *f)
4197 RECT rect;
4199 rect.left = rect.top = 0;
4200 rect.right = FRAME_PIXEL_WIDTH (f);
4201 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4203 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4204 FRAME_EXTERNAL_MENU_BAR (f));
4206 tip_window = FRAME_W32_WINDOW (f)
4207 = CreateWindow (EMACS_CLASS,
4208 f->namebuf,
4209 f->output_data.w32->dwStyle,
4210 f->left_pos,
4211 f->top_pos,
4212 rect.right - rect.left,
4213 rect.bottom - rect.top,
4214 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4215 NULL,
4216 hinst,
4217 NULL);
4219 if (tip_window)
4221 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4222 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4223 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4224 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4226 /* Tip frames have no scrollbars. */
4227 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
4228 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
4230 /* Do this to discard the default setting specified by our parent. */
4231 ShowWindow (tip_window, SW_HIDE);
4236 /* Create and set up the w32 window for frame F. */
4238 static void
4239 w32_window (struct frame *f, long window_prompting, bool minibuffer_only)
4241 block_input ();
4243 /* Use the resource name as the top-level window name
4244 for looking up resources. Make a non-Lisp copy
4245 for the window manager, so GC relocation won't bother it.
4247 Elsewhere we specify the window name for the window manager. */
4248 f->namebuf = xlispstrdup (Vx_resource_name);
4250 my_create_window (f);
4252 validate_x_resource_name ();
4254 /* x_set_name normally ignores requests to set the name if the
4255 requested name is the same as the current name. This is the one
4256 place where that assumption isn't correct; f->name is set, but
4257 the server hasn't been told. */
4259 Lisp_Object name;
4260 int explicit = f->explicit_name;
4262 f->explicit_name = 0;
4263 name = f->name;
4264 fset_name (f, Qnil);
4265 x_set_name (f, name, explicit);
4268 unblock_input ();
4270 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4271 initialize_frame_menubar (f);
4273 if (FRAME_W32_WINDOW (f) == 0)
4274 error ("Unable to create window");
4277 /* Handle the icon stuff for this window. Perhaps later we might
4278 want an x_set_icon_position which can be called interactively as
4279 well. */
4281 static void
4282 x_icon (struct frame *f, Lisp_Object parms)
4284 Lisp_Object icon_x, icon_y;
4285 struct w32_display_info *dpyinfo = &one_w32_display_info;
4287 /* Set the position of the icon. Note that Windows 95 groups all
4288 icons in the tray. */
4289 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4290 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4291 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4293 CHECK_NUMBER (icon_x);
4294 CHECK_NUMBER (icon_y);
4296 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4297 error ("Both left and top icon corners of icon must be specified");
4299 block_input ();
4301 #if 0 /* TODO */
4302 /* Start up iconic or window? */
4303 x_wm_set_window_state
4304 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4305 ? IconicState
4306 : NormalState));
4308 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4309 ? f->icon_name
4310 : f->name)));
4311 #endif
4313 unblock_input ();
4317 static void
4318 x_make_gc (struct frame *f)
4320 XGCValues gc_values;
4322 block_input ();
4324 /* Create the GC's of this frame.
4325 Note that many default values are used. */
4327 /* Normal video */
4328 gc_values.font = FRAME_FONT (f);
4330 /* Cursor has cursor-color background, background-color foreground. */
4331 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4332 gc_values.background = f->output_data.w32->cursor_pixel;
4333 f->output_data.w32->cursor_gc
4334 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4335 (GCFont | GCForeground | GCBackground),
4336 &gc_values);
4338 /* Reliefs. */
4339 f->output_data.w32->white_relief.gc = 0;
4340 f->output_data.w32->black_relief.gc = 0;
4342 unblock_input ();
4346 /* Handler for signals raised during x_create_frame and
4347 x_create_tip_frame. FRAME is the frame which is partially
4348 constructed. */
4350 static Lisp_Object
4351 unwind_create_frame (Lisp_Object frame)
4353 struct frame *f = XFRAME (frame);
4355 /* If frame is ``official'', nothing to do. */
4356 if (NILP (Fmemq (frame, Vframe_list)))
4358 #ifdef GLYPH_DEBUG
4359 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4361 /* If the frame's image cache refcount is still the same as our
4362 private shadow variable, it means we are unwinding a frame
4363 for which we didn't yet call init_frame_faces, where the
4364 refcount is incremented. Therefore, we increment it here, so
4365 that free_frame_faces, called in x_free_frame_resources
4366 below, will not mistakenly decrement the counter that was not
4367 incremented yet to account for this new frame. */
4368 if (FRAME_IMAGE_CACHE (f) != NULL
4369 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
4370 FRAME_IMAGE_CACHE (f)->refcount++;
4371 #endif
4373 x_free_frame_resources (f);
4374 free_glyphs (f);
4376 #ifdef GLYPH_DEBUG
4377 /* Check that reference counts are indeed correct. */
4378 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4379 eassert ((dpyinfo->terminal->image_cache == NULL
4380 && image_cache_refcount == 0)
4381 || (dpyinfo->terminal->image_cache != NULL
4382 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
4383 #endif
4384 return Qt;
4387 return Qnil;
4390 static void
4391 do_unwind_create_frame (Lisp_Object frame)
4393 unwind_create_frame (frame);
4396 static void
4397 unwind_create_frame_1 (Lisp_Object val)
4399 inhibit_lisp_code = val;
4402 static void
4403 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4405 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4406 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4407 RES_TYPE_STRING);
4408 Lisp_Object font;
4409 if (EQ (font_param, Qunbound))
4410 font_param = Qnil;
4411 font = !NILP (font_param) ? font_param
4412 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4414 if (!STRINGP (font))
4416 int i;
4417 static char *names[]
4418 = { "Courier New-10",
4419 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4420 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4421 "Fixedsys",
4422 NULL };
4424 for (i = 0; names[i]; i++)
4426 font = font_open_by_name (f, build_unibyte_string (names[i]));
4427 if (! NILP (font))
4428 break;
4430 if (NILP (font))
4431 error ("No suitable font was found");
4433 else if (!NILP (font_param))
4435 /* Remember the explicit font parameter, so we can re-apply it after
4436 we've applied the `default' face settings. */
4437 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4439 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4442 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4443 1, 1, 0,
4444 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4445 Return an Emacs frame object.
4446 PARAMETERS is an alist of frame parameters.
4447 If the parameters specify that the frame should not have a minibuffer,
4448 and do not specify a specific minibuffer window to use,
4449 then `default-minibuffer-frame' must be a frame whose minibuffer can
4450 be shared by the new frame.
4452 This function is an internal primitive--use `make-frame' instead. */)
4453 (Lisp_Object parameters)
4455 struct frame *f;
4456 Lisp_Object frame, tem;
4457 Lisp_Object name;
4458 bool minibuffer_only = false;
4459 long window_prompting = 0;
4460 ptrdiff_t count = SPECPDL_INDEX ();
4461 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4462 Lisp_Object display;
4463 struct w32_display_info *dpyinfo = NULL;
4464 Lisp_Object parent;
4465 struct kboard *kb;
4467 if (!FRAME_W32_P (SELECTED_FRAME ())
4468 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4469 error ("Cannot create a GUI frame in a -nw session");
4471 /* Make copy of frame parameters because the original is in pure
4472 storage now. */
4473 parameters = Fcopy_alist (parameters);
4475 /* Use this general default value to start with
4476 until we know if this frame has a specified name. */
4477 Vx_resource_name = Vinvocation_name;
4479 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4480 if (EQ (display, Qunbound))
4481 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4482 if (EQ (display, Qunbound))
4483 display = Qnil;
4484 dpyinfo = check_x_display_info (display);
4485 kb = dpyinfo->terminal->kboard;
4487 if (!dpyinfo->terminal->name)
4488 error ("Terminal is not live, can't create new frames on it");
4490 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4491 if (!STRINGP (name)
4492 && ! EQ (name, Qunbound)
4493 && ! NILP (name))
4494 error ("Invalid frame name--not a string or nil");
4496 if (STRINGP (name))
4497 Vx_resource_name = name;
4499 /* See if parent window is specified. */
4500 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4501 if (EQ (parent, Qunbound))
4502 parent = Qnil;
4503 if (! NILP (parent))
4504 CHECK_NUMBER (parent);
4506 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4507 /* No need to protect DISPLAY because that's not used after passing
4508 it to make_frame_without_minibuffer. */
4509 frame = Qnil;
4510 GCPRO4 (parameters, parent, name, frame);
4511 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
4512 RES_TYPE_SYMBOL);
4513 if (EQ (tem, Qnone) || NILP (tem))
4514 f = make_frame_without_minibuffer (Qnil, kb, display);
4515 else if (EQ (tem, Qonly))
4517 f = make_minibuffer_frame ();
4518 minibuffer_only = true;
4520 else if (WINDOWP (tem))
4521 f = make_frame_without_minibuffer (tem, kb, display);
4522 else
4523 f = make_frame (true);
4525 XSETFRAME (frame, f);
4527 /* By default, make scrollbars the system standard width and height. */
4528 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4529 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
4531 f->terminal = dpyinfo->terminal;
4533 f->output_method = output_w32;
4534 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
4535 FRAME_FONTSET (f) = -1;
4537 fset_icon_name
4538 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
4539 RES_TYPE_STRING));
4540 if (! STRINGP (f->icon_name))
4541 fset_icon_name (f, Qnil);
4543 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
4545 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
4546 record_unwind_protect (do_unwind_create_frame, frame);
4548 #ifdef GLYPH_DEBUG
4549 image_cache_refcount =
4550 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
4551 dpyinfo_refcount = dpyinfo->reference_count;
4552 #endif /* GLYPH_DEBUG */
4554 /* Specify the parent under which to make this window. */
4555 if (!NILP (parent))
4557 /* Cast to UINT_PTR shuts up compiler warnings about cast to
4558 pointer from integer of different size. */
4559 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
4560 f->output_data.w32->explicit_parent = true;
4562 else
4564 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4565 f->output_data.w32->explicit_parent = false;
4568 /* Set the name; the functions to which we pass f expect the name to
4569 be set. */
4570 if (EQ (name, Qunbound) || NILP (name))
4572 fset_name (f, build_string (dpyinfo->w32_id_name));
4573 f->explicit_name = false;
4575 else
4577 fset_name (f, name);
4578 f->explicit_name = true;
4579 /* Use the frame's title when getting resources for this frame. */
4580 specbind (Qx_resource_name, name);
4583 if (uniscribe_available)
4584 register_font_driver (&uniscribe_font_driver, f);
4585 register_font_driver (&w32font_driver, f);
4587 x_default_parameter (f, parameters, Qfont_backend, Qnil,
4588 "fontBackend", "FontBackend", RES_TYPE_STRING);
4590 /* Extract the window parameters from the supplied values
4591 that are needed to determine window geometry. */
4592 x_default_font_parameter (f, parameters);
4594 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4595 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4597 /* We recognize either internalBorderWidth or internalBorder
4598 (which is what xterm calls it). */
4599 if (NILP (Fassq (Qinternal_border_width, parameters)))
4601 Lisp_Object value;
4603 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
4604 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4605 if (! EQ (value, Qunbound))
4606 parameters = Fcons (Fcons (Qinternal_border_width, value),
4607 parameters);
4609 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4610 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4611 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4612 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
4613 NULL, NULL, RES_TYPE_NUMBER);
4614 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
4615 NULL, NULL, RES_TYPE_NUMBER);
4616 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4617 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4618 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
4619 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4621 /* Also do the stuff which must be set before the window exists. */
4622 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4623 "foreground", "Foreground", RES_TYPE_STRING);
4624 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4625 "background", "Background", RES_TYPE_STRING);
4626 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4627 "pointerColor", "Foreground", RES_TYPE_STRING);
4628 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4629 "borderColor", "BorderColor", RES_TYPE_STRING);
4630 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4631 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4632 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4633 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4634 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4635 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4636 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4637 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4638 /* Process alpha here (Bug#16619). */
4639 x_default_parameter (f, parameters, Qalpha, Qnil,
4640 "alpha", "Alpha", RES_TYPE_NUMBER);
4642 /* Init faces first since we need the frame's column width/line
4643 height in various occasions. */
4644 init_frame_faces (f);
4646 /* The following call of change_frame_size is needed since otherwise
4647 x_set_tool_bar_lines will already work with the character sizes
4648 installed by init_frame_faces while the frame's pixel size is
4649 still calculated from a character size of 1 and we subsequently
4650 hit the (height >= 0) assertion in window_box_height.
4652 The non-pixelwise code apparently worked around this because it
4653 had one frame line vs one toolbar line which left us with a zero
4654 root window height which was obviously wrong as well ... */
4655 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
4656 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, true,
4657 Qx_create_frame_1);
4659 /* The X resources controlling the menu-bar and tool-bar are
4660 processed specially at startup, and reflected in the mode
4661 variables; ignore them here. */
4662 x_default_parameter (f, parameters, Qmenu_bar_lines,
4663 NILP (Vmenu_bar_mode)
4664 ? make_number (0) : make_number (1),
4665 NULL, NULL, RES_TYPE_NUMBER);
4666 x_default_parameter (f, parameters, Qtool_bar_lines,
4667 NILP (Vtool_bar_mode)
4668 ? make_number (0) : make_number (1),
4669 NULL, NULL, RES_TYPE_NUMBER);
4671 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4672 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4673 x_default_parameter (f, parameters, Qtitle, Qnil,
4674 "title", "Title", RES_TYPE_STRING);
4676 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4677 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4679 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4680 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4681 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4682 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4683 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4684 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4685 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
4687 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
4689 window_prompting = x_figure_window_size (f, parameters, true);
4691 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4692 f->no_split = minibuffer_only || EQ (tem, Qt);
4694 w32_window (f, window_prompting, minibuffer_only);
4695 x_icon (f, parameters);
4697 x_make_gc (f);
4699 /* Now consider the frame official. */
4700 f->terminal->reference_count++;
4701 FRAME_DISPLAY_INFO (f)->reference_count++;
4702 Vframe_list = Fcons (frame, Vframe_list);
4704 /* We need to do this after creating the window, so that the
4705 icon-creation functions can say whose icon they're describing. */
4706 x_default_parameter (f, parameters, Qicon_type, Qnil,
4707 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4709 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4710 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4711 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4712 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4713 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4714 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4715 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4716 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4717 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
4718 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
4720 /* Allow x_set_window_size, now. */
4721 f->can_x_set_window_size = true;
4723 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, true,
4724 Qx_create_frame_2);
4726 /* Tell the server what size and position, etc, we want, and how
4727 badly we want them. This should be done after we have the menu
4728 bar so that its size can be taken into account. */
4729 block_input ();
4730 x_wm_set_size_hint (f, window_prompting, false);
4731 unblock_input ();
4733 /* Process fullscreen parameter here in the hope that normalizing a
4734 fullheight/fullwidth frame will produce the size set by the last
4735 adjust_frame_size call. */
4736 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4737 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4739 /* Make the window appear on the frame and enable display, unless
4740 the caller says not to. However, with explicit parent, Emacs
4741 cannot control visibility, so don't try. */
4742 if (! f->output_data.w32->explicit_parent)
4744 Lisp_Object visibility;
4746 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4747 if (EQ (visibility, Qunbound))
4748 visibility = Qt;
4750 if (EQ (visibility, Qicon))
4751 x_iconify_frame (f);
4752 else if (! NILP (visibility))
4753 x_make_frame_visible (f);
4754 else
4755 /* Must have been Qnil. */
4759 /* Initialize `default-minibuffer-frame' in case this is the first
4760 frame on this terminal. */
4761 if (FRAME_HAS_MINIBUF_P (f)
4762 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
4763 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
4764 kset_default_minibuffer_frame (kb, frame);
4766 /* All remaining specified parameters, which have not been "used"
4767 by x_get_arg and friends, now go in the misc. alist of the frame. */
4768 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4769 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4770 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
4772 UNGCPRO;
4774 /* Make sure windows on this frame appear in calls to next-window
4775 and similar functions. */
4776 Vwindow_list = Qnil;
4778 return unbind_to (count, frame);
4781 /* FRAME is used only to get a handle on the X display. We don't pass the
4782 display info directly because we're called from frame.c, which doesn't
4783 know about that structure. */
4784 Lisp_Object
4785 x_get_focus_frame (struct frame *frame)
4787 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
4788 Lisp_Object xfocus;
4789 if (! dpyinfo->w32_focus_frame)
4790 return Qnil;
4792 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4793 return xfocus;
4796 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4797 doc: /* Internal function called by `color-defined-p', which see.
4798 \(Note that the Nextstep version of this function ignores FRAME.) */)
4799 (Lisp_Object color, Lisp_Object frame)
4801 XColor foo;
4802 struct frame *f = decode_window_system_frame (frame);
4804 CHECK_STRING (color);
4806 if (w32_defined_color (f, SDATA (color), &foo, false))
4807 return Qt;
4808 else
4809 return Qnil;
4812 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
4813 doc: /* Internal function called by `color-values', which see. */)
4814 (Lisp_Object color, Lisp_Object frame)
4816 XColor foo;
4817 struct frame *f = decode_window_system_frame (frame);
4819 CHECK_STRING (color);
4821 if (w32_defined_color (f, SDATA (color), &foo, false))
4822 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4823 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4824 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
4825 else
4826 return Qnil;
4829 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
4830 doc: /* Internal function called by `display-color-p', which see. */)
4831 (Lisp_Object display)
4833 struct w32_display_info *dpyinfo = check_x_display_info (display);
4835 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4836 return Qnil;
4838 return Qt;
4841 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4842 Sx_display_grayscale_p, 0, 1, 0,
4843 doc: /* Return t if DISPLAY supports shades of gray.
4844 Note that color displays do support shades of gray.
4845 The optional argument DISPLAY specifies which display to ask about.
4846 DISPLAY should be either a frame or a display name (a string).
4847 If omitted or nil, that stands for the selected frame's display. */)
4848 (Lisp_Object display)
4850 struct w32_display_info *dpyinfo = check_x_display_info (display);
4852 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4853 return Qnil;
4855 return Qt;
4858 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4859 Sx_display_pixel_width, 0, 1, 0,
4860 doc: /* Return the width in pixels of DISPLAY.
4861 The optional argument DISPLAY specifies which display to ask about.
4862 DISPLAY should be either a frame or a display name (a string).
4863 If omitted or nil, that stands for the selected frame's display.
4865 On \"multi-monitor\" setups this refers to the pixel width for all
4866 physical monitors associated with DISPLAY. To get information for
4867 each physical monitor, use `display-monitor-attributes-list'. */)
4868 (Lisp_Object display)
4870 struct w32_display_info *dpyinfo = check_x_display_info (display);
4872 return make_number (x_display_pixel_width (dpyinfo));
4875 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
4876 Sx_display_pixel_height, 0, 1, 0,
4877 doc: /* Return the height in pixels of DISPLAY.
4878 The optional argument DISPLAY specifies which display to ask about.
4879 DISPLAY should be either a frame or a display name (a string).
4880 If omitted or nil, that stands for the selected frame's display.
4882 On \"multi-monitor\" setups this refers to the pixel height for all
4883 physical monitors associated with DISPLAY. To get information for
4884 each physical monitor, use `display-monitor-attributes-list'. */)
4885 (Lisp_Object display)
4887 struct w32_display_info *dpyinfo = check_x_display_info (display);
4889 return make_number (x_display_pixel_height (dpyinfo));
4892 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
4893 0, 1, 0,
4894 doc: /* Return the number of bitplanes of DISPLAY.
4895 The optional argument DISPLAY specifies which display to ask about.
4896 DISPLAY should be either a frame or a display name (a string).
4897 If omitted or nil, that stands for the selected frame's display. */)
4898 (Lisp_Object display)
4900 struct w32_display_info *dpyinfo = check_x_display_info (display);
4902 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4905 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
4906 0, 1, 0,
4907 doc: /* Return the number of color cells of DISPLAY.
4908 The optional argument DISPLAY specifies which display to ask about.
4909 DISPLAY should be either a frame or a display name (a string).
4910 If omitted or nil, that stands for the selected frame's display. */)
4911 (Lisp_Object display)
4913 struct w32_display_info *dpyinfo = check_x_display_info (display);
4914 int cap;
4916 /* Don't use NCOLORS: it returns incorrect results under remote
4917 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4918 * overflow and because probably is more meaningful on Windows
4919 * anyway. */
4921 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
4922 return make_number (cap);
4925 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4926 Sx_server_max_request_size,
4927 0, 1, 0,
4928 doc: /* Return the maximum request size of the server of DISPLAY.
4929 The optional argument DISPLAY specifies which display to ask about.
4930 DISPLAY should be either a frame or a display name (a string).
4931 If omitted or nil, that stands for the selected frame's display. */)
4932 (Lisp_Object display)
4934 return make_number (1);
4937 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
4938 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
4940 \(Labeling every distributor as a "vendor" embodies the false assumption
4941 that operating systems cannot be developed and distributed noncommercially.)
4943 For GNU and Unix systems, this queries the X server software; for
4944 MS-Windows, this queries the OS.
4946 The optional argument TERMINAL specifies which display to ask about.
4947 TERMINAL should be a terminal object, a frame or a display name (a string).
4948 If omitted or nil, that stands for the selected frame's display. */)
4949 (Lisp_Object terminal)
4951 return build_string ("Microsoft Corp.");
4954 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
4955 doc: /* Return the version numbers of the GUI software on TERMINAL.
4956 The value is a list of three integers specifying the version of the GUI
4957 software in use.
4959 For GNU and Unix system, the first 2 numbers are the version of the X
4960 Protocol used on TERMINAL and the 3rd number is the distributor-specific
4961 release number. For MS-Windows, the 3 numbers report the version and
4962 the build number of the OS.
4964 See also the function `x-server-vendor'.
4966 The optional argument TERMINAL specifies which display to ask about.
4967 TERMINAL should be a terminal object, a frame or a display name (a string).
4968 If omitted or nil, that stands for the selected frame's display. */)
4969 (Lisp_Object terminal)
4971 return list3i (w32_major_version, w32_minor_version, w32_build_number);
4974 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
4975 doc: /* Return the number of screens on the server of DISPLAY.
4976 The optional argument DISPLAY specifies which display to ask about.
4977 DISPLAY should be either a frame or a display name (a string).
4978 If omitted or nil, that stands for the selected frame's display. */)
4979 (Lisp_Object display)
4981 return make_number (1);
4984 DEFUN ("x-display-mm-height", Fx_display_mm_height,
4985 Sx_display_mm_height, 0, 1, 0,
4986 doc: /* Return the height in millimeters of DISPLAY.
4987 The optional argument DISPLAY specifies which display to ask about.
4988 DISPLAY should be either a frame or a display name (a string).
4989 If omitted or nil, that stands for the selected frame's display.
4991 On \"multi-monitor\" setups this refers to the height in millimeters for
4992 all physical monitors associated with DISPLAY. To get information
4993 for each physical monitor, use `display-monitor-attributes-list'. */)
4994 (Lisp_Object display)
4996 struct w32_display_info *dpyinfo = check_x_display_info (display);
4997 HDC hdc;
4998 double mm_per_pixel;
5000 hdc = GetDC (NULL);
5001 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5002 / GetDeviceCaps (hdc, VERTRES));
5003 ReleaseDC (NULL, hdc);
5005 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
5008 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
5009 doc: /* Return the width in millimeters of DISPLAY.
5010 The optional argument DISPLAY specifies which display to ask about.
5011 DISPLAY should be either a frame or a display name (a string).
5012 If omitted or nil, that stands for the selected frame's display.
5014 On \"multi-monitor\" setups this refers to the width in millimeters for
5015 all physical monitors associated with TERMINAL. To get information
5016 for each physical monitor, use `display-monitor-attributes-list'. */)
5017 (Lisp_Object display)
5019 struct w32_display_info *dpyinfo = check_x_display_info (display);
5020 HDC hdc;
5021 double mm_per_pixel;
5023 hdc = GetDC (NULL);
5024 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5025 / GetDeviceCaps (hdc, HORZRES));
5026 ReleaseDC (NULL, hdc);
5028 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
5031 DEFUN ("x-display-backing-store", Fx_display_backing_store,
5032 Sx_display_backing_store, 0, 1, 0,
5033 doc: /* Return an indication of whether DISPLAY does backing store.
5034 The value may be `always', `when-mapped', or `not-useful'.
5035 The optional argument DISPLAY specifies which display to ask about.
5036 DISPLAY should be either a frame or a display name (a string).
5037 If omitted or nil, that stands for the selected frame's display. */)
5038 (Lisp_Object display)
5040 return intern ("not-useful");
5043 DEFUN ("x-display-visual-class", Fx_display_visual_class,
5044 Sx_display_visual_class, 0, 1, 0,
5045 doc: /* Return the visual class of DISPLAY.
5046 The value is one of the symbols `static-gray', `gray-scale',
5047 `static-color', `pseudo-color', `true-color', or `direct-color'.
5049 The optional argument DISPLAY specifies which display to ask about.
5050 DISPLAY should be either a frame or a display name (a string).
5051 If omitted or nil, that stands for the selected frame's display. */)
5052 (Lisp_Object display)
5054 struct w32_display_info *dpyinfo = check_x_display_info (display);
5055 Lisp_Object result = Qnil;
5057 if (dpyinfo->has_palette)
5058 result = intern ("pseudo-color");
5059 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5060 result = intern ("static-grey");
5061 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5062 result = intern ("static-color");
5063 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5064 result = intern ("true-color");
5066 return result;
5069 DEFUN ("x-display-save-under", Fx_display_save_under,
5070 Sx_display_save_under, 0, 1, 0,
5071 doc: /* Return t if DISPLAY supports the save-under feature.
5072 The optional argument DISPLAY specifies which display to ask about.
5073 DISPLAY should be either a frame or a display name (a string).
5074 If omitted or nil, that stands for the selected frame's display. */)
5075 (Lisp_Object display)
5077 return Qnil;
5080 static BOOL CALLBACK ALIGN_STACK
5081 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5083 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5085 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5087 return TRUE;
5090 static Lisp_Object
5091 w32_display_monitor_attributes_list (void)
5093 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5094 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5095 int i, n_monitors;
5096 HMONITOR *monitors;
5097 struct gcpro gcpro1, gcpro2, gcpro3;
5099 if (!(enum_display_monitors_fn && get_monitor_info_fn
5100 && monitor_from_window_fn))
5101 return Qnil;
5103 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5104 (LPARAM) &monitor_list)
5105 || NILP (monitor_list))
5106 return Qnil;
5108 n_monitors = 0;
5109 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5110 n_monitors++;
5112 monitors = xmalloc (n_monitors * sizeof (*monitors));
5113 for (i = 0; i < n_monitors; i++)
5115 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5116 monitor_list = XCDR (monitor_list);
5119 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5120 FOR_EACH_FRAME (rest, frame)
5122 struct frame *f = XFRAME (frame);
5124 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5126 HMONITOR monitor =
5127 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5128 MONITOR_DEFAULT_TO_NEAREST);
5130 for (i = 0; i < n_monitors; i++)
5131 if (monitors[i] == monitor)
5132 break;
5134 if (i < n_monitors)
5135 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5139 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5141 for (i = 0; i < n_monitors; i++)
5143 Lisp_Object geometry, workarea, name, attributes = Qnil;
5144 HDC hdc;
5145 int width_mm, height_mm;
5146 struct MONITOR_INFO_EX mi;
5148 mi.cbSize = sizeof (mi);
5149 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5150 continue;
5152 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5153 if (hdc == NULL)
5154 continue;
5155 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5156 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5157 DeleteDC (hdc);
5159 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5160 attributes);
5162 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5164 attributes = Fcons (Fcons (Qname, name), attributes);
5166 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5167 attributes);
5169 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5170 mi.rcWork.right - mi.rcWork.left,
5171 mi.rcWork.bottom - mi.rcWork.top);
5172 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5174 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5175 mi.rcMonitor.right - mi.rcMonitor.left,
5176 mi.rcMonitor.bottom - mi.rcMonitor.top);
5177 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5179 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5180 primary_monitor_attributes = attributes;
5181 else
5182 attributes_list = Fcons (attributes, attributes_list);
5185 if (!NILP (primary_monitor_attributes))
5186 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5188 UNGCPRO;
5190 xfree (monitors);
5192 return attributes_list;
5195 static Lisp_Object
5196 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5198 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5199 HDC hdc;
5200 double mm_per_pixel;
5201 int pixel_width, pixel_height, width_mm, height_mm;
5202 RECT workarea_rect;
5204 /* Fallback: treat (possibly) multiple physical monitors as if they
5205 formed a single monitor as a whole. This should provide a
5206 consistent result at least on single monitor environments. */
5207 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5208 attributes);
5210 frames = Qnil;
5211 FOR_EACH_FRAME (rest, frame)
5213 struct frame *f = XFRAME (frame);
5215 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5216 frames = Fcons (frame, frames);
5218 attributes = Fcons (Fcons (Qframes, frames), attributes);
5220 pixel_width = x_display_pixel_width (dpyinfo);
5221 pixel_height = x_display_pixel_height (dpyinfo);
5223 hdc = GetDC (NULL);
5224 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5225 / GetDeviceCaps (hdc, HORZRES));
5226 width_mm = pixel_width * mm_per_pixel + 0.5;
5227 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5228 / GetDeviceCaps (hdc, VERTRES));
5229 height_mm = pixel_height * mm_per_pixel + 0.5;
5230 ReleaseDC (NULL, hdc);
5231 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5232 attributes);
5234 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5235 we don't care. */
5236 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5237 GetSystemMetrics (SM_YVIRTUALSCREEN),
5238 pixel_width, pixel_height);
5239 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5240 workarea = list4i (workarea_rect.left, workarea_rect.top,
5241 workarea_rect.right - workarea_rect.left,
5242 workarea_rect.bottom - workarea_rect.top);
5243 else
5244 workarea = geometry;
5245 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5247 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5249 return list1 (attributes);
5252 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5253 Sw32_display_monitor_attributes_list,
5254 0, 1, 0,
5255 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5257 The optional argument DISPLAY specifies which display to ask about.
5258 DISPLAY should be either a frame or a display name (a string).
5259 If omitted or nil, that stands for the selected frame's display.
5261 Internal use only, use `display-monitor-attributes-list' instead. */)
5262 (Lisp_Object display)
5264 struct w32_display_info *dpyinfo = check_x_display_info (display);
5265 Lisp_Object attributes_list;
5267 block_input ();
5268 attributes_list = w32_display_monitor_attributes_list ();
5269 if (NILP (attributes_list))
5270 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5271 unblock_input ();
5273 return attributes_list;
5276 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5277 doc: /* Set the sound generated when the bell is rung.
5278 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5279 to use the corresponding system sound for the bell. The 'silent sound
5280 prevents Emacs from making any sound at all.
5281 SOUND is nil to use the normal beep. */)
5282 (Lisp_Object sound)
5284 CHECK_SYMBOL (sound);
5286 if (NILP (sound))
5287 sound_type = 0xFFFFFFFF;
5288 else if (EQ (sound, intern ("asterisk")))
5289 sound_type = MB_ICONASTERISK;
5290 else if (EQ (sound, intern ("exclamation")))
5291 sound_type = MB_ICONEXCLAMATION;
5292 else if (EQ (sound, intern ("hand")))
5293 sound_type = MB_ICONHAND;
5294 else if (EQ (sound, intern ("question")))
5295 sound_type = MB_ICONQUESTION;
5296 else if (EQ (sound, intern ("ok")))
5297 sound_type = MB_OK;
5298 else if (EQ (sound, intern ("silent")))
5299 sound_type = MB_EMACS_SILENT;
5300 else
5301 sound_type = 0xFFFFFFFF;
5303 return sound;
5307 x_screen_planes (register struct frame *f)
5309 return FRAME_DISPLAY_INFO (f)->n_planes;
5312 /* Return the display structure for the display named NAME.
5313 Open a new connection if necessary. */
5315 struct w32_display_info *
5316 x_display_info_for_name (Lisp_Object name)
5318 struct w32_display_info *dpyinfo;
5320 CHECK_STRING (name);
5322 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5323 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5324 return dpyinfo;
5326 /* Use this general default value to start with. */
5327 Vx_resource_name = Vinvocation_name;
5329 validate_x_resource_name ();
5331 dpyinfo = w32_term_init (name, (unsigned char *)0,
5332 SSDATA (Vx_resource_name));
5334 if (dpyinfo == 0)
5335 error ("Cannot connect to server %s", SDATA (name));
5337 XSETFASTINT (Vwindow_system_version, w32_major_version);
5339 return dpyinfo;
5342 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5343 1, 3, 0, doc: /* Open a connection to a display server.
5344 DISPLAY is the name of the display to connect to.
5345 Optional second arg XRM-STRING is a string of resources in xrdb format.
5346 If the optional third arg MUST-SUCCEED is non-nil,
5347 terminate Emacs if we can't open the connection.
5348 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5349 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5351 unsigned char *xrm_option;
5352 struct w32_display_info *dpyinfo;
5354 CHECK_STRING (display);
5356 /* Signal an error in order to encourage correct use from callers.
5357 * If we ever support multiple window systems in the same Emacs,
5358 * we'll need callers to be precise about what window system they
5359 * want. */
5361 if (strcmp (SSDATA (display), "w32") != 0)
5362 error ("The name of the display in this Emacs must be \"w32\"");
5364 /* If initialization has already been done, return now to avoid
5365 overwriting critical parts of one_w32_display_info. */
5366 if (window_system_available (NULL))
5367 return Qnil;
5369 if (! NILP (xrm_string))
5370 CHECK_STRING (xrm_string);
5372 /* Allow color mapping to be defined externally; first look in user's
5373 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5375 Lisp_Object color_file;
5376 struct gcpro gcpro1;
5378 color_file = build_string ("~/rgb.txt");
5380 GCPRO1 (color_file);
5382 if (NILP (Ffile_readable_p (color_file)))
5383 color_file =
5384 Fexpand_file_name (build_string ("rgb.txt"),
5385 Fsymbol_value (intern ("data-directory")));
5387 Vw32_color_map = Fx_load_color_file (color_file);
5389 UNGCPRO;
5391 if (NILP (Vw32_color_map))
5392 Vw32_color_map = w32_default_color_map ();
5394 /* Merge in system logical colors. */
5395 add_system_logical_colors_to_map (&Vw32_color_map);
5397 if (! NILP (xrm_string))
5398 xrm_option = SDATA (xrm_string);
5399 else
5400 xrm_option = (unsigned char *) 0;
5402 /* Use this general default value to start with. */
5403 /* First remove .exe suffix from invocation-name - it looks ugly. */
5405 char basename[ MAX_PATH ], *str;
5407 lispstpcpy (basename, Vinvocation_name);
5408 str = strrchr (basename, '.');
5409 if (str) *str = 0;
5410 Vinvocation_name = build_string (basename);
5412 Vx_resource_name = Vinvocation_name;
5414 validate_x_resource_name ();
5416 /* This is what opens the connection and sets x_current_display.
5417 This also initializes many symbols, such as those used for input. */
5418 dpyinfo = w32_term_init (display, xrm_option,
5419 SSDATA (Vx_resource_name));
5421 if (dpyinfo == 0)
5423 if (!NILP (must_succeed))
5424 fatal ("Cannot connect to server %s.\n",
5425 SDATA (display));
5426 else
5427 error ("Cannot connect to server %s", SDATA (display));
5430 XSETFASTINT (Vwindow_system_version, w32_major_version);
5431 return Qnil;
5434 DEFUN ("x-close-connection", Fx_close_connection,
5435 Sx_close_connection, 1, 1, 0,
5436 doc: /* Close the connection to DISPLAY's server.
5437 For DISPLAY, specify either a frame or a display name (a string).
5438 If DISPLAY is nil, that stands for the selected frame's display. */)
5439 (Lisp_Object display)
5441 struct w32_display_info *dpyinfo = check_x_display_info (display);
5443 if (dpyinfo->reference_count > 0)
5444 error ("Display still has frames on it");
5446 block_input ();
5447 x_destroy_all_bitmaps (dpyinfo);
5449 x_delete_display (dpyinfo);
5450 unblock_input ();
5452 return Qnil;
5455 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5456 doc: /* Return the list of display names that Emacs has connections to. */)
5457 (void)
5459 Lisp_Object result = Qnil;
5460 struct w32_display_info *wdi;
5462 for (wdi = x_display_list; wdi; wdi = wdi->next)
5463 result = Fcons (XCAR (wdi->name_list_element), result);
5465 return result;
5468 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5469 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5470 This function only has an effect on X Windows. With MS Windows, it is
5471 defined but does nothing.
5473 If ON is nil, allow buffering of requests.
5474 Turning on synchronization prohibits the Xlib routines from buffering
5475 requests and seriously degrades performance, but makes debugging much
5476 easier.
5477 The optional second argument TERMINAL specifies which display to act on.
5478 TERMINAL should be a terminal object, a frame or a display name (a string).
5479 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5480 (Lisp_Object on, Lisp_Object display)
5482 return Qnil;
5487 /***********************************************************************
5488 Window properties
5489 ***********************************************************************/
5491 #if 0 /* TODO : port window properties to W32 */
5493 DEFUN ("x-change-window-property", Fx_change_window_property,
5494 Sx_change_window_property, 2, 6, 0,
5495 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5496 PROP must be a string. VALUE may be a string or a list of conses,
5497 numbers and/or strings. If an element in the list is a string, it is
5498 converted to an atom and the value of the Atom is used. If an element
5499 is a cons, it is converted to a 32 bit number where the car is the 16
5500 top bits and the cdr is the lower 16 bits.
5502 FRAME nil or omitted means use the selected frame.
5503 If TYPE is given and non-nil, it is the name of the type of VALUE.
5504 If TYPE is not given or nil, the type is STRING.
5505 FORMAT gives the size in bits of each element if VALUE is a list.
5506 It must be one of 8, 16 or 32.
5507 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
5508 If OUTER-P is non-nil, the property is changed for the outer X window of
5509 FRAME. Default is to change on the edit X window. */)
5510 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5511 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
5513 struct frame *f = decode_window_system_frame (frame);
5514 Atom prop_atom;
5516 CHECK_STRING (prop);
5517 CHECK_STRING (value);
5519 block_input ();
5520 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5521 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5522 prop_atom, XA_STRING, 8, PropModeReplace,
5523 SDATA (value), SCHARS (value));
5525 /* Make sure the property is set when we return. */
5526 XFlush (FRAME_W32_DISPLAY (f));
5527 unblock_input ();
5529 return value;
5533 DEFUN ("x-delete-window-property", Fx_delete_window_property,
5534 Sx_delete_window_property, 1, 2, 0,
5535 doc: /* Remove window property PROP from X window of FRAME.
5536 FRAME nil or omitted means use the selected frame. Value is PROP. */)
5537 (Lisp_Object prop, Lisp_Object frame)
5539 struct frame *f = decode_window_system_frame (frame);
5540 Atom prop_atom;
5542 CHECK_STRING (prop);
5543 block_input ();
5544 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5545 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
5547 /* Make sure the property is removed when we return. */
5548 XFlush (FRAME_W32_DISPLAY (f));
5549 unblock_input ();
5551 return prop;
5555 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
5556 1, 6, 0,
5557 doc: /* Value is the value of window property PROP on FRAME.
5558 If FRAME is nil or omitted, use the selected frame.
5560 On X Windows, the following optional arguments are also accepted:
5561 If TYPE is nil or omitted, get the property as a string.
5562 Otherwise TYPE is the name of the atom that denotes the type expected.
5563 If SOURCE is non-nil, get the property on that window instead of from
5564 FRAME. The number 0 denotes the root window.
5565 If DELETE-P is non-nil, delete the property after retrieving it.
5566 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5568 On MS Windows, this function accepts but ignores those optional arguments.
5570 Value is nil if FRAME hasn't a property with name PROP or if PROP has
5571 no value of TYPE (always string in the MS Windows case). */)
5572 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5573 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
5575 struct frame *f = decode_window_system_frame (frame);
5576 Atom prop_atom;
5577 int rc;
5578 Lisp_Object prop_value = Qnil;
5579 char *tmp_data = NULL;
5580 Atom actual_type;
5581 int actual_format;
5582 unsigned long actual_size, bytes_remaining;
5584 CHECK_STRING (prop);
5585 block_input ();
5586 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5587 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5588 prop_atom, 0, 0, False, XA_STRING,
5589 &actual_type, &actual_format, &actual_size,
5590 &bytes_remaining, (unsigned char **) &tmp_data);
5591 if (rc == Success)
5593 int size = bytes_remaining;
5595 XFree (tmp_data);
5596 tmp_data = NULL;
5598 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5599 prop_atom, 0, bytes_remaining,
5600 False, XA_STRING,
5601 &actual_type, &actual_format,
5602 &actual_size, &bytes_remaining,
5603 (unsigned char **) &tmp_data);
5604 if (rc == Success)
5605 prop_value = make_string (tmp_data, size);
5607 XFree (tmp_data);
5610 unblock_input ();
5612 return prop_value;
5614 return Qnil;
5617 #endif /* TODO */
5619 /***********************************************************************
5620 Tool tips
5621 ***********************************************************************/
5623 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5624 Lisp_Object, Lisp_Object);
5625 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5626 Lisp_Object, int, int, int *, int *);
5628 /* The frame of a currently visible tooltip. */
5630 Lisp_Object tip_frame;
5632 /* If non-nil, a timer started that hides the last tooltip when it
5633 fires. */
5635 Lisp_Object tip_timer;
5636 Window tip_window;
5638 /* If non-nil, a vector of 3 elements containing the last args
5639 with which x-show-tip was called. See there. */
5641 Lisp_Object last_show_tip_args;
5644 static void
5645 unwind_create_tip_frame (Lisp_Object frame)
5647 Lisp_Object deleted;
5649 deleted = unwind_create_frame (frame);
5650 if (EQ (deleted, Qt))
5652 tip_window = NULL;
5653 tip_frame = Qnil;
5658 /* Create a frame for a tooltip on the display described by DPYINFO.
5659 PARMS is a list of frame parameters. TEXT is the string to
5660 display in the tip frame. Value is the frame.
5662 Note that functions called here, esp. x_default_parameter can
5663 signal errors, for instance when a specified color name is
5664 undefined. We have to make sure that we're in a consistent state
5665 when this happens. */
5667 static Lisp_Object
5668 x_create_tip_frame (struct w32_display_info *dpyinfo,
5669 Lisp_Object parms, Lisp_Object text)
5671 struct frame *f;
5672 Lisp_Object frame;
5673 Lisp_Object name;
5674 long window_prompting = 0;
5675 int width, height;
5676 ptrdiff_t count = SPECPDL_INDEX ();
5677 struct gcpro gcpro1, gcpro2, gcpro3;
5678 struct kboard *kb;
5679 bool face_change_before = face_change;
5680 Lisp_Object buffer;
5681 struct buffer *old_buffer;
5683 /* Use this general default value to start with until we know if
5684 this frame has a specified name. */
5685 Vx_resource_name = Vinvocation_name;
5687 kb = dpyinfo->terminal->kboard;
5689 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5690 avoid destructive changes behind our caller's back. */
5691 parms = Fcopy_alist (parms);
5693 /* Get the name of the frame to use for resource lookup. */
5694 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
5695 if (!STRINGP (name)
5696 && !EQ (name, Qunbound)
5697 && !NILP (name))
5698 error ("Invalid frame name--not a string or nil");
5699 Vx_resource_name = name;
5701 frame = Qnil;
5702 GCPRO3 (parms, name, frame);
5703 /* Make a frame without minibuffer nor mode-line. */
5704 f = make_frame (false);
5705 f->wants_modeline = 0;
5706 XSETFRAME (frame, f);
5708 AUTO_STRING (tip, " *tip*");
5709 buffer = Fget_buffer_create (tip);
5710 /* Use set_window_buffer instead of Fset_window_buffer (see
5711 discussion of bug#11984, bug#12025, bug#12026). */
5712 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, false, false);
5713 old_buffer = current_buffer;
5714 set_buffer_internal_1 (XBUFFER (buffer));
5715 bset_truncate_lines (current_buffer, Qnil);
5716 specbind (Qinhibit_read_only, Qt);
5717 specbind (Qinhibit_modification_hooks, Qt);
5718 Ferase_buffer ();
5719 Finsert (1, &text);
5720 set_buffer_internal_1 (old_buffer);
5722 record_unwind_protect (unwind_create_tip_frame, frame);
5724 /* By setting the output method, we're essentially saying that
5725 the frame is live, as per FRAME_LIVE_P. If we get a signal
5726 from this point on, x_destroy_window might screw up reference
5727 counts etc. */
5728 f->terminal = dpyinfo->terminal;
5729 f->output_method = output_w32;
5730 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5732 FRAME_FONTSET (f) = -1;
5733 fset_icon_name (f, Qnil);
5735 #ifdef GLYPH_DEBUG
5736 image_cache_refcount =
5737 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5738 dpyinfo_refcount = dpyinfo->reference_count;
5739 #endif /* GLYPH_DEBUG */
5740 FRAME_KBOARD (f) = kb;
5741 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5742 f->output_data.w32->explicit_parent = false;
5744 /* Set the name; the functions to which we pass f expect the name to
5745 be set. */
5746 if (EQ (name, Qunbound) || NILP (name))
5748 fset_name (f, build_string (dpyinfo->w32_id_name));
5749 f->explicit_name = false;
5751 else
5753 fset_name (f, name);
5754 f->explicit_name = true;
5755 /* use the frame's title when getting resources for this frame. */
5756 specbind (Qx_resource_name, name);
5759 if (uniscribe_available)
5760 register_font_driver (&uniscribe_font_driver, f);
5761 register_font_driver (&w32font_driver, f);
5763 x_default_parameter (f, parms, Qfont_backend, Qnil,
5764 "fontBackend", "FontBackend", RES_TYPE_STRING);
5766 /* Extract the window parameters from the supplied values
5767 that are needed to determine window geometry. */
5768 x_default_font_parameter (f, parms);
5770 x_default_parameter (f, parms, Qborder_width, make_number (2),
5771 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5772 /* This defaults to 2 in order to match xterm. We recognize either
5773 internalBorderWidth or internalBorder (which is what xterm calls
5774 it). */
5775 if (NILP (Fassq (Qinternal_border_width, parms)))
5777 Lisp_Object value;
5779 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
5780 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5781 if (! EQ (value, Qunbound))
5782 parms = Fcons (Fcons (Qinternal_border_width, value),
5783 parms);
5785 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
5786 "internalBorderWidth", "internalBorderWidth",
5787 RES_TYPE_NUMBER);
5788 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5789 NULL, NULL, RES_TYPE_NUMBER);
5790 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5791 NULL, NULL, RES_TYPE_NUMBER);
5793 /* Also do the stuff which must be set before the window exists. */
5794 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5795 "foreground", "Foreground", RES_TYPE_STRING);
5796 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5797 "background", "Background", RES_TYPE_STRING);
5798 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5799 "pointerColor", "Foreground", RES_TYPE_STRING);
5800 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5801 "cursorColor", "Foreground", RES_TYPE_STRING);
5802 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5803 "borderColor", "BorderColor", RES_TYPE_STRING);
5804 x_default_parameter (f, parms, Qalpha, Qnil,
5805 "alpha", "Alpha", RES_TYPE_NUMBER);
5807 /* Init faces before x_default_parameter is called for the
5808 scroll-bar-width parameter because otherwise we end up in
5809 init_iterator with a null face cache, which should not happen. */
5810 init_frame_faces (f);
5812 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
5813 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5815 window_prompting = x_figure_window_size (f, parms, false);
5817 /* No fringes on tip frame. */
5818 f->fringe_cols = 0;
5819 f->left_fringe_width = 0;
5820 f->right_fringe_width = 0;
5822 block_input ();
5823 my_create_tip_window (f);
5824 unblock_input ();
5826 x_make_gc (f);
5828 x_default_parameter (f, parms, Qauto_raise, Qnil,
5829 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5830 x_default_parameter (f, parms, Qauto_lower, Qnil,
5831 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5832 x_default_parameter (f, parms, Qcursor_type, Qbox,
5833 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5835 /* Dimensions, especially FRAME_LINES (f), must be done via
5836 change_frame_size. Change will not be effected unless different
5837 from the current FRAME_LINES (f). */
5838 width = FRAME_COLS (f);
5839 height = FRAME_LINES (f);
5840 SET_FRAME_COLS (f, 0);
5841 SET_FRAME_LINES (f, 0);
5842 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
5843 height * FRAME_LINE_HEIGHT (f), 0, true, Qtip_frame);
5845 /* Add `tooltip' frame parameter's default value. */
5846 if (NILP (Fframe_parameter (frame, Qtooltip)))
5847 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
5849 /* Set up faces after all frame parameters are known. This call
5850 also merges in face attributes specified for new frames.
5852 Frame parameters may be changed if .Xdefaults contains
5853 specifications for the default font. For example, if there is an
5854 `Emacs.default.attributeBackground: pink', the `background-color'
5855 attribute of the frame get's set, which let's the internal border
5856 of the tooltip frame appear in pink. Prevent this. */
5858 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
5859 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5860 Lisp_Object colors = Qnil;
5862 /* Set tip_frame here, so that */
5863 tip_frame = frame;
5864 call2 (Qface_set_after_frame_default, frame, Qnil);
5866 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
5867 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5868 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5869 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5871 if (!NILP (colors))
5872 Fmodify_frame_parameters (frame, colors);
5875 f->no_split = true;
5877 UNGCPRO;
5879 /* Now that the frame is official, it counts as a reference to
5880 its display. */
5881 FRAME_DISPLAY_INFO (f)->reference_count++;
5882 f->terminal->reference_count++;
5884 /* It is now ok to make the frame official even if we get an error
5885 below. And the frame needs to be on Vframe_list or making it
5886 visible won't work. */
5887 Vframe_list = Fcons (frame, Vframe_list);
5888 f->can_x_set_window_size = true;
5890 /* Setting attributes of faces of the tooltip frame from resources
5891 and similar will set face_change, which leads to the
5892 clearing of all current matrices. Since this isn't necessary
5893 here, avoid it by resetting face_change to the value it
5894 had before we created the tip frame. */
5895 face_change = face_change_before;
5897 /* Discard the unwind_protect. */
5898 return unbind_to (count, frame);
5902 /* Compute where to display tip frame F. PARMS is the list of frame
5903 parameters for F. DX and DY are specified offsets from the current
5904 location of the mouse. WIDTH and HEIGHT are the width and height
5905 of the tooltip. Return coordinates relative to the root window of
5906 the display in *ROOT_X, and *ROOT_Y. */
5908 static void
5909 compute_tip_xy (struct frame *f,
5910 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5911 int width, int height, int *root_x, int *root_y)
5913 Lisp_Object left, top;
5914 int min_x, min_y, max_x, max_y;
5916 /* User-specified position? */
5917 left = Fcdr (Fassq (Qleft, parms));
5918 top = Fcdr (Fassq (Qtop, parms));
5920 /* Move the tooltip window where the mouse pointer is. Resize and
5921 show it. */
5922 if (!INTEGERP (left) || !INTEGERP (top))
5924 POINT pt;
5926 /* Default min and max values. */
5927 min_x = 0;
5928 min_y = 0;
5929 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5930 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
5932 block_input ();
5933 GetCursorPos (&pt);
5934 *root_x = pt.x;
5935 *root_y = pt.y;
5936 unblock_input ();
5938 /* If multiple monitor support is available, constrain the tip onto
5939 the current monitor. This improves the above by allowing negative
5940 co-ordinates if monitor positions are such that they are valid, and
5941 snaps a tooltip onto a single monitor if we are close to the edge
5942 where it would otherwise flow onto the other monitor (or into
5943 nothingness if there is a gap in the overlap). */
5944 if (monitor_from_point_fn && get_monitor_info_fn)
5946 struct MONITOR_INFO info;
5947 HMONITOR monitor
5948 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5949 info.cbSize = sizeof (info);
5951 if (get_monitor_info_fn (monitor, &info))
5953 min_x = info.rcWork.left;
5954 min_y = info.rcWork.top;
5955 max_x = info.rcWork.right;
5956 max_y = info.rcWork.bottom;
5961 if (INTEGERP (top))
5962 *root_y = XINT (top);
5963 else if (*root_y + XINT (dy) <= min_y)
5964 *root_y = min_y; /* Can happen for negative dy */
5965 else if (*root_y + XINT (dy) + height <= max_y)
5966 /* It fits below the pointer */
5967 *root_y += XINT (dy);
5968 else if (height + XINT (dy) + min_y <= *root_y)
5969 /* It fits above the pointer. */
5970 *root_y -= height + XINT (dy);
5971 else
5972 /* Put it on the top. */
5973 *root_y = min_y;
5975 if (INTEGERP (left))
5976 *root_x = XINT (left);
5977 else if (*root_x + XINT (dx) <= min_x)
5978 *root_x = 0; /* Can happen for negative dx */
5979 else if (*root_x + XINT (dx) + width <= max_x)
5980 /* It fits to the right of the pointer. */
5981 *root_x += XINT (dx);
5982 else if (width + XINT (dx) + min_x <= *root_x)
5983 /* It fits to the left of the pointer. */
5984 *root_x -= width + XINT (dx);
5985 else
5986 /* Put it left justified on the screen -- it ought to fit that way. */
5987 *root_x = min_x;
5991 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
5992 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
5993 A tooltip window is a small window displaying a string.
5995 This is an internal function; Lisp code should call `tooltip-show'.
5997 FRAME nil or omitted means use the selected frame.
5999 PARMS is an optional list of frame parameters which can be
6000 used to change the tooltip's appearance.
6002 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6003 means use the default timeout of 5 seconds.
6005 If the list of frame parameters PARMS contains a `left' parameter,
6006 the tooltip is displayed at that x-position. Otherwise it is
6007 displayed at the mouse position, with offset DX added (default is 5 if
6008 DX isn't specified). Likewise for the y-position; if a `top' frame
6009 parameter is specified, it determines the y-position of the tooltip
6010 window, otherwise it is displayed at the mouse position, with offset
6011 DY added (default is -10).
6013 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6014 Text larger than the specified size is clipped. */)
6015 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6017 struct frame *f;
6018 struct window *w;
6019 int root_x, root_y;
6020 struct buffer *old_buffer;
6021 struct text_pos pos;
6022 int i, width, height;
6023 bool seen_reversed_p;
6024 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
6025 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6026 ptrdiff_t count = SPECPDL_INDEX ();
6028 specbind (Qinhibit_redisplay, Qt);
6030 GCPRO4 (string, parms, frame, timeout);
6032 CHECK_STRING (string);
6033 f = decode_window_system_frame (frame);
6034 if (NILP (timeout))
6035 timeout = make_number (5);
6036 else
6037 CHECK_NATNUM (timeout);
6039 if (NILP (dx))
6040 dx = make_number (5);
6041 else
6042 CHECK_NUMBER (dx);
6044 if (NILP (dy))
6045 dy = make_number (-10);
6046 else
6047 CHECK_NUMBER (dy);
6049 if (NILP (last_show_tip_args))
6050 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6052 if (!NILP (tip_frame))
6054 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6055 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6056 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6058 if (EQ (frame, last_frame)
6059 && !NILP (Fequal (last_string, string))
6060 && !NILP (Fequal (last_parms, parms)))
6062 struct frame *f = XFRAME (tip_frame);
6064 /* Only DX and DY have changed. */
6065 if (!NILP (tip_timer))
6067 Lisp_Object timer = tip_timer;
6068 tip_timer = Qnil;
6069 call1 (Qcancel_timer, timer);
6072 block_input ();
6073 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6074 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6076 /* Put tooltip in topmost group and in position. */
6077 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6078 root_x, root_y, 0, 0,
6079 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6081 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6082 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6083 0, 0, 0, 0,
6084 SWP_NOMOVE | SWP_NOSIZE
6085 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6087 unblock_input ();
6088 goto start_timer;
6092 /* Hide a previous tip, if any. */
6093 Fx_hide_tip ();
6095 ASET (last_show_tip_args, 0, string);
6096 ASET (last_show_tip_args, 1, frame);
6097 ASET (last_show_tip_args, 2, parms);
6099 /* Add default values to frame parameters. */
6100 if (NILP (Fassq (Qname, parms)))
6101 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6102 if (NILP (Fassq (Qinternal_border_width, parms)))
6103 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6104 if (NILP (Fassq (Qright_divider_width, parms)))
6105 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6106 if (NILP (Fassq (Qbottom_divider_width, parms)))
6107 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6108 if (NILP (Fassq (Qborder_width, parms)))
6109 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6110 if (NILP (Fassq (Qborder_color, parms)))
6111 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6112 if (NILP (Fassq (Qbackground_color, parms)))
6113 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6114 parms);
6116 /* Block input until the tip has been fully drawn, to avoid crashes
6117 when drawing tips in menus. */
6118 block_input ();
6120 /* Create a frame for the tooltip, and record it in the global
6121 variable tip_frame. */
6122 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6123 f = XFRAME (frame);
6125 /* Set up the frame's root window. */
6126 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6127 w->left_col = 0;
6128 w->top_line = 0;
6129 w->pixel_left = 0;
6130 w->pixel_top = 0;
6132 if (CONSP (Vx_max_tooltip_size)
6133 && INTEGERP (XCAR (Vx_max_tooltip_size))
6134 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6135 && INTEGERP (XCDR (Vx_max_tooltip_size))
6136 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6138 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6139 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6141 else
6143 w->total_cols = 80;
6144 w->total_lines = 40;
6147 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6148 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6150 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6151 adjust_frame_glyphs (f);
6152 w->pseudo_window_p = true;
6154 /* Display the tooltip text in a temporary buffer. */
6155 old_buffer = current_buffer;
6156 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6157 bset_truncate_lines (current_buffer, Qnil);
6158 clear_glyph_matrix (w->desired_matrix);
6159 clear_glyph_matrix (w->current_matrix);
6160 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6161 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6163 /* Compute width and height of the tooltip. */
6164 width = height = 0;
6165 seen_reversed_p = false;
6166 for (i = 0; i < w->desired_matrix->nrows; ++i)
6168 struct glyph_row *row = &w->desired_matrix->rows[i];
6169 struct glyph *last;
6170 int row_width;
6172 /* Stop at the first empty row at the end. */
6173 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6174 break;
6176 /* Let the row go over the full width of the frame. */
6177 row->full_width_p = true;
6179 row_width = row->pixel_width;
6180 if (row->used[TEXT_AREA])
6182 if (!row->reversed_p)
6184 /* There's a glyph at the end of rows that is used to
6185 place the cursor there. Don't include the width of
6186 this glyph. */
6187 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6188 if (NILP (last->object))
6189 row_width -= last->pixel_width;
6191 else
6193 /* There could be a stretch glyph at the beginning of R2L
6194 rows that is produced by extend_face_to_end_of_line.
6195 Don't count that glyph. */
6196 struct glyph *g = row->glyphs[TEXT_AREA];
6198 if (g->type == STRETCH_GLYPH && NILP (g->object))
6200 row_width -= g->pixel_width;
6201 seen_reversed_p = true;
6206 height += row->height;
6207 width = max (width, row_width);
6210 /* If we've seen partial-length R2L rows, we need to re-adjust the
6211 tool-tip frame width and redisplay it again, to avoid over-wide
6212 tips due to the stretch glyph that extends R2L lines to full
6213 width of the frame. */
6214 if (seen_reversed_p)
6216 /* PXW: Why do we do the pixel-to-cols conversion only if
6217 seen_reversed_p holds? Don't we have to set other fields of
6218 the window/frame structure?
6220 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6221 not in pixels. */
6222 w->pixel_width = width;
6223 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6224 w->total_cols = width;
6225 FRAME_TOTAL_COLS (f) = width;
6226 SET_FRAME_WIDTH (f, width);
6227 adjust_frame_glyphs (f);
6228 w->pseudo_window_p = 1;
6229 clear_glyph_matrix (w->desired_matrix);
6230 clear_glyph_matrix (w->current_matrix);
6231 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6232 width = height = 0;
6233 /* Recompute width and height of the tooltip. */
6234 for (i = 0; i < w->desired_matrix->nrows; ++i)
6236 struct glyph_row *row = &w->desired_matrix->rows[i];
6237 struct glyph *last;
6238 int row_width;
6240 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6241 break;
6242 row->full_width_p = true;
6243 row_width = row->pixel_width;
6244 if (row->used[TEXT_AREA] && !row->reversed_p)
6246 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6247 if (NILP (last->object))
6248 row_width -= last->pixel_width;
6251 height += row->height;
6252 width = max (width, row_width);
6256 /* Add the frame's internal border to the width and height the w32
6257 window should have. */
6258 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6259 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6261 /* Move the tooltip window where the mouse pointer is. Resize and
6262 show it.
6264 PXW: This should use the frame's pixel coordinates. */
6265 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6268 /* Adjust Window size to take border into account. */
6269 RECT rect;
6270 rect.left = rect.top = 0;
6271 rect.right = width;
6272 rect.bottom = height;
6273 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6274 FRAME_EXTERNAL_MENU_BAR (f));
6276 /* Position and size tooltip, and put it in the topmost group.
6277 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6278 peculiarity of w32 display: without it, some fonts cause the
6279 last character of the tip to be truncated or wrapped around to
6280 the next line. */
6281 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6282 root_x, root_y,
6283 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6284 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6286 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6287 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6288 0, 0, 0, 0,
6289 SWP_NOMOVE | SWP_NOSIZE
6290 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6292 /* Let redisplay know that we have made the frame visible already. */
6293 SET_FRAME_VISIBLE (f, 1);
6295 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6298 /* Draw into the window. */
6299 w->must_be_updated_p = true;
6300 update_single_window (w);
6302 unblock_input ();
6304 /* Restore original current buffer. */
6305 set_buffer_internal_1 (old_buffer);
6306 windows_or_buffers_changed = old_windows_or_buffers_changed;
6308 start_timer:
6309 /* Let the tip disappear after timeout seconds. */
6310 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6311 intern ("x-hide-tip"));
6313 UNGCPRO;
6314 return unbind_to (count, Qnil);
6318 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6319 doc: /* Hide the current tooltip window, if there is any.
6320 Value is t if tooltip was open, nil otherwise. */)
6321 (void)
6323 ptrdiff_t count;
6324 Lisp_Object deleted, frame, timer;
6325 struct gcpro gcpro1, gcpro2;
6327 /* Return quickly if nothing to do. */
6328 if (NILP (tip_timer) && NILP (tip_frame))
6329 return Qnil;
6331 frame = tip_frame;
6332 timer = tip_timer;
6333 GCPRO2 (frame, timer);
6334 tip_frame = tip_timer = deleted = Qnil;
6336 count = SPECPDL_INDEX ();
6337 specbind (Qinhibit_redisplay, Qt);
6338 specbind (Qinhibit_quit, Qt);
6340 if (!NILP (timer))
6341 call1 (Qcancel_timer, timer);
6343 if (FRAMEP (frame))
6345 delete_frame (frame, Qnil);
6346 deleted = Qt;
6349 UNGCPRO;
6350 return unbind_to (count, deleted);
6353 /***********************************************************************
6354 File selection dialog
6355 ***********************************************************************/
6357 #define FILE_NAME_TEXT_FIELD edt1
6358 #define FILE_NAME_COMBO_BOX cmb13
6359 #define FILE_NAME_LIST lst1
6361 /* Callback for altering the behavior of the Open File dialog.
6362 Makes the Filename text field contain "Current Directory" and be
6363 read-only when "Directories" is selected in the filter. This
6364 allows us to work around the fact that the standard Open File
6365 dialog does not support directories. */
6366 static UINT_PTR CALLBACK
6367 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6369 if (msg == WM_NOTIFY)
6371 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6372 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6373 int dropdown_changed;
6374 int dir_index;
6375 #ifdef NTGUI_UNICODE
6376 const int use_unicode = 1;
6377 #else /* !NTGUI_UNICODE */
6378 int use_unicode = w32_unicode_filenames;
6379 #endif /* NTGUI_UNICODE */
6381 /* Detect when the Filter dropdown is changed. */
6382 if (use_unicode)
6383 dropdown_changed =
6384 notify_w->hdr.code == CDN_TYPECHANGE
6385 || notify_w->hdr.code == CDN_INITDONE;
6386 else
6387 dropdown_changed =
6388 notify_a->hdr.code == CDN_TYPECHANGE
6389 || notify_a->hdr.code == CDN_INITDONE;
6390 if (dropdown_changed)
6392 HWND dialog = GetParent (hwnd);
6393 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6394 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6395 int hdr_code;
6397 /* At least on Windows 7, the above attempt to get the window handle
6398 to the File Name Text Field fails. The following code does the
6399 job though. Note that this code is based on my examination of the
6400 window hierarchy using Microsoft Spy++. bk */
6401 if (edit_control == NULL)
6403 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6404 if (tmp)
6406 tmp = GetWindow (tmp, GW_CHILD);
6407 if (tmp)
6408 edit_control = GetWindow (tmp, GW_CHILD);
6412 /* Directories is in index 2. */
6413 if (use_unicode)
6415 dir_index = notify_w->lpOFN->nFilterIndex;
6416 hdr_code = notify_w->hdr.code;
6418 else
6420 dir_index = notify_a->lpOFN->nFilterIndex;
6421 hdr_code = notify_a->hdr.code;
6423 if (dir_index == 2)
6425 if (use_unicode)
6426 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6427 (LPARAM)L"Current Directory");
6428 else
6429 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6430 (LPARAM)"Current Directory");
6431 EnableWindow (edit_control, FALSE);
6432 /* Note that at least on Windows 7, the above call to EnableWindow
6433 disables the window that would ordinarily have focus. If we
6434 do not set focus to some other window here, focus will land in
6435 no man's land and the user will be unable to tab through the
6436 dialog box (pressing tab will only result in a beep).
6437 Avoid that problem by setting focus to the list here. */
6438 if (hdr_code == CDN_INITDONE)
6439 SetFocus (list);
6441 else
6443 /* Don't override default filename on init done. */
6444 if (hdr_code == CDN_TYPECHANGE)
6446 if (use_unicode)
6447 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6448 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6449 else
6450 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6451 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6453 EnableWindow (edit_control, TRUE);
6457 return 0;
6460 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6461 doc: /* Read file name, prompting with PROMPT in directory DIR.
6462 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6463 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6464 or directory must exist.
6466 This function is only defined on NS, MS Windows, and X Windows with the
6467 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6468 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6469 On Windows 7 and later, the file selection dialog "remembers" the last
6470 directory where the user selected a file, and will open that directory
6471 instead of DIR on subsequent invocations of this function with the same
6472 value of DIR as in previous invocations; this is standard Windows behavior. */)
6473 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6475 /* Filter index: 1: All Files, 2: Directories only */
6476 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6477 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6479 Lisp_Object filename = default_filename;
6480 struct frame *f = SELECTED_FRAME ();
6481 BOOL file_opened = FALSE;
6482 Lisp_Object orig_dir = dir;
6483 Lisp_Object orig_prompt = prompt;
6485 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6486 compatibility) we end up with the old file dialogs. Define a big
6487 enough struct for the new dialog to trick GetOpenFileName into
6488 giving us the new dialogs on newer versions of Windows. */
6489 struct {
6490 OPENFILENAMEW details;
6491 #if _WIN32_WINNT < 0x500 /* < win2k */
6492 PVOID pvReserved;
6493 DWORD dwReserved;
6494 DWORD FlagsEx;
6495 #endif /* < win2k */
6496 } new_file_details_w;
6498 #ifdef NTGUI_UNICODE
6499 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6500 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6501 const int use_unicode = 1;
6502 #else /* not NTGUI_UNICODE */
6503 struct {
6504 OPENFILENAMEA details;
6505 #if _WIN32_WINNT < 0x500 /* < win2k */
6506 PVOID pvReserved;
6507 DWORD dwReserved;
6508 DWORD FlagsEx;
6509 #endif /* < win2k */
6510 } new_file_details_a;
6511 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6512 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6513 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6514 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6515 int use_unicode = w32_unicode_filenames;
6516 wchar_t *prompt_w;
6517 char *prompt_a;
6518 int len;
6519 char fname_ret[MAX_UTF8_PATH];
6520 #endif /* NTGUI_UNICODE */
6522 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
6523 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
6526 struct gcpro gcpro1, gcpro2;
6527 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
6529 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6530 system file encoding expected by the platform APIs (e.g. Cygwin's
6531 POSIX implementation) may not be the same as the encoding expected
6532 by the Windows "ANSI" APIs! */
6534 CHECK_STRING (prompt);
6535 CHECK_STRING (dir);
6537 dir = Fexpand_file_name (dir, Qnil);
6539 if (STRINGP (filename))
6540 filename = Ffile_name_nondirectory (filename);
6541 else
6542 filename = empty_unibyte_string;
6544 #ifdef CYGWIN
6545 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
6546 if (SCHARS (filename) > 0)
6547 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
6548 #endif
6550 CHECK_STRING (dir);
6551 CHECK_STRING (filename);
6553 /* The code in file_dialog_callback that attempts to set the text
6554 of the file name edit window when handling the CDN_INITDONE
6555 WM_NOTIFY message does not work. Setting filename to "Current
6556 Directory" in the only_dir_p case here does work however. */
6557 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6558 filename = build_string ("Current Directory");
6560 /* Convert the values we've computed so far to system form. */
6561 #ifdef NTGUI_UNICODE
6562 to_unicode (prompt, &prompt);
6563 to_unicode (dir, &dir);
6564 to_unicode (filename, &filename);
6565 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6566 report_file_error ("filename too long", default_filename);
6568 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
6569 #else /* !NTGUI_UNICODE */
6570 prompt = ENCODE_FILE (prompt);
6571 dir = ENCODE_FILE (dir);
6572 filename = ENCODE_FILE (filename);
6574 /* We modify these in-place, so make copies for safety. */
6575 dir = Fcopy_sequence (dir);
6576 unixtodos_filename (SDATA (dir));
6577 filename = Fcopy_sequence (filename);
6578 unixtodos_filename (SDATA (filename));
6579 if (SBYTES (filename) >= MAX_UTF8_PATH)
6580 report_file_error ("filename too long", default_filename);
6581 if (w32_unicode_filenames)
6583 filename_to_utf16 (SSDATA (dir), dir_w);
6584 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6586 /* filename_to_utf16 sets errno to ENOENT when the file
6587 name is too long or cannot be converted to UTF-16. */
6588 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6589 report_file_error ("filename too long", default_filename);
6591 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6592 SSDATA (prompt), -1, NULL, 0);
6593 if (len > 32768)
6594 len = 32768;
6595 prompt_w = alloca (len * sizeof (wchar_t));
6596 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6597 SSDATA (prompt), -1, prompt_w, len);
6599 else
6601 filename_to_ansi (SSDATA (dir), dir_a);
6602 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6604 /* filename_to_ansi sets errno to ENOENT when the file
6605 name is too long or cannot be converted to UTF-16. */
6606 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6607 report_file_error ("filename too long", default_filename);
6609 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6610 SSDATA (prompt), -1, NULL, 0);
6611 if (len > 32768)
6612 len = 32768;
6613 prompt_w = alloca (len * sizeof (wchar_t));
6614 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6615 SSDATA (prompt), -1, prompt_w, len);
6616 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
6617 if (len > 32768)
6618 len = 32768;
6619 prompt_a = alloca (len);
6620 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
6622 #endif /* NTGUI_UNICODE */
6624 /* Fill in the structure for the call to GetOpenFileName below.
6625 For NTGUI_UNICODE builds (which run only on NT), we just use
6626 the actual size of the structure. For non-NTGUI_UNICODE
6627 builds, we tell the OS we're using an old version of the
6628 structure if the OS isn't new enough to support the newer
6629 version. */
6630 if (use_unicode)
6632 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6633 if (w32_major_version > 4 && w32_major_version < 95)
6634 file_details_w->lStructSize = sizeof (new_file_details_w);
6635 else
6636 file_details_w->lStructSize = sizeof (*file_details_w);
6637 /* Set up the inout parameter for the selected file name. */
6638 file_details_w->lpstrFile = filename_buf_w;
6639 file_details_w->nMaxFile =
6640 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6641 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6642 /* Undocumented Bug in Common File Dialog:
6643 If a filter is not specified, shell links are not resolved. */
6644 file_details_w->lpstrFilter = filter_w;
6645 #ifdef NTGUI_UNICODE
6646 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
6647 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
6648 #else
6649 file_details_w->lpstrInitialDir = dir_w;
6650 file_details_w->lpstrTitle = prompt_w;
6651 #endif
6652 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6653 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6654 | OFN_EXPLORER | OFN_ENABLEHOOK);
6655 if (!NILP (mustmatch))
6657 /* Require that the path to the parent directory exists. */
6658 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6659 /* If we are looking for a file, require that it exists. */
6660 if (NILP (only_dir_p))
6661 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6664 #ifndef NTGUI_UNICODE
6665 else
6667 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6668 if (w32_major_version > 4 && w32_major_version < 95)
6669 file_details_a->lStructSize = sizeof (new_file_details_a);
6670 else
6671 file_details_a->lStructSize = sizeof (*file_details_a);
6672 file_details_a->lpstrFile = filename_buf_a;
6673 file_details_a->nMaxFile =
6674 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6675 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6676 file_details_a->lpstrFilter = filter_a;
6677 file_details_a->lpstrInitialDir = dir_a;
6678 file_details_a->lpstrTitle = prompt_a;
6679 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6680 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6681 | OFN_EXPLORER | OFN_ENABLEHOOK);
6682 if (!NILP (mustmatch))
6684 /* Require that the path to the parent directory exists. */
6685 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6686 /* If we are looking for a file, require that it exists. */
6687 if (NILP (only_dir_p))
6688 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6691 #endif /* !NTGUI_UNICODE */
6694 int count = SPECPDL_INDEX ();
6695 /* Prevent redisplay. */
6696 specbind (Qinhibit_redisplay, Qt);
6697 block_input ();
6698 if (use_unicode)
6700 file_details_w->lpfnHook = file_dialog_callback;
6702 file_opened = GetOpenFileNameW (file_details_w);
6704 #ifndef NTGUI_UNICODE
6705 else
6707 file_details_a->lpfnHook = file_dialog_callback;
6709 file_opened = GetOpenFileNameA (file_details_a);
6711 #endif /* !NTGUI_UNICODE */
6712 unblock_input ();
6713 unbind_to (count, Qnil);
6716 if (file_opened)
6718 /* Get an Emacs string from the value Windows gave us. */
6719 #ifdef NTGUI_UNICODE
6720 filename = from_unicode_buffer (filename_buf_w);
6721 #else /* !NTGUI_UNICODE */
6722 if (use_unicode)
6723 filename_from_utf16 (filename_buf_w, fname_ret);
6724 else
6725 filename_from_ansi (filename_buf_a, fname_ret);
6726 dostounix_filename (fname_ret);
6727 filename = DECODE_FILE (build_unibyte_string (fname_ret));
6728 #endif /* NTGUI_UNICODE */
6730 #ifdef CYGWIN
6731 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
6732 #endif /* CYGWIN */
6734 /* Strip the dummy filename off the end of the string if we
6735 added it to select a directory. */
6736 if ((use_unicode && file_details_w->nFilterIndex == 2)
6737 #ifndef NTGUI_UNICODE
6738 || (!use_unicode && file_details_a->nFilterIndex == 2)
6739 #endif
6741 filename = Ffile_name_directory (filename);
6743 /* User canceled the dialog without making a selection. */
6744 else if (!CommDlgExtendedError ())
6745 filename = Qnil;
6746 /* An error occurred, fallback on reading from the mini-buffer. */
6747 else
6748 filename = Fcompleting_read (
6749 orig_prompt,
6750 intern ("read-file-name-internal"),
6751 orig_dir,
6752 mustmatch,
6753 orig_dir,
6754 Qfile_name_history,
6755 default_filename,
6756 Qnil);
6758 UNGCPRO;
6761 /* Make "Cancel" equivalent to C-g. */
6762 if (NILP (filename))
6763 Fsignal (Qquit, Qnil);
6765 RETURN_UNGCPRO (filename);
6769 #ifdef WINDOWSNT
6770 /* Moving files to the system recycle bin.
6771 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6772 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6773 Ssystem_move_file_to_trash, 1, 1, 0,
6774 doc: /* Move file or directory named FILENAME to the recycle bin. */)
6775 (Lisp_Object filename)
6777 Lisp_Object handler;
6778 Lisp_Object encoded_file;
6779 Lisp_Object operation;
6781 operation = Qdelete_file;
6782 if (!NILP (Ffile_directory_p (filename))
6783 && NILP (Ffile_symlink_p (filename)))
6785 operation = intern ("delete-directory");
6786 filename = Fdirectory_file_name (filename);
6789 /* Must have fully qualified file names for moving files to Recycle
6790 Bin. */
6791 filename = Fexpand_file_name (filename, Qnil);
6793 handler = Ffind_file_name_handler (filename, operation);
6794 if (!NILP (handler))
6795 return call2 (handler, operation, filename);
6796 else
6798 const char * path;
6799 int result;
6801 encoded_file = ENCODE_FILE (filename);
6803 path = map_w32_filename (SDATA (encoded_file), NULL);
6805 /* The Unicode version of SHFileOperation is not supported on
6806 Windows 9X. */
6807 if (w32_unicode_filenames && os_subtype != OS_9X)
6809 SHFILEOPSTRUCTW file_op_w;
6810 /* We need one more element beyond MAX_PATH because this is
6811 a list of file names, with the last element double-null
6812 terminated. */
6813 wchar_t tmp_path_w[MAX_PATH + 1];
6815 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6816 filename_to_utf16 (path, tmp_path_w);
6818 /* On Windows, write permission is required to delete/move files. */
6819 _wchmod (tmp_path_w, 0666);
6821 memset (&file_op_w, 0, sizeof (file_op_w));
6822 file_op_w.hwnd = HWND_DESKTOP;
6823 file_op_w.wFunc = FO_DELETE;
6824 file_op_w.pFrom = tmp_path_w;
6825 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6826 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6827 file_op_w.fAnyOperationsAborted = FALSE;
6829 result = SHFileOperationW (&file_op_w);
6831 else
6833 SHFILEOPSTRUCTA file_op_a;
6834 char tmp_path_a[MAX_PATH + 1];
6836 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6837 filename_to_ansi (path, tmp_path_a);
6839 /* If a file cannot be represented in ANSI codepage, don't
6840 let them inadvertently delete other files because some
6841 characters are interpreted as a wildcards. */
6842 if (_mbspbrk (tmp_path_a, "?*"))
6843 result = ERROR_FILE_NOT_FOUND;
6844 else
6846 _chmod (tmp_path_a, 0666);
6848 memset (&file_op_a, 0, sizeof (file_op_a));
6849 file_op_a.hwnd = HWND_DESKTOP;
6850 file_op_a.wFunc = FO_DELETE;
6851 file_op_a.pFrom = tmp_path_a;
6852 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6853 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6854 file_op_a.fAnyOperationsAborted = FALSE;
6856 result = SHFileOperationA (&file_op_a);
6859 if (result != 0)
6860 report_file_error ("Removing old name", list1 (filename));
6862 return Qnil;
6865 #endif /* WINDOWSNT */
6868 /***********************************************************************
6869 w32 specialized functions
6870 ***********************************************************************/
6872 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6873 Sw32_send_sys_command, 1, 2, 0,
6874 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
6875 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
6876 to minimize), #xf120 to restore frame to original size, and #xf100
6877 to activate the menubar for keyboard access. #xf140 activates the
6878 screen saver if defined.
6880 If optional parameter FRAME is not specified, use selected frame. */)
6881 (Lisp_Object command, Lisp_Object frame)
6883 struct frame *f = decode_window_system_frame (frame);
6885 CHECK_NUMBER (command);
6887 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
6889 return Qnil;
6892 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
6893 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6894 This is a wrapper around the ShellExecute system function, which
6895 invokes the application registered to handle OPERATION for DOCUMENT.
6897 OPERATION is either nil or a string that names a supported operation.
6898 What operations can be used depends on the particular DOCUMENT and its
6899 handler application, but typically it is one of the following common
6900 operations:
6902 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6903 executable program (application). If it is an application,
6904 that application is launched in the current buffer's default
6905 directory. Otherwise, the application associated with
6906 DOCUMENT is launched in the buffer's default directory.
6907 \"opennew\" - like \"open\", but instruct the application to open
6908 DOCUMENT in a new window.
6909 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
6910 \"print\" - print DOCUMENT, which must be a file.
6911 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
6912 The printer should be provided in PARAMETERS, see below.
6913 \"explore\" - start the Windows Explorer on DOCUMENT.
6914 \"edit\" - launch an editor and open DOCUMENT for editing; which
6915 editor is launched depends on the association for the
6916 specified DOCUMENT.
6917 \"find\" - initiate search starting from DOCUMENT, which must specify
6918 a directory.
6919 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
6920 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
6921 the clipboard.
6922 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
6923 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
6924 which must be a directory.
6925 \"pastelink\"
6926 - create a shortcut in DOCUMENT (which must be a directory)
6927 the file or directory whose name is in the clipboard.
6928 \"runas\" - run DOCUMENT, which must be an excutable file, with
6929 elevated privileges (a.k.a. \"as Administrator\").
6930 \"properties\"
6931 - open the property sheet dialog for DOCUMENT.
6932 nil - invoke the default OPERATION, or \"open\" if default is
6933 not defined or unavailable.
6935 DOCUMENT is typically the name of a document file or a URL, but can
6936 also be an executable program to run, or a directory to open in the
6937 Windows Explorer. If it is a file or a directory, it must be a local
6938 one; this function does not support remote file names.
6940 If DOCUMENT is an executable program, the optional third arg PARAMETERS
6941 can be a string containing command line parameters, separated by blanks,
6942 that will be passed to the program. Some values of OPERATION also require
6943 parameters (e.g., \"printto\" requires the printer address). Otherwise,
6944 PARAMETERS should be nil or unspecified. Note that double quote characters
6945 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
6947 Optional fourth argument SHOW-FLAG can be used to control how the
6948 application will be displayed when it is invoked. If SHOW-FLAG is nil
6949 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
6950 specified, otherwise it is an integer between 0 and 11 representing
6951 a ShowWindow flag:
6953 0 - start hidden
6954 1 - start as normal-size window
6955 3 - start in a maximized window
6956 6 - start in a minimized window
6957 10 - start as the application itself specifies; this is the default. */)
6958 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
6960 char *errstr;
6961 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6962 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
6963 #ifdef CYGWIN
6964 intptr_t result;
6965 #else
6966 int use_unicode = w32_unicode_filenames;
6967 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
6968 Lisp_Object absdoc, handler;
6969 BOOL success;
6970 struct gcpro gcpro1;
6971 #endif
6973 CHECK_STRING (document);
6975 #ifdef CYGWIN
6976 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
6977 document = Fcygwin_convert_file_name_to_windows (document, Qt);
6979 /* Encode filename, current directory and parameters. */
6980 current_dir = GUI_ENCODE_FILE (current_dir);
6981 document = GUI_ENCODE_FILE (document);
6982 doc_w = GUI_SDATA (document);
6983 if (STRINGP (parameters))
6985 parameters = GUI_ENCODE_SYSTEM (parameters);
6986 params_w = GUI_SDATA (parameters);
6988 if (STRINGP (operation))
6990 operation = GUI_ENCODE_SYSTEM (operation);
6991 ops_w = GUI_SDATA (operation);
6993 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6994 GUI_SDATA (current_dir),
6995 (INTEGERP (show_flag)
6996 ? XINT (show_flag) : SW_SHOWDEFAULT));
6998 if (result > 32)
6999 return Qt;
7001 switch (result)
7003 case SE_ERR_ACCESSDENIED:
7004 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7005 break;
7006 case SE_ERR_ASSOCINCOMPLETE:
7007 case SE_ERR_NOASSOC:
7008 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7009 break;
7010 case SE_ERR_DDEBUSY:
7011 case SE_ERR_DDEFAIL:
7012 errstr = w32_strerror (ERROR_DDE_FAIL);
7013 break;
7014 case SE_ERR_DDETIMEOUT:
7015 errstr = w32_strerror (ERROR_TIMEOUT);
7016 break;
7017 case SE_ERR_DLLNOTFOUND:
7018 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7019 break;
7020 case SE_ERR_FNF:
7021 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7022 break;
7023 case SE_ERR_OOM:
7024 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7025 break;
7026 case SE_ERR_PNF:
7027 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7028 break;
7029 case SE_ERR_SHARE:
7030 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7031 break;
7032 default:
7033 errstr = w32_strerror (0);
7034 break;
7037 #else /* !CYGWIN */
7039 current_dir = ENCODE_FILE (current_dir);
7040 /* We have a situation here. If DOCUMENT is a relative file name,
7041 but its name includes leading directories, i.e. it lives not in
7042 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7043 will fail to find it. So we need to make the file name is
7044 absolute. But DOCUMENT does not have to be a file, it can be a
7045 URL, for example. So we make it absolute only if it is an
7046 existing file; if it is a file that does not exist, tough. */
7047 GCPRO1 (absdoc);
7048 absdoc = Fexpand_file_name (document, Qnil);
7049 /* Don't call file handlers for file-exists-p, since they might
7050 attempt to access the file, which could fail or produce undesired
7051 consequences, see bug#16558 for an example. */
7052 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7053 if (NILP (handler))
7055 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7057 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7059 /* ShellExecute fails if DOCUMENT is a UNC with forward
7060 slashes (expand-file-name above converts all backslashes
7061 to forward slashes). Now that we know DOCUMENT is a
7062 file, we can mirror all forward slashes into backslashes. */
7063 unixtodos_filename (SSDATA (absdoc_encoded));
7064 document = absdoc_encoded;
7066 else
7067 document = ENCODE_FILE (document);
7069 else
7070 document = ENCODE_FILE (document);
7071 UNGCPRO;
7072 if (use_unicode)
7074 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
7075 SHELLEXECUTEINFOW shexinfo_w;
7077 /* Encode filename, current directory and parameters, and
7078 convert operation to UTF-16. */
7079 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7080 filename_to_utf16 (SSDATA (document), document_w);
7081 doc_w = document_w;
7082 if (STRINGP (parameters))
7084 int len;
7086 parameters = ENCODE_SYSTEM (parameters);
7087 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7088 SSDATA (parameters), -1, NULL, 0);
7089 if (len > 32768)
7090 len = 32768;
7091 params_w = alloca (len * sizeof (wchar_t));
7092 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7093 SSDATA (parameters), -1, params_w, len);
7095 if (STRINGP (operation))
7097 /* Assume OPERATION is pure ASCII. */
7098 const char *s = SSDATA (operation);
7099 wchar_t *d;
7100 int len = SBYTES (operation) + 1;
7102 if (len > 32768)
7103 len = 32768;
7104 d = ops_w = alloca (len * sizeof (wchar_t));
7105 while (d < ops_w + len - 1)
7106 *d++ = *s++;
7107 *d = 0;
7110 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7111 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7112 able to invoke verbs from shortcut menu extensions, not just
7113 static verbs listed in the Registry. */
7114 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7115 shexinfo_w.cbSize = sizeof (shexinfo_w);
7116 shexinfo_w.fMask =
7117 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7118 shexinfo_w.hwnd = NULL;
7119 shexinfo_w.lpVerb = ops_w;
7120 shexinfo_w.lpFile = doc_w;
7121 shexinfo_w.lpParameters = params_w;
7122 shexinfo_w.lpDirectory = current_dir_w;
7123 shexinfo_w.nShow =
7124 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7125 success = ShellExecuteExW (&shexinfo_w);
7127 else
7129 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7130 SHELLEXECUTEINFOA shexinfo_a;
7132 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7133 filename_to_ansi (SSDATA (document), document_a);
7134 doc_a = document_a;
7135 if (STRINGP (parameters))
7137 parameters = ENCODE_SYSTEM (parameters);
7138 params_a = SSDATA (parameters);
7140 if (STRINGP (operation))
7142 /* Assume OPERATION is pure ASCII. */
7143 ops_a = SSDATA (operation);
7145 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7146 shexinfo_a.cbSize = sizeof (shexinfo_a);
7147 shexinfo_a.fMask =
7148 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7149 shexinfo_a.hwnd = NULL;
7150 shexinfo_a.lpVerb = ops_a;
7151 shexinfo_a.lpFile = doc_a;
7152 shexinfo_a.lpParameters = params_a;
7153 shexinfo_a.lpDirectory = current_dir_a;
7154 shexinfo_a.nShow =
7155 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7156 success = ShellExecuteExA (&shexinfo_a);
7159 if (success)
7160 return Qt;
7162 errstr = w32_strerror (0);
7164 #endif /* !CYGWIN */
7166 /* The error string might be encoded in the locale's encoding. */
7167 if (!NILP (Vlocale_coding_system))
7169 Lisp_Object decoded =
7170 code_convert_string_norecord (build_unibyte_string (errstr),
7171 Vlocale_coding_system, 0);
7172 errstr = SSDATA (decoded);
7174 error ("ShellExecute failed: %s", errstr);
7177 /* Lookup virtual keycode from string representing the name of a
7178 non-ascii keystroke into the corresponding virtual key, using
7179 lispy_function_keys. */
7180 static int
7181 lookup_vk_code (char *key)
7183 int i;
7185 for (i = 0; i < 256; i++)
7186 if (lispy_function_keys[i]
7187 && strcmp (lispy_function_keys[i], key) == 0)
7188 return i;
7190 return -1;
7193 /* Convert a one-element vector style key sequence to a hot key
7194 definition. */
7195 static Lisp_Object
7196 w32_parse_hot_key (Lisp_Object key)
7198 /* Copied from Fdefine_key and store_in_keymap. */
7199 register Lisp_Object c;
7200 int vk_code;
7201 int lisp_modifiers;
7202 int w32_modifiers;
7203 struct gcpro gcpro1;
7205 CHECK_VECTOR (key);
7207 if (ASIZE (key) != 1)
7208 return Qnil;
7210 GCPRO1 (key);
7212 c = AREF (key, 0);
7214 if (CONSP (c) && lucid_event_type_list_p (c))
7215 c = Fevent_convert_list (c);
7217 UNGCPRO;
7219 if (! INTEGERP (c) && ! SYMBOLP (c))
7220 error ("Key definition is invalid");
7222 /* Work out the base key and the modifiers. */
7223 if (SYMBOLP (c))
7225 c = parse_modifiers (c);
7226 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7227 c = Fcar (c);
7228 if (!SYMBOLP (c))
7229 emacs_abort ();
7230 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7232 else if (INTEGERP (c))
7234 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7235 /* Many ascii characters are their own virtual key code. */
7236 vk_code = XINT (c) & CHARACTERBITS;
7239 if (vk_code < 0 || vk_code > 255)
7240 return Qnil;
7242 if ((lisp_modifiers & meta_modifier) != 0
7243 && !NILP (Vw32_alt_is_meta))
7244 lisp_modifiers |= alt_modifier;
7246 /* Supply defs missing from mingw32. */
7247 #ifndef MOD_ALT
7248 #define MOD_ALT 0x0001
7249 #define MOD_CONTROL 0x0002
7250 #define MOD_SHIFT 0x0004
7251 #define MOD_WIN 0x0008
7252 #endif
7254 /* Convert lisp modifiers to Windows hot-key form. */
7255 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7256 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7257 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7258 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7260 return HOTKEY (vk_code, w32_modifiers);
7263 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7264 Sw32_register_hot_key, 1, 1, 0,
7265 doc: /* Register KEY as a hot-key combination.
7266 Certain key combinations like Alt-Tab are reserved for system use on
7267 Windows, and therefore are normally intercepted by the system. However,
7268 most of these key combinations can be received by registering them as
7269 hot-keys, overriding their special meaning.
7271 KEY must be a one element key definition in vector form that would be
7272 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7273 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7274 is always interpreted as the Windows modifier keys.
7276 The return value is the hotkey-id if registered, otherwise nil. */)
7277 (Lisp_Object key)
7279 key = w32_parse_hot_key (key);
7281 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7283 /* Reuse an empty slot if possible. */
7284 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7286 /* Safe to add new key to list, even if we have focus. */
7287 if (NILP (item))
7288 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7289 else
7290 XSETCAR (item, key);
7292 /* Notify input thread about new hot-key definition, so that it
7293 takes effect without needing to switch focus. */
7294 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7295 (WPARAM) XINT (key), 0);
7298 return key;
7301 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7302 Sw32_unregister_hot_key, 1, 1, 0,
7303 doc: /* Unregister KEY as a hot-key combination. */)
7304 (Lisp_Object key)
7306 Lisp_Object item;
7308 if (!INTEGERP (key))
7309 key = w32_parse_hot_key (key);
7311 item = Fmemq (key, w32_grabbed_keys);
7313 if (!NILP (item))
7315 LPARAM lparam;
7317 eassert (CONSP (item));
7318 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
7319 so that it works in a --with-wide-int build as well. */
7320 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
7322 /* Notify input thread about hot-key definition being removed, so
7323 that it takes effect without needing focus switch. */
7324 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7325 (WPARAM) XINT (XCAR (item)), lparam))
7327 MSG msg;
7328 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7330 return Qt;
7332 return Qnil;
7335 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7336 Sw32_registered_hot_keys, 0, 0, 0,
7337 doc: /* Return list of registered hot-key IDs. */)
7338 (void)
7340 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7343 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7344 Sw32_reconstruct_hot_key, 1, 1, 0,
7345 doc: /* Convert hot-key ID to a lisp key combination.
7346 usage: (w32-reconstruct-hot-key ID) */)
7347 (Lisp_Object hotkeyid)
7349 int vk_code, w32_modifiers;
7350 Lisp_Object key;
7352 CHECK_NUMBER (hotkeyid);
7354 vk_code = HOTKEY_VK_CODE (hotkeyid);
7355 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7357 if (vk_code < 256 && lispy_function_keys[vk_code])
7358 key = intern (lispy_function_keys[vk_code]);
7359 else
7360 key = make_number (vk_code);
7362 key = Fcons (key, Qnil);
7363 if (w32_modifiers & MOD_SHIFT)
7364 key = Fcons (Qshift, key);
7365 if (w32_modifiers & MOD_CONTROL)
7366 key = Fcons (Qctrl, key);
7367 if (w32_modifiers & MOD_ALT)
7368 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7369 if (w32_modifiers & MOD_WIN)
7370 key = Fcons (Qhyper, key);
7372 return key;
7375 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7376 Sw32_toggle_lock_key, 1, 2, 0,
7377 doc: /* Toggle the state of the lock key KEY.
7378 KEY can be `capslock', `kp-numlock', or `scroll'.
7379 If the optional parameter NEW-STATE is a number, then the state of KEY
7380 is set to off if the low bit of NEW-STATE is zero, otherwise on.
7381 If NEW-STATE is omitted or nil, the function toggles the state,
7383 Value is the new state of the key, or nil if the function failed
7384 to change the state. */)
7385 (Lisp_Object key, Lisp_Object new_state)
7387 int vk_code;
7388 LPARAM lparam;
7390 if (EQ (key, intern ("capslock")))
7391 vk_code = VK_CAPITAL;
7392 else if (EQ (key, intern ("kp-numlock")))
7393 vk_code = VK_NUMLOCK;
7394 else if (EQ (key, intern ("scroll")))
7395 vk_code = VK_SCROLL;
7396 else
7397 return Qnil;
7399 if (!dwWindowsThreadId)
7400 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7402 if (NILP (new_state))
7403 lparam = -1;
7404 else
7405 lparam = (XUINT (new_state)) & 1;
7406 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7407 (WPARAM) vk_code, lparam))
7409 MSG msg;
7410 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7411 return make_number (msg.wParam);
7413 return Qnil;
7416 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7417 2, 2, 0,
7418 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7420 This is a direct interface to the Windows API FindWindow function. */)
7421 (Lisp_Object class, Lisp_Object name)
7423 HWND hnd;
7425 if (!NILP (class))
7426 CHECK_STRING (class);
7427 if (!NILP (name))
7428 CHECK_STRING (name);
7430 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7431 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7432 if (!hnd)
7433 return Qnil;
7434 return Qt;
7437 DEFUN ("w32-frame-menu-bar-size", Fw32_frame_menu_bar_size, Sw32_frame_menu_bar_size, 0, 1, 0,
7438 doc: /* Return sizes of menu bar on frame FRAME.
7439 The return value is a list of four elements: The current width and
7440 height of FRAME's menu bar in pixels, the height of one menu bar line in
7441 a wrapped menu bar in pixels, and the height of a single line menu bar
7442 in pixels.
7444 If FRAME is omitted or nil, the selected frame is used. */)
7445 (Lisp_Object frame)
7447 struct frame *f = decode_any_frame (frame);
7448 MENUBARINFO menu_bar;
7449 int width, height, single_height, wrapped_height;
7451 block_input ();
7453 single_height = GetSystemMetrics (SM_CYMENU);
7454 wrapped_height = GetSystemMetrics (SM_CYMENUSIZE);
7455 menu_bar.cbSize = sizeof (menu_bar);
7456 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
7457 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
7458 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
7459 width = menu_bar.rcBar.right - menu_bar.rcBar.left;
7460 height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
7462 unblock_input ();
7464 return list4 (make_number (width), make_number (height),
7465 make_number (wrapped_height), make_number (single_height));
7468 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7469 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7470 FRAME must be a live frame and defaults to the selected one.
7472 The boundary rectangle is a list of four elements, specifying the left,
7473 top, right and bottom screen coordinates of FRAME including menu and
7474 title bar and decorations. Optional argument CLIENT non-nil means to
7475 return the boundaries of the client rectangle which excludes menu and
7476 title bar and decorations. */)
7477 (Lisp_Object frame, Lisp_Object client)
7479 struct frame *f = decode_live_frame (frame);
7480 RECT rect;
7482 block_input ();
7484 if (!NILP (client))
7485 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7486 else
7487 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7489 unblock_input ();
7491 return list4 (make_number (rect.left), make_number (rect.top),
7492 make_number (rect.right), make_number (rect.bottom));
7495 DEFUN ("x-frame-geometry", Fx_frame_geometry, Sx_frame_geometry, 0, 1, 0,
7496 doc: /* Return geometric attributes of frame FRAME.
7497 FRAME must be a live frame and defaults to the selected one.
7499 The return value is an association list containing the following
7500 elements (all size values are in pixels).
7502 - `frame-outer-size' is a cons of the outer width and height of FRAME.
7503 The outer size includes the title bar and the external borders as well
7504 as any menu and/or tool bar of frame.
7506 - `border' is a cons of the horizontal and vertical width of FRAME's
7507 external borders.
7509 - `title-bar-height' is the height of the title bar of FRAME.
7511 - `menu-bar-external' if `t' means the menu bar is by default external
7512 (not included in the inner size of FRAME).
7514 - `menu-bar-size' is a cons of the width and height of the menu bar of
7515 FRAME.
7517 - `tool-bar-external' if `t' means the tool bar is by default external
7518 (not included in the inner size of FRAME).
7520 - `tool-bar-side' tells tells on which side the tool bar on FRAME is by
7521 default and can be one of `left', `top', `right' or `bottom'.
7523 - `tool-bar-size' is a cons of the width and height of the tool bar of
7524 FRAME.
7526 - `frame-inner-size' is a cons of the inner width and height of FRAME.
7527 This excludes FRAME's title bar and external border as well as any
7528 external menu and/or tool bar. */)
7529 (Lisp_Object frame)
7531 struct frame *f = decode_live_frame (frame);
7532 Lisp_Object geometry = Qnil;
7533 RECT frame_outer_edges, frame_inner_edges;
7534 MENUBARINFO menu_bar;
7535 int border_width, border_height, title_height;
7536 int single_bar_height, wrapped_bar_height, menu_bar_height;
7537 Lisp_Object fullscreen = Fframe_parameter (frame, Qfullscreen);
7539 block_input ();
7541 /* Outer frame rectangle, including outer borders and title bar. */
7542 GetWindowRect (FRAME_W32_WINDOW (f), &frame_outer_edges);
7543 /* Inner frame rectangle, excluding borders and title bar. */
7544 GetClientRect (FRAME_W32_WINDOW (f), &frame_inner_edges);
7545 /* Outer border. */
7546 border_width = GetSystemMetrics (SM_CXFRAME);
7547 border_height = GetSystemMetrics (SM_CYFRAME);
7548 /* Title bar. */
7549 title_height = GetSystemMetrics (SM_CYCAPTION);
7550 /* Menu bar. */
7551 menu_bar.cbSize = sizeof (menu_bar);
7552 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
7553 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
7554 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
7555 single_bar_height = GetSystemMetrics (SM_CYMENU);
7556 wrapped_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
7557 unblock_input ();
7559 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
7560 /* Fix menu bar height reported by GetMenuBarInfo. */
7561 if (menu_bar_height > single_bar_height)
7562 /* A wrapped menu bar. */
7563 menu_bar_height += single_bar_height - wrapped_bar_height;
7564 else if (menu_bar_height > 0)
7565 /* A single line menu bar. */
7566 menu_bar_height = single_bar_height;
7568 return
7569 listn (CONSTYPE_HEAP, 10,
7570 Fcons (Qframe_position,
7571 Fcons (make_number (frame_outer_edges.left),
7572 make_number (frame_outer_edges.top))),
7573 Fcons (Qframe_outer_size,
7574 Fcons (make_number
7575 (frame_outer_edges.right - frame_outer_edges.left),
7576 make_number
7577 (frame_outer_edges.bottom - frame_outer_edges.top))),
7578 Fcons (Qexternal_border_size,
7579 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
7580 ? Fcons (make_number (0), make_number (0))
7581 : Fcons (make_number (border_width),
7582 make_number (border_height)))),
7583 Fcons (Qtitle_height,
7584 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
7585 ? make_number (0)
7586 : make_number (title_height))),
7587 Fcons (Qmenu_bar_external, Qt),
7588 Fcons (Qmenu_bar_size,
7589 Fcons (make_number
7590 (menu_bar.rcBar.right - menu_bar.rcBar.left),
7591 make_number (menu_bar_height))),
7592 Fcons (Qtool_bar_external, Qnil),
7593 Fcons (Qtool_bar_position, Qtop),
7594 Fcons (Qtool_bar_size,
7595 Fcons (make_number (FRAME_TOOL_BAR_LINES (f)
7596 ? (FRAME_PIXEL_WIDTH (f)
7597 - 2 * FRAME_INTERNAL_BORDER_WIDTH (f))
7598 : 0),
7599 make_number (FRAME_TOOL_BAR_HEIGHT (f)))),
7600 Fcons (Qframe_inner_size,
7601 Fcons (make_number
7602 (frame_inner_edges.right - frame_inner_edges.left),
7603 make_number
7604 (frame_inner_edges.bottom - frame_inner_edges.top))));
7607 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7608 doc: /* Get power status information from Windows system.
7610 The following %-sequences are provided:
7611 %L AC line status (verbose)
7612 %B Battery status (verbose)
7613 %b Battery status, empty means high, `-' means low,
7614 `!' means critical, and `+' means charging
7615 %p Battery load percentage
7616 %s Remaining time (to charge or discharge) in seconds
7617 %m Remaining time (to charge or discharge) in minutes
7618 %h Remaining time (to charge or discharge) in hours
7619 %t Remaining time (to charge or discharge) in the form `h:min' */)
7620 (void)
7622 Lisp_Object status = Qnil;
7624 SYSTEM_POWER_STATUS system_status;
7625 if (GetSystemPowerStatus (&system_status))
7627 Lisp_Object line_status, battery_status, battery_status_symbol;
7628 Lisp_Object load_percentage, seconds, minutes, hours, remain;
7630 long seconds_left = (long) system_status.BatteryLifeTime;
7632 if (system_status.ACLineStatus == 0)
7633 line_status = build_string ("off-line");
7634 else if (system_status.ACLineStatus == 1)
7635 line_status = build_string ("on-line");
7636 else
7637 line_status = build_string ("N/A");
7639 if (system_status.BatteryFlag & 128)
7641 battery_status = build_string ("N/A");
7642 battery_status_symbol = empty_unibyte_string;
7644 else if (system_status.BatteryFlag & 8)
7646 battery_status = build_string ("charging");
7647 battery_status_symbol = build_string ("+");
7648 if (system_status.BatteryFullLifeTime != -1L)
7649 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7651 else if (system_status.BatteryFlag & 4)
7653 battery_status = build_string ("critical");
7654 battery_status_symbol = build_string ("!");
7656 else if (system_status.BatteryFlag & 2)
7658 battery_status = build_string ("low");
7659 battery_status_symbol = build_string ("-");
7661 else if (system_status.BatteryFlag & 1)
7663 battery_status = build_string ("high");
7664 battery_status_symbol = empty_unibyte_string;
7666 else
7668 battery_status = build_string ("medium");
7669 battery_status_symbol = empty_unibyte_string;
7672 if (system_status.BatteryLifePercent > 100)
7673 load_percentage = build_string ("N/A");
7674 else
7676 char buffer[16];
7677 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
7678 load_percentage = build_string (buffer);
7681 if (seconds_left < 0)
7682 seconds = minutes = hours = remain = build_string ("N/A");
7683 else
7685 long m;
7686 float h;
7687 char buffer[16];
7688 snprintf (buffer, 16, "%ld", seconds_left);
7689 seconds = build_string (buffer);
7691 m = seconds_left / 60;
7692 snprintf (buffer, 16, "%ld", m);
7693 minutes = build_string (buffer);
7695 h = seconds_left / 3600.0;
7696 snprintf (buffer, 16, "%3.1f", h);
7697 hours = build_string (buffer);
7699 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
7700 remain = build_string (buffer);
7703 status = listn (CONSTYPE_HEAP, 8,
7704 Fcons (make_number ('L'), line_status),
7705 Fcons (make_number ('B'), battery_status),
7706 Fcons (make_number ('b'), battery_status_symbol),
7707 Fcons (make_number ('p'), load_percentage),
7708 Fcons (make_number ('s'), seconds),
7709 Fcons (make_number ('m'), minutes),
7710 Fcons (make_number ('h'), hours),
7711 Fcons (make_number ('t'), remain));
7713 return status;
7717 #ifdef WINDOWSNT
7718 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
7719 doc: /* Return storage information about the file system FILENAME is on.
7720 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7721 storage of the file system, FREE is the free storage, and AVAIL is the
7722 storage available to a non-superuser. All 3 numbers are in bytes.
7723 If the underlying system call fails, value is nil. */)
7724 (Lisp_Object filename)
7726 Lisp_Object encoded, value;
7728 CHECK_STRING (filename);
7729 filename = Fexpand_file_name (filename, Qnil);
7730 encoded = ENCODE_FILE (filename);
7732 value = Qnil;
7734 /* Determining the required information on Windows turns out, sadly,
7735 to be more involved than one would hope. The original Windows API
7736 call for this will return bogus information on some systems, but we
7737 must dynamically probe for the replacement api, since that was
7738 added rather late on. */
7740 HMODULE hKernel = GetModuleHandle ("kernel32");
7741 BOOL (WINAPI *pfn_GetDiskFreeSpaceExW)
7742 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7743 = GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7744 BOOL (WINAPI *pfn_GetDiskFreeSpaceExA)
7745 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7746 = GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
7747 bool have_pfn_GetDiskFreeSpaceEx =
7748 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
7749 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
7751 /* On Windows, we may need to specify the root directory of the
7752 volume holding FILENAME. */
7753 char rootname[MAX_UTF8_PATH];
7754 wchar_t rootname_w[MAX_PATH];
7755 char rootname_a[MAX_PATH];
7756 char *name = SDATA (encoded);
7757 BOOL result;
7759 /* find the root name of the volume if given */
7760 if (isalpha (name[0]) && name[1] == ':')
7762 rootname[0] = name[0];
7763 rootname[1] = name[1];
7764 rootname[2] = '\\';
7765 rootname[3] = 0;
7767 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7769 char *str = rootname;
7770 int slashes = 4;
7773 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7774 break;
7775 *str++ = *name++;
7777 while ( *name );
7779 *str++ = '\\';
7780 *str = 0;
7783 if (w32_unicode_filenames)
7784 filename_to_utf16 (rootname, rootname_w);
7785 else
7786 filename_to_ansi (rootname, rootname_a);
7788 if (have_pfn_GetDiskFreeSpaceEx)
7790 /* Unsigned large integers cannot be cast to double, so
7791 use signed ones instead. */
7792 LARGE_INTEGER availbytes;
7793 LARGE_INTEGER freebytes;
7794 LARGE_INTEGER totalbytes;
7796 if (w32_unicode_filenames)
7797 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7798 (ULARGE_INTEGER *)&availbytes,
7799 (ULARGE_INTEGER *)&totalbytes,
7800 (ULARGE_INTEGER *)&freebytes);
7801 else
7802 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7803 (ULARGE_INTEGER *)&availbytes,
7804 (ULARGE_INTEGER *)&totalbytes,
7805 (ULARGE_INTEGER *)&freebytes);
7806 if (result)
7807 value = list3 (make_float ((double) totalbytes.QuadPart),
7808 make_float ((double) freebytes.QuadPart),
7809 make_float ((double) availbytes.QuadPart));
7811 else
7813 DWORD sectors_per_cluster;
7814 DWORD bytes_per_sector;
7815 DWORD free_clusters;
7816 DWORD total_clusters;
7818 if (w32_unicode_filenames)
7819 result = GetDiskFreeSpaceW (rootname_w,
7820 &sectors_per_cluster,
7821 &bytes_per_sector,
7822 &free_clusters,
7823 &total_clusters);
7824 else
7825 result = GetDiskFreeSpaceA (rootname_a,
7826 &sectors_per_cluster,
7827 &bytes_per_sector,
7828 &free_clusters,
7829 &total_clusters);
7830 if (result)
7831 value = list3 (make_float ((double) total_clusters
7832 * sectors_per_cluster * bytes_per_sector),
7833 make_float ((double) free_clusters
7834 * sectors_per_cluster * bytes_per_sector),
7835 make_float ((double) free_clusters
7836 * sectors_per_cluster * bytes_per_sector));
7840 return value;
7842 #endif /* WINDOWSNT */
7845 #ifdef WINDOWSNT
7846 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7847 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
7848 (void)
7850 static char pname_buf[256];
7851 int err;
7852 HANDLE hPrn;
7853 PRINTER_INFO_2W *ppi2w = NULL;
7854 PRINTER_INFO_2A *ppi2a = NULL;
7855 DWORD dwNeeded = 0, dwReturned = 0;
7856 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7857 char port_name[MAX_UTF8_PATH];
7859 /* Retrieve the default string from Win.ini (the registry).
7860 * String will be in form "printername,drivername,portname".
7861 * This is the most portable way to get the default printer. */
7862 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7863 return Qnil;
7864 /* printername precedes first "," character */
7865 strtok (pname_buf, ",");
7866 /* We want to know more than the printer name */
7867 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7868 return Qnil;
7869 /* GetPrinterW is not supported by unicows.dll. */
7870 if (w32_unicode_filenames && os_subtype != OS_9X)
7871 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7872 else
7873 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
7874 if (dwNeeded == 0)
7876 ClosePrinter (hPrn);
7877 return Qnil;
7879 /* Call GetPrinter again with big enough memory block. */
7880 if (w32_unicode_filenames && os_subtype != OS_9X)
7882 /* Allocate memory for the PRINTER_INFO_2 struct. */
7883 ppi2w = xmalloc (dwNeeded);
7884 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
7885 ClosePrinter (hPrn);
7886 if (!err)
7888 xfree (ppi2w);
7889 return Qnil;
7892 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7893 && ppi2w->pServerName)
7895 filename_from_utf16 (ppi2w->pServerName, server_name);
7896 filename_from_utf16 (ppi2w->pShareName, share_name);
7898 else
7900 server_name[0] = '\0';
7901 filename_from_utf16 (ppi2w->pPortName, port_name);
7904 else
7906 ppi2a = xmalloc (dwNeeded);
7907 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7908 ClosePrinter (hPrn);
7909 if (!err)
7911 xfree (ppi2a);
7912 return Qnil;
7915 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7916 && ppi2a->pServerName)
7918 filename_from_ansi (ppi2a->pServerName, server_name);
7919 filename_from_ansi (ppi2a->pShareName, share_name);
7921 else
7923 server_name[0] = '\0';
7924 filename_from_ansi (ppi2a->pPortName, port_name);
7928 if (server_name[0])
7930 /* a remote printer */
7931 if (server_name[0] == '\\')
7932 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7933 share_name);
7934 else
7935 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7936 share_name);
7937 pname_buf[sizeof (pname_buf) - 1] = '\0';
7939 else
7941 /* a local printer */
7942 strncpy (pname_buf, port_name, sizeof (pname_buf));
7943 pname_buf[sizeof (pname_buf) - 1] = '\0';
7944 /* `pPortName' can include several ports, delimited by ','.
7945 * we only use the first one. */
7946 strtok (pname_buf, ",");
7949 return DECODE_FILE (build_unibyte_string (pname_buf));
7951 #endif /* WINDOWSNT */
7954 /* Equivalent of strerror for W32 error codes. */
7955 char *
7956 w32_strerror (int error_no)
7958 static char buf[500];
7959 DWORD ret;
7961 if (error_no == 0)
7962 error_no = GetLastError ();
7964 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7965 FORMAT_MESSAGE_IGNORE_INSERTS,
7966 NULL,
7967 error_no,
7968 0, /* choose most suitable language */
7969 buf, sizeof (buf), NULL);
7971 while (ret > 0 && (buf[ret - 1] == '\n' ||
7972 buf[ret - 1] == '\r' ))
7973 --ret;
7974 buf[ret] = '\0';
7975 if (!ret)
7976 sprintf (buf, "w32 error %u", error_no);
7978 return buf;
7981 /* For convenience when debugging. (You cannot call GetLastError
7982 directly from GDB: it will crash, because it uses the __stdcall
7983 calling convention, not the _cdecl convention assumed by GDB.) */
7984 DWORD
7985 w32_last_error (void)
7987 return GetLastError ();
7990 /* Cache information describing the NT system for later use. */
7991 void
7992 cache_system_info (void)
7994 union
7996 struct info
7998 char major;
7999 char minor;
8000 short platform;
8001 } info;
8002 DWORD data;
8003 } version;
8005 /* Cache the module handle of Emacs itself. */
8006 hinst = GetModuleHandle (NULL);
8008 /* Cache the version of the operating system. */
8009 version.data = GetVersion ();
8010 w32_major_version = version.info.major;
8011 w32_minor_version = version.info.minor;
8013 if (version.info.platform & 0x8000)
8014 os_subtype = OS_9X;
8015 else
8016 os_subtype = OS_NT;
8018 /* Cache page size, allocation unit, processor type, etc. */
8019 GetSystemInfo (&sysinfo_cache);
8020 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
8022 /* Cache os info. */
8023 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
8024 GetVersionEx (&osinfo_cache);
8026 w32_build_number = osinfo_cache.dwBuildNumber;
8027 if (os_subtype == OS_9X)
8028 w32_build_number &= 0xffff;
8030 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
8033 #ifdef EMACSDEBUG
8034 void
8035 _DebPrint (const char *fmt, ...)
8037 char buf[1024];
8038 va_list args;
8040 va_start (args, fmt);
8041 vsprintf (buf, fmt, args);
8042 va_end (args);
8043 #if CYGWIN
8044 fprintf (stderr, "%s", buf);
8045 #endif
8046 OutputDebugString (buf);
8048 #endif
8051 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
8053 int cur_state = (GetKeyState (vk_code) & 1);
8055 if (NILP (new_state)
8056 || (NUMBERP (new_state)
8057 && ((XUINT (new_state)) & 1) != cur_state))
8059 #ifdef WINDOWSNT
8060 faked_key = vk_code;
8061 #endif /* WINDOWSNT */
8063 keybd_event ((BYTE) vk_code,
8064 (BYTE) MapVirtualKey (vk_code, 0),
8065 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8066 keybd_event ((BYTE) vk_code,
8067 (BYTE) MapVirtualKey (vk_code, 0),
8068 KEYEVENTF_EXTENDEDKEY | 0, 0);
8069 keybd_event ((BYTE) vk_code,
8070 (BYTE) MapVirtualKey (vk_code, 0),
8071 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8072 cur_state = !cur_state;
8075 return cur_state;
8078 /* Translate console modifiers to emacs modifiers.
8079 German keyboard support (Kai Morgan Zeise 2/18/95). */
8081 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
8083 int retval = 0;
8085 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
8086 pressed, first remove those modifiers. */
8087 if (!NILP (Vw32_recognize_altgr)
8088 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8089 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8090 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
8092 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
8093 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
8095 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8097 retval |= ctrl_modifier;
8098 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8099 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8100 retval |= meta_modifier;
8103 if (mods & LEFT_WIN_PRESSED)
8104 retval |= w32_key_to_modifier (VK_LWIN);
8105 if (mods & RIGHT_WIN_PRESSED)
8106 retval |= w32_key_to_modifier (VK_RWIN);
8107 if (mods & APPS_PRESSED)
8108 retval |= w32_key_to_modifier (VK_APPS);
8109 if (mods & SCROLLLOCK_ON)
8110 retval |= w32_key_to_modifier (VK_SCROLL);
8112 /* Just in case someone wanted the original behavior, make it
8113 optional by setting w32-capslock-is-shiftlock to t. */
8114 if (NILP (Vw32_capslock_is_shiftlock)
8115 /* Keys that should _not_ be affected by CapsLock. */
8116 && ( (key == VK_BACK)
8117 || (key == VK_TAB)
8118 || (key == VK_CLEAR)
8119 || (key == VK_RETURN)
8120 || (key == VK_ESCAPE)
8121 || ((key >= VK_SPACE) && (key <= VK_HELP))
8122 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
8123 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
8126 /* Only consider shift state. */
8127 if ((mods & SHIFT_PRESSED) != 0)
8128 retval |= shift_modifier;
8130 else
8132 /* Ignore CapsLock state if not enabled. */
8133 if (NILP (Vw32_enable_caps_lock))
8134 mods &= ~CAPSLOCK_ON;
8135 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
8136 retval |= shift_modifier;
8139 return retval;
8142 /* The return code indicates key code size. cpID is the codepage to
8143 use for translation to Unicode; -1 means use the current console
8144 input codepage. */
8146 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
8148 unsigned int key_code = event->wVirtualKeyCode;
8149 unsigned int mods = event->dwControlKeyState;
8150 BYTE keystate[256];
8151 static BYTE ansi_code[4];
8152 static int isdead = 0;
8154 if (isdead == 2)
8156 event->uChar.AsciiChar = ansi_code[2];
8157 isdead = 0;
8158 return 1;
8160 if (event->uChar.AsciiChar != 0)
8161 return 1;
8163 memset (keystate, 0, sizeof (keystate));
8164 keystate[key_code] = 0x80;
8165 if (mods & SHIFT_PRESSED)
8166 keystate[VK_SHIFT] = 0x80;
8167 if (mods & CAPSLOCK_ON)
8168 keystate[VK_CAPITAL] = 1;
8169 /* If we recognize right-alt and left-ctrl as AltGr, set the key
8170 states accordingly before invoking ToAscii. */
8171 if (!NILP (Vw32_recognize_altgr)
8172 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
8174 keystate[VK_CONTROL] = 0x80;
8175 keystate[VK_LCONTROL] = 0x80;
8176 keystate[VK_MENU] = 0x80;
8177 keystate[VK_RMENU] = 0x80;
8180 #if 0
8181 /* Because of an OS bug, ToAscii corrupts the stack when called to
8182 convert a dead key in console mode on NT4. Unfortunately, trying
8183 to check for dead keys using MapVirtualKey doesn't work either -
8184 these functions apparently use internal information about keyboard
8185 layout which doesn't get properly updated in console programs when
8186 changing layout (though apparently it gets partly updated,
8187 otherwise ToAscii wouldn't crash). */
8188 if (is_dead_key (event->wVirtualKeyCode))
8189 return 0;
8190 #endif
8192 /* On NT, call ToUnicode instead and then convert to the current
8193 console input codepage. */
8194 if (os_subtype == OS_NT)
8196 WCHAR buf[128];
8198 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
8199 keystate, buf, 128, 0);
8200 if (isdead > 0)
8202 /* When we are called from the GUI message processing code,
8203 we are passed the current keyboard codepage, a positive
8204 number, to use below. */
8205 if (cpId == -1)
8206 cpId = GetConsoleCP ();
8208 event->uChar.UnicodeChar = buf[isdead - 1];
8209 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8210 ansi_code, 4, NULL, NULL);
8212 else
8213 isdead = 0;
8215 else
8217 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8218 keystate, (LPWORD) ansi_code, 0);
8221 if (isdead == 0)
8222 return 0;
8223 event->uChar.AsciiChar = ansi_code[0];
8224 return isdead;
8228 void
8229 w32_sys_ring_bell (struct frame *f)
8231 if (sound_type == 0xFFFFFFFF)
8233 Beep (666, 100);
8235 else if (sound_type == MB_EMACS_SILENT)
8237 /* Do nothing. */
8239 else
8240 MessageBeep (sound_type);
8244 /***********************************************************************
8245 Initialization
8246 ***********************************************************************/
8248 /* Keep this list in the same order as frame_parms in frame.c.
8249 Use 0 for unsupported frame parameters. */
8251 frame_parm_handler w32_frame_parm_handlers[] =
8253 x_set_autoraise,
8254 x_set_autolower,
8255 x_set_background_color,
8256 x_set_border_color,
8257 x_set_border_width,
8258 x_set_cursor_color,
8259 x_set_cursor_type,
8260 x_set_font,
8261 x_set_foreground_color,
8262 x_set_icon_name,
8263 x_set_icon_type,
8264 x_set_internal_border_width,
8265 x_set_right_divider_width,
8266 x_set_bottom_divider_width,
8267 x_set_menu_bar_lines,
8268 x_set_mouse_color,
8269 x_explicitly_set_name,
8270 x_set_scroll_bar_width,
8271 x_set_scroll_bar_height,
8272 x_set_title,
8273 x_set_unsplittable,
8274 x_set_vertical_scroll_bars,
8275 x_set_horizontal_scroll_bars,
8276 x_set_visibility,
8277 x_set_tool_bar_lines,
8278 0, /* x_set_scroll_bar_foreground, */
8279 0, /* x_set_scroll_bar_background, */
8280 x_set_screen_gamma,
8281 x_set_line_spacing,
8282 x_set_left_fringe,
8283 x_set_right_fringe,
8284 0, /* x_set_wait_for_wm, */
8285 x_set_fullscreen,
8286 x_set_font_backend,
8287 x_set_alpha,
8288 0, /* x_set_sticky */
8289 0, /* x_set_tool_bar_position */
8292 void
8293 syms_of_w32fns (void)
8295 globals_of_w32fns ();
8296 track_mouse_window = NULL;
8298 w32_visible_system_caret_hwnd = NULL;
8300 DEFSYM (Qundefined_color, "undefined-color");
8301 DEFSYM (Qcancel_timer, "cancel-timer");
8302 DEFSYM (Qhyper, "hyper");
8303 DEFSYM (Qsuper, "super");
8304 DEFSYM (Qmeta, "meta");
8305 DEFSYM (Qalt, "alt");
8306 DEFSYM (Qctrl, "ctrl");
8307 DEFSYM (Qcontrol, "control");
8308 DEFSYM (Qshift, "shift");
8309 DEFSYM (Qfont_param, "font-parameter");
8310 DEFSYM (Qgeometry, "geometry");
8311 DEFSYM (Qworkarea, "workarea");
8312 DEFSYM (Qmm_size, "mm-size");
8313 DEFSYM (Qframes, "frames");
8315 Fput (Qundefined_color, Qerror_conditions,
8316 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8317 Fput (Qundefined_color, Qerror_message,
8318 build_pure_c_string ("Undefined color"));
8320 staticpro (&w32_grabbed_keys);
8321 w32_grabbed_keys = Qnil;
8323 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8324 doc: /* An array of color name mappings for Windows. */);
8325 Vw32_color_map = Qnil;
8327 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8328 doc: /* Non-nil if Alt key presses are passed on to Windows.
8329 When non-nil, for example, Alt pressed and released and then space will
8330 open the System menu. When nil, Emacs processes the Alt key events, and
8331 then silently swallows them. */);
8332 Vw32_pass_alt_to_system = Qnil;
8334 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8335 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8336 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8337 Vw32_alt_is_meta = Qt;
8339 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8340 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8341 w32_quit_key = 0;
8343 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8344 Vw32_pass_lwindow_to_system,
8345 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8347 When non-nil, the Start menu is opened by tapping the key.
8348 If you set this to nil, the left \"Windows\" key is processed by Emacs
8349 according to the value of `w32-lwindow-modifier', which see.
8351 Note that some combinations of the left \"Windows\" key with other keys are
8352 caught by Windows at low level, and so binding them in Emacs will have no
8353 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8354 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8355 the doc string of `w32-phantom-key-code'. */);
8356 Vw32_pass_lwindow_to_system = Qt;
8358 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8359 Vw32_pass_rwindow_to_system,
8360 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8362 When non-nil, the Start menu is opened by tapping the key.
8363 If you set this to nil, the right \"Windows\" key is processed by Emacs
8364 according to the value of `w32-rwindow-modifier', which see.
8366 Note that some combinations of the right \"Windows\" key with other keys are
8367 caught by Windows at low level, and so binding them in Emacs will have no
8368 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8369 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8370 the doc string of `w32-phantom-key-code'. */);
8371 Vw32_pass_rwindow_to_system = Qt;
8373 DEFVAR_LISP ("w32-phantom-key-code",
8374 Vw32_phantom_key_code,
8375 doc: /* Virtual key code used to generate \"phantom\" key presses.
8376 Value is a number between 0 and 255.
8378 Phantom key presses are generated in order to stop the system from
8379 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8380 `w32-pass-rwindow-to-system' is nil. */);
8381 /* Although 255 is technically not a valid key code, it works and
8382 means that this hack won't interfere with any real key code. */
8383 XSETINT (Vw32_phantom_key_code, 255);
8385 DEFVAR_LISP ("w32-enable-num-lock",
8386 Vw32_enable_num_lock,
8387 doc: /* If non-nil, the Num Lock key acts normally.
8388 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8389 Vw32_enable_num_lock = Qt;
8391 DEFVAR_LISP ("w32-enable-caps-lock",
8392 Vw32_enable_caps_lock,
8393 doc: /* If non-nil, the Caps Lock key acts normally.
8394 Set to nil to handle Caps Lock as the `capslock' key. */);
8395 Vw32_enable_caps_lock = Qt;
8397 DEFVAR_LISP ("w32-scroll-lock-modifier",
8398 Vw32_scroll_lock_modifier,
8399 doc: /* Modifier to use for the Scroll Lock ON state.
8400 The value can be hyper, super, meta, alt, control or shift for the
8401 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8402 Any other value will cause the Scroll Lock key to be ignored. */);
8403 Vw32_scroll_lock_modifier = Qnil;
8405 DEFVAR_LISP ("w32-lwindow-modifier",
8406 Vw32_lwindow_modifier,
8407 doc: /* Modifier to use for the left \"Windows\" key.
8408 The value can be hyper, super, meta, alt, control or shift for the
8409 respective modifier, or nil to appear as the `lwindow' key.
8410 Any other value will cause the key to be ignored. */);
8411 Vw32_lwindow_modifier = Qnil;
8413 DEFVAR_LISP ("w32-rwindow-modifier",
8414 Vw32_rwindow_modifier,
8415 doc: /* Modifier to use for the right \"Windows\" key.
8416 The value can be hyper, super, meta, alt, control or shift for the
8417 respective modifier, or nil to appear as the `rwindow' key.
8418 Any other value will cause the key to be ignored. */);
8419 Vw32_rwindow_modifier = Qnil;
8421 DEFVAR_LISP ("w32-apps-modifier",
8422 Vw32_apps_modifier,
8423 doc: /* Modifier to use for the \"Apps\" key.
8424 The value can be hyper, super, meta, alt, control or shift for the
8425 respective modifier, or nil to appear as the `apps' key.
8426 Any other value will cause the key to be ignored. */);
8427 Vw32_apps_modifier = Qnil;
8429 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
8430 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8431 w32_enable_synthesized_fonts = 0;
8433 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
8434 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8435 Vw32_enable_palette = Qt;
8437 DEFVAR_INT ("w32-mouse-button-tolerance",
8438 w32_mouse_button_tolerance,
8439 doc: /* Analogue of double click interval for faking middle mouse events.
8440 The value is the minimum time in milliseconds that must elapse between
8441 left and right button down events before they are considered distinct events.
8442 If both mouse buttons are depressed within this interval, a middle mouse
8443 button down event is generated instead. */);
8444 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8446 DEFVAR_INT ("w32-mouse-move-interval",
8447 w32_mouse_move_interval,
8448 doc: /* Minimum interval between mouse move events.
8449 The value is the minimum time in milliseconds that must elapse between
8450 successive mouse move (or scroll bar drag) events before they are
8451 reported as lisp events. */);
8452 w32_mouse_move_interval = 0;
8454 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8455 w32_pass_extra_mouse_buttons_to_system,
8456 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8457 Recent versions of Windows support mice with up to five buttons.
8458 Since most applications don't support these extra buttons, most mouse
8459 drivers will allow you to map them to functions at the system level.
8460 If this variable is non-nil, Emacs will pass them on, allowing the
8461 system to handle them. */);
8462 w32_pass_extra_mouse_buttons_to_system = 0;
8464 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8465 w32_pass_multimedia_buttons_to_system,
8466 doc: /* If non-nil, media buttons are passed to Windows.
8467 Some modern keyboards contain buttons for controlling media players, web
8468 browsers and other applications. Generally these buttons are handled on a
8469 system wide basis, but by setting this to nil they are made available
8470 to Emacs for binding. Depending on your keyboard, additional keys that
8471 may be available are:
8473 browser-back, browser-forward, browser-refresh, browser-stop,
8474 browser-search, browser-favorites, browser-home,
8475 mail, mail-reply, mail-forward, mail-send,
8476 app-1, app-2,
8477 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8478 spell-check, correction-list, toggle-dictate-command,
8479 media-next, media-previous, media-stop, media-play-pause, media-select,
8480 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8481 media-channel-up, media-channel-down,
8482 volume-mute, volume-up, volume-down,
8483 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8484 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8485 w32_pass_multimedia_buttons_to_system = 1;
8487 #if 0 /* TODO: Mouse cursor customization. */
8488 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
8489 doc: /* The shape of the pointer when over text.
8490 Changing the value does not affect existing frames
8491 unless you set the mouse color. */);
8492 Vx_pointer_shape = Qnil;
8494 Vx_nontext_pointer_shape = Qnil;
8496 Vx_mode_pointer_shape = Qnil;
8498 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
8499 doc: /* The shape of the pointer when Emacs is busy.
8500 This variable takes effect when you create a new frame
8501 or when you set the mouse color. */);
8502 Vx_hourglass_pointer_shape = Qnil;
8504 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8505 Vx_sensitive_text_pointer_shape,
8506 doc: /* The shape of the pointer when over mouse-sensitive text.
8507 This variable takes effect when you create a new frame
8508 or when you set the mouse color. */);
8509 Vx_sensitive_text_pointer_shape = Qnil;
8511 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8512 Vx_window_horizontal_drag_shape,
8513 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8514 This variable takes effect when you create a new frame
8515 or when you set the mouse color. */);
8516 Vx_window_horizontal_drag_shape = Qnil;
8518 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8519 Vx_window_vertical_drag_shape,
8520 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8521 This variable takes effect when you create a new frame
8522 or when you set the mouse color. */);
8523 Vx_window_vertical_drag_shape = Qnil;
8524 #endif
8526 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
8527 doc: /* A string indicating the foreground color of the cursor box. */);
8528 Vx_cursor_fore_pixel = Qnil;
8530 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
8531 doc: /* Maximum size for tooltips.
8532 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8533 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8535 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
8536 doc: /* Non-nil if no window manager is in use.
8537 Emacs doesn't try to figure this out; this is always nil
8538 unless you set it to something else. */);
8539 /* We don't have any way to find this out, so set it to nil
8540 and maybe the user would like to set it to t. */
8541 Vx_no_window_manager = Qnil;
8543 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8544 Vx_pixel_size_width_font_regexp,
8545 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8547 Since Emacs gets width of a font matching with this regexp from
8548 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8549 such a font. This is especially effective for such large fonts as
8550 Chinese, Japanese, and Korean. */);
8551 Vx_pixel_size_width_font_regexp = Qnil;
8553 DEFVAR_LISP ("w32-bdf-filename-alist",
8554 Vw32_bdf_filename_alist,
8555 doc: /* List of bdf fonts and their corresponding filenames. */);
8556 Vw32_bdf_filename_alist = Qnil;
8558 DEFVAR_BOOL ("w32-strict-fontnames",
8559 w32_strict_fontnames,
8560 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8561 Default is nil, which allows old fontnames that are not XLFD compliant,
8562 and allows third-party CJK display to work by specifying false charset
8563 fields to trick Emacs into translating to Big5, SJIS etc.
8564 Setting this to t will prevent wrong fonts being selected when
8565 fontsets are automatically created. */);
8566 w32_strict_fontnames = 0;
8568 DEFVAR_BOOL ("w32-strict-painting",
8569 w32_strict_painting,
8570 doc: /* Non-nil means use strict rules for repainting frames.
8571 Set this to nil to get the old behavior for repainting; this should
8572 only be necessary if the default setting causes problems. */);
8573 w32_strict_painting = 1;
8575 #if 0 /* TODO: Port to W32 */
8576 defsubr (&Sx_change_window_property);
8577 defsubr (&Sx_delete_window_property);
8578 defsubr (&Sx_window_property);
8579 #endif
8580 defsubr (&Sxw_display_color_p);
8581 defsubr (&Sx_display_grayscale_p);
8582 defsubr (&Sxw_color_defined_p);
8583 defsubr (&Sxw_color_values);
8584 defsubr (&Sx_server_max_request_size);
8585 defsubr (&Sx_server_vendor);
8586 defsubr (&Sx_server_version);
8587 defsubr (&Sx_display_pixel_width);
8588 defsubr (&Sx_display_pixel_height);
8589 defsubr (&Sx_display_mm_width);
8590 defsubr (&Sx_display_mm_height);
8591 defsubr (&Sx_display_screens);
8592 defsubr (&Sx_display_planes);
8593 defsubr (&Sx_display_color_cells);
8594 defsubr (&Sx_display_visual_class);
8595 defsubr (&Sx_display_backing_store);
8596 defsubr (&Sx_display_save_under);
8597 defsubr (&Sx_create_frame);
8598 defsubr (&Sx_open_connection);
8599 defsubr (&Sx_close_connection);
8600 defsubr (&Sx_display_list);
8601 defsubr (&Sx_frame_geometry);
8602 defsubr (&Sx_synchronize);
8604 /* W32 specific functions */
8606 defsubr (&Sw32_define_rgb_color);
8607 defsubr (&Sw32_default_color_map);
8608 defsubr (&Sw32_display_monitor_attributes_list);
8609 defsubr (&Sw32_send_sys_command);
8610 defsubr (&Sw32_shell_execute);
8611 defsubr (&Sw32_register_hot_key);
8612 defsubr (&Sw32_unregister_hot_key);
8613 defsubr (&Sw32_registered_hot_keys);
8614 defsubr (&Sw32_reconstruct_hot_key);
8615 defsubr (&Sw32_toggle_lock_key);
8616 defsubr (&Sw32_window_exists_p);
8617 defsubr (&Sw32_frame_rect);
8618 defsubr (&Sw32_frame_menu_bar_size);
8619 defsubr (&Sw32_battery_status);
8621 #ifdef WINDOWSNT
8622 defsubr (&Sfile_system_info);
8623 defsubr (&Sdefault_printer_name);
8624 #endif
8626 defsubr (&Sset_message_beep);
8627 defsubr (&Sx_show_tip);
8628 defsubr (&Sx_hide_tip);
8629 tip_timer = Qnil;
8630 staticpro (&tip_timer);
8631 tip_frame = Qnil;
8632 staticpro (&tip_frame);
8634 last_show_tip_args = Qnil;
8635 staticpro (&last_show_tip_args);
8637 defsubr (&Sx_file_dialog);
8638 #ifdef WINDOWSNT
8639 defsubr (&Ssystem_move_file_to_trash);
8640 #endif
8645 /* Crashing and reporting backtrace. */
8647 #ifndef CYGWIN
8648 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8649 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8650 #endif
8651 static DWORD except_code;
8652 static PVOID except_addr;
8654 #ifndef CYGWIN
8655 /* This handler records the exception code and the address where it
8656 was triggered so that this info could be included in the backtrace.
8657 Without that, the backtrace in some cases has no information
8658 whatsoever about the offending code, and looks as if the top-level
8659 exception handler in the MinGW startup code di the one that
8660 crashed. */
8661 static LONG CALLBACK
8662 my_exception_handler (EXCEPTION_POINTERS * exception_data)
8664 except_code = exception_data->ExceptionRecord->ExceptionCode;
8665 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8667 if (prev_exception_handler)
8668 return prev_exception_handler (exception_data);
8669 return EXCEPTION_EXECUTE_HANDLER;
8671 #endif
8673 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8674 PULONG);
8676 #define BACKTRACE_LIMIT_MAX 62
8679 w32_backtrace (void **buffer, int limit)
8681 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8682 HMODULE hm_kernel32 = NULL;
8684 if (!s_pfn_CaptureStackBackTrace)
8686 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8687 s_pfn_CaptureStackBackTrace =
8688 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8689 "RtlCaptureStackBackTrace");
8691 if (s_pfn_CaptureStackBackTrace)
8692 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8693 buffer, NULL);
8694 return 0;
8697 void
8698 emacs_abort (void)
8700 int button;
8701 button = MessageBox (NULL,
8702 "A fatal error has occurred!\n\n"
8703 "Would you like to attach a debugger?\n\n"
8704 "Select:\n"
8705 "YES -- to debug Emacs, or\n"
8706 "NO -- to abort Emacs and produce a backtrace\n"
8707 " (emacs_backtrace.txt in current directory)."
8708 #if __GNUC__
8709 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8710 "\"continue\" inside GDB before clicking YES.)"
8711 #endif
8712 , "Emacs Abort Dialog",
8713 MB_ICONEXCLAMATION | MB_TASKMODAL
8714 | MB_SETFOREGROUND | MB_YESNO);
8715 switch (button)
8717 case IDYES:
8718 DebugBreak ();
8719 exit (2); /* tell the compiler we will never return */
8720 case IDNO:
8721 default:
8723 void *stack[BACKTRACE_LIMIT_MAX + 1];
8724 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8726 if (i)
8728 int errfile_fd = -1;
8729 int j;
8730 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
8731 /* The type below should really be 'void *', but
8732 INT_BUFSIZE_BOUND cannot handle that without
8733 triggering compiler warnings (under certain
8734 pedantic warning switches), it wants an
8735 integer type. */
8736 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
8737 #ifdef CYGWIN
8738 int stderr_fd = 2;
8739 #else
8740 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
8741 int stderr_fd = -1;
8743 if (errout && errout != INVALID_HANDLE_VALUE)
8744 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
8745 #endif
8747 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8748 but not on Windows 7. addr2line doesn't mind a missing
8749 "0x", but will be confused by an extra one. */
8750 if (except_addr)
8751 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8752 except_code, except_addr);
8753 if (stderr_fd >= 0)
8755 if (except_addr)
8756 write (stderr_fd, buf, strlen (buf));
8757 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8759 #ifdef CYGWIN
8760 #define _open open
8761 #endif
8762 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8763 if (errfile_fd >= 0)
8765 lseek (errfile_fd, 0L, SEEK_END);
8766 if (except_addr)
8767 write (errfile_fd, buf, strlen (buf));
8768 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8771 for (j = 0; j < i; j++)
8773 /* stack[] gives the return addresses, whereas we want
8774 the address of the call, so decrease each address
8775 by approximate size of 1 CALL instruction. */
8776 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
8777 if (stderr_fd >= 0)
8778 write (stderr_fd, buf, strlen (buf));
8779 if (errfile_fd >= 0)
8780 write (errfile_fd, buf, strlen (buf));
8782 if (i == BACKTRACE_LIMIT_MAX)
8784 if (stderr_fd >= 0)
8785 write (stderr_fd, "...\r\n", 5);
8786 if (errfile_fd >= 0)
8787 write (errfile_fd, "...\r\n", 5);
8789 if (errfile_fd >= 0)
8790 close (errfile_fd);
8792 abort ();
8793 break;
8800 /* Initialization. */
8803 globals_of_w32fns is used to initialize those global variables that
8804 must always be initialized on startup even when the global variable
8805 initialized is non zero (see the function main in emacs.c).
8806 globals_of_w32fns is called from syms_of_w32fns when the global
8807 variable initialized is 0 and directly from main when initialized
8808 is non zero.
8810 void
8811 globals_of_w32fns (void)
8813 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8815 TrackMouseEvent not available in all versions of Windows, so must load
8816 it dynamically. Do it once, here, instead of every time it is used.
8818 track_mouse_event_fn = (TrackMouseEvent_Proc)
8819 GetProcAddress (user32_lib, "TrackMouseEvent");
8821 monitor_from_point_fn = (MonitorFromPoint_Proc)
8822 GetProcAddress (user32_lib, "MonitorFromPoint");
8823 get_monitor_info_fn = (GetMonitorInfo_Proc)
8824 GetProcAddress (user32_lib, "GetMonitorInfoA");
8825 monitor_from_window_fn = (MonitorFromWindow_Proc)
8826 GetProcAddress (user32_lib, "MonitorFromWindow");
8827 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8828 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8831 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8832 get_composition_string_fn = (ImmGetCompositionString_Proc)
8833 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8834 get_ime_context_fn = (ImmGetContext_Proc)
8835 GetProcAddress (imm32_lib, "ImmGetContext");
8836 release_ime_context_fn = (ImmReleaseContext_Proc)
8837 GetProcAddress (imm32_lib, "ImmReleaseContext");
8838 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8839 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8842 except_code = 0;
8843 except_addr = 0;
8844 #ifndef CYGWIN
8845 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8846 #endif
8848 DEFVAR_INT ("w32-ansi-code-page",
8849 w32_ansi_code_page,
8850 doc: /* The ANSI code page used by the system. */);
8851 w32_ansi_code_page = GetACP ();
8853 if (os_subtype == OS_NT)
8854 w32_unicode_gui = 1;
8855 else
8856 w32_unicode_gui = 0;
8858 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8859 InitCommonControls ();
8861 syms_of_w32uniscribe ();
8864 #ifdef NTGUI_UNICODE
8866 Lisp_Object
8867 ntgui_encode_system (Lisp_Object str)
8869 Lisp_Object encoded;
8870 to_unicode (str, &encoded);
8871 return encoded;
8874 #endif /* NTGUI_UNICODE */