Implement native scrolling of the webkit xwidget
[emacs.git] / src / w32fns.c
blob2dd92ff8a3acc8f04951b29d2dfeb9f145e42d03
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, int alloc)
1138 register Lisp_Object tem;
1139 COLORREF w32_color_ref;
1141 tem = x_to_w32_color (color);
1143 if (!NILP (tem))
1145 if (f)
1147 /* Apply gamma correction. */
1148 w32_color_ref = XUINT (tem);
1149 gamma_correct (f, &w32_color_ref);
1150 XSETINT (tem, w32_color_ref);
1153 /* Map this color to the palette if it is enabled. */
1154 if (!NILP (Vw32_enable_palette))
1156 struct w32_palette_entry * entry =
1157 one_w32_display_info.color_list;
1158 struct w32_palette_entry ** prev =
1159 &one_w32_display_info.color_list;
1161 /* check if color is already mapped */
1162 while (entry)
1164 if (W32_COLOR (entry->entry) == XUINT (tem))
1165 break;
1166 prev = &entry->next;
1167 entry = entry->next;
1170 if (entry == NULL && alloc)
1172 /* not already mapped, so add to list */
1173 entry = xmalloc (sizeof (struct w32_palette_entry));
1174 SET_W32_COLOR (entry->entry, XUINT (tem));
1175 entry->next = NULL;
1176 *prev = entry;
1177 one_w32_display_info.num_colors++;
1179 /* set flag that palette must be regenerated */
1180 one_w32_display_info.regen_palette = TRUE;
1183 /* Ensure COLORREF value is snapped to nearest color in (default)
1184 palette by simulating the PALETTERGB macro. This works whether
1185 or not the display device has a palette. */
1186 w32_color_ref = XUINT (tem) | 0x2000000;
1188 color_def->pixel = w32_color_ref;
1189 color_def->red = GetRValue (w32_color_ref) * 256;
1190 color_def->green = GetGValue (w32_color_ref) * 256;
1191 color_def->blue = GetBValue (w32_color_ref) * 256;
1193 return 1;
1195 else
1197 return 0;
1201 /* Given a string ARG naming a color, compute a pixel value from it
1202 suitable for screen F.
1203 If F is not a color screen, return DEF (default) regardless of what
1204 ARG says. */
1207 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1209 XColor cdef;
1211 CHECK_STRING (arg);
1213 if (strcmp (SDATA (arg), "black") == 0)
1214 return BLACK_PIX_DEFAULT (f);
1215 else if (strcmp (SDATA (arg), "white") == 0)
1216 return WHITE_PIX_DEFAULT (f);
1218 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1219 return def;
1221 /* w32_defined_color is responsible for coping with failures
1222 by looking for a near-miss. */
1223 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1224 return cdef.pixel;
1226 /* defined_color failed; return an ultimate default. */
1227 return def;
1232 /* Functions called only from `x_set_frame_param'
1233 to set individual parameters.
1235 If FRAME_W32_WINDOW (f) is 0,
1236 the frame is being created and its window does not exist yet.
1237 In that case, just record the parameter's new value
1238 in the standard place; do not attempt to change the window. */
1240 void
1241 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1243 struct w32_output *x = f->output_data.w32;
1244 PIX_TYPE fg, old_fg;
1246 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1247 old_fg = FRAME_FOREGROUND_PIXEL (f);
1248 FRAME_FOREGROUND_PIXEL (f) = fg;
1250 if (FRAME_W32_WINDOW (f) != 0)
1252 if (x->cursor_pixel == old_fg)
1254 x->cursor_pixel = fg;
1255 x->cursor_gc->background = fg;
1258 update_face_from_frame_parameter (f, Qforeground_color, arg);
1259 if (FRAME_VISIBLE_P (f))
1260 redraw_frame (f);
1264 void
1265 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1267 FRAME_BACKGROUND_PIXEL (f)
1268 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1270 if (FRAME_W32_WINDOW (f) != 0)
1272 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1273 FRAME_BACKGROUND_PIXEL (f));
1275 update_face_from_frame_parameter (f, Qbackground_color, arg);
1277 if (FRAME_VISIBLE_P (f))
1278 redraw_frame (f);
1282 void
1283 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1285 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1286 int count;
1287 int mask_color;
1289 if (!EQ (Qnil, arg))
1290 f->output_data.w32->mouse_pixel
1291 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1292 mask_color = FRAME_BACKGROUND_PIXEL (f);
1294 /* Don't let pointers be invisible. */
1295 if (mask_color == f->output_data.w32->mouse_pixel
1296 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1297 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1299 #if 0 /* TODO : Mouse cursor customization. */
1300 block_input ();
1302 /* It's not okay to crash if the user selects a screwy cursor. */
1303 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1305 if (!EQ (Qnil, Vx_pointer_shape))
1307 CHECK_NUMBER (Vx_pointer_shape);
1308 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1310 else
1311 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1312 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1314 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1316 CHECK_NUMBER (Vx_nontext_pointer_shape);
1317 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1318 XINT (Vx_nontext_pointer_shape));
1320 else
1321 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1322 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1324 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1326 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1327 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1328 XINT (Vx_hourglass_pointer_shape));
1330 else
1331 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1332 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1334 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1335 if (!EQ (Qnil, Vx_mode_pointer_shape))
1337 CHECK_NUMBER (Vx_mode_pointer_shape);
1338 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1339 XINT (Vx_mode_pointer_shape));
1341 else
1342 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1343 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1345 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1347 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1348 hand_cursor
1349 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1350 XINT (Vx_sensitive_text_pointer_shape));
1352 else
1353 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1355 if (!NILP (Vx_window_horizontal_drag_shape))
1357 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1358 horizontal_drag_cursor
1359 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1360 XINT (Vx_window_horizontal_drag_shape));
1362 else
1363 horizontal_drag_cursor
1364 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_h_double_arrow);
1366 if (!NILP (Vx_window_vertical_drag_shape))
1368 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1369 vertical_drag_cursor
1370 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1371 XINT (Vx_window_vertical_drag_shape));
1373 else
1374 vertical_drag_cursor
1375 = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_sb_v_double_arrow);
1377 /* Check and report errors with the above calls. */
1378 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1379 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1382 XColor fore_color, back_color;
1384 fore_color.pixel = f->output_data.w32->mouse_pixel;
1385 back_color.pixel = mask_color;
1386 XQueryColor (FRAME_W32_DISPLAY (f),
1387 DefaultColormap (FRAME_W32_DISPLAY (f),
1388 DefaultScreen (FRAME_W32_DISPLAY (f))),
1389 &fore_color);
1390 XQueryColor (FRAME_W32_DISPLAY (f),
1391 DefaultColormap (FRAME_W32_DISPLAY (f),
1392 DefaultScreen (FRAME_W32_DISPLAY (f))),
1393 &back_color);
1394 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1395 &fore_color, &back_color);
1396 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1397 &fore_color, &back_color);
1398 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1399 &fore_color, &back_color);
1400 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1401 &fore_color, &back_color);
1402 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1403 &fore_color, &back_color);
1406 if (FRAME_W32_WINDOW (f) != 0)
1407 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1409 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1410 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1411 f->output_data.w32->text_cursor = cursor;
1413 if (nontext_cursor != f->output_data.w32->nontext_cursor
1414 && f->output_data.w32->nontext_cursor != 0)
1415 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1416 f->output_data.w32->nontext_cursor = nontext_cursor;
1418 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1419 && f->output_data.w32->hourglass_cursor != 0)
1420 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1421 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1423 if (mode_cursor != f->output_data.w32->modeline_cursor
1424 && f->output_data.w32->modeline_cursor != 0)
1425 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1426 f->output_data.w32->modeline_cursor = mode_cursor;
1428 if (hand_cursor != f->output_data.w32->hand_cursor
1429 && f->output_data.w32->hand_cursor != 0)
1430 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1431 f->output_data.w32->hand_cursor = hand_cursor;
1433 XFlush (FRAME_W32_DISPLAY (f));
1434 unblock_input ();
1436 update_face_from_frame_parameter (f, Qmouse_color, arg);
1437 #endif /* TODO */
1440 void
1441 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1443 unsigned long fore_pixel, pixel;
1445 if (!NILP (Vx_cursor_fore_pixel))
1446 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1447 WHITE_PIX_DEFAULT (f));
1448 else
1449 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1451 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1453 /* Make sure that the cursor color differs from the background color. */
1454 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1456 pixel = f->output_data.w32->mouse_pixel;
1457 if (pixel == fore_pixel)
1458 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1461 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1462 f->output_data.w32->cursor_pixel = pixel;
1464 if (FRAME_W32_WINDOW (f) != 0)
1466 block_input ();
1467 /* Update frame's cursor_gc. */
1468 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1469 f->output_data.w32->cursor_gc->background = pixel;
1471 unblock_input ();
1473 if (FRAME_VISIBLE_P (f))
1475 x_update_cursor (f, 0);
1476 x_update_cursor (f, 1);
1480 update_face_from_frame_parameter (f, Qcursor_color, arg);
1483 /* Set the border-color of frame F to pixel value PIX.
1484 Note that this does not fully take effect if done before
1485 F has a window. */
1487 void
1488 x_set_border_pixel (struct frame *f, int pix)
1491 f->output_data.w32->border_pixel = pix;
1493 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1495 if (FRAME_VISIBLE_P (f))
1496 redraw_frame (f);
1500 /* Set the border-color of frame F to value described by ARG.
1501 ARG can be a string naming a color.
1502 The border-color is used for the border that is drawn by the server.
1503 Note that this does not fully take effect if done before
1504 F has a window; it must be redone when the window is created. */
1506 void
1507 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1509 int pix;
1511 CHECK_STRING (arg);
1512 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1513 x_set_border_pixel (f, pix);
1514 update_face_from_frame_parameter (f, Qborder_color, arg);
1518 void
1519 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1521 set_frame_cursor_types (f, arg);
1524 void
1525 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1527 int result;
1529 if (NILP (arg) && NILP (oldval))
1530 return;
1532 if (STRINGP (arg) && STRINGP (oldval)
1533 && EQ (Fstring_equal (oldval, arg), Qt))
1534 return;
1536 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1537 return;
1539 block_input ();
1541 result = x_bitmap_icon (f, arg);
1542 if (result)
1544 unblock_input ();
1545 error ("No icon window available");
1548 unblock_input ();
1551 void
1552 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1554 if (STRINGP (arg))
1556 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1557 return;
1559 else if (!NILP (arg) || NILP (oldval))
1560 return;
1562 fset_icon_name (f, arg);
1564 #if 0
1565 if (f->output_data.w32->icon_bitmap != 0)
1566 return;
1568 block_input ();
1570 result = x_text_icon (f,
1571 SSDATA ((!NILP (f->icon_name)
1572 ? f->icon_name
1573 : !NILP (f->title)
1574 ? f->title
1575 : f->name)));
1577 if (result)
1579 unblock_input ();
1580 error ("No icon window available");
1583 /* If the window was unmapped (and its icon was mapped),
1584 the new icon is not mapped, so map the window in its stead. */
1585 if (FRAME_VISIBLE_P (f))
1587 #ifdef USE_X_TOOLKIT
1588 XtPopup (f->output_data.w32->widget, XtGrabNone);
1589 #endif
1590 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1593 XFlush (FRAME_W32_DISPLAY (f));
1594 unblock_input ();
1595 #endif
1598 void
1599 x_clear_under_internal_border (struct frame *f)
1601 int border = FRAME_INTERNAL_BORDER_WIDTH (f);
1603 /* Clear border if it's larger than before. */
1604 if (border != 0)
1606 HDC hdc = get_frame_dc (f);
1607 int width = FRAME_PIXEL_WIDTH (f);
1608 int height = FRAME_PIXEL_HEIGHT (f);
1610 block_input ();
1611 w32_clear_area (f, hdc, 0, FRAME_TOP_MARGIN_HEIGHT (f), width, border);
1612 w32_clear_area (f, hdc, 0, 0, border, height);
1613 w32_clear_area (f, hdc, width - border, 0, border, height);
1614 w32_clear_area (f, hdc, 0, height - border, width, border);
1615 release_frame_dc (f, hdc);
1616 unblock_input ();
1621 void
1622 x_set_internal_border_width (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1624 int border;
1626 CHECK_TYPE_RANGED_INTEGER (int, arg);
1627 border = max (XINT (arg), 0);
1629 if (border != FRAME_INTERNAL_BORDER_WIDTH (f))
1631 FRAME_INTERNAL_BORDER_WIDTH (f) = border;
1633 if (FRAME_X_WINDOW (f) != 0)
1635 adjust_frame_size (f, -1, -1, 3, 0, Qinternal_border_width);
1637 if (FRAME_VISIBLE_P (f))
1638 x_clear_under_internal_border (f);
1644 void
1645 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1647 int nlines;
1649 /* Right now, menu bars don't work properly in minibuf-only frames;
1650 most of the commands try to apply themselves to the minibuffer
1651 frame itself, and get an error because you can't switch buffers
1652 in or split the minibuffer window. */
1653 if (FRAME_MINIBUF_ONLY_P (f))
1654 return;
1656 if (INTEGERP (value))
1657 nlines = XINT (value);
1658 else
1659 nlines = 0;
1661 FRAME_MENU_BAR_LINES (f) = 0;
1662 FRAME_MENU_BAR_HEIGHT (f) = 0;
1663 if (nlines)
1665 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1666 windows_or_buffers_changed = 23;
1668 else
1670 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1671 free_frame_menubar (f);
1672 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1674 /* Adjust the frame size so that the client (text) dimensions
1675 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1676 set correctly. Note that we resize twice: The first time upon
1677 a request from the window manager who wants to keep the height
1678 of the outer rectangle (including decorations) unchanged, and a
1679 second time because we want to keep the height of the inner
1680 rectangle (without the decorations unchanged). */
1681 adjust_frame_size (f, -1, -1, 2, 1, Qmenu_bar_lines);
1683 /* Not sure whether this is needed. */
1684 x_clear_under_internal_border (f);
1689 /* Set the number of lines used for the tool bar of frame F to VALUE.
1690 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1691 the old number of tool bar lines (and is unused). This function may
1692 change the height of all windows on frame F to match the new tool bar
1693 height. By design, the frame's height doesn't change (but maybe it
1694 should if we don't get enough space otherwise). */
1696 void
1697 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1699 int nlines;
1701 /* Treat tool bars like menu bars. */
1702 if (FRAME_MINIBUF_ONLY_P (f))
1703 return;
1705 /* Use VALUE only if an integer >= 0. */
1706 if (INTEGERP (value) && XINT (value) >= 0)
1707 nlines = XFASTINT (value);
1708 else
1709 nlines = 0;
1711 x_change_tool_bar_height (f, nlines * FRAME_LINE_HEIGHT (f));
1715 /* Set the pixel height of the tool bar of frame F to HEIGHT. */
1716 void
1717 x_change_tool_bar_height (struct frame *f, int height)
1719 Lisp_Object frame;
1720 int unit = FRAME_LINE_HEIGHT (f);
1721 int old_height = FRAME_TOOL_BAR_HEIGHT (f);
1722 int lines = (height + unit - 1) / unit;
1723 int old_text_height = FRAME_TEXT_HEIGHT (f);
1725 /* Make sure we redisplay all windows in this frame. */
1726 windows_or_buffers_changed = 23;
1728 /* Recalculate tool bar and frame text sizes. */
1729 FRAME_TOOL_BAR_HEIGHT (f) = height;
1730 FRAME_TOOL_BAR_LINES (f) = lines;
1731 /* Store `tool-bar-lines' and `height' frame parameters. */
1732 store_frame_param (f, Qtool_bar_lines, make_number (lines));
1733 store_frame_param (f, Qheight, make_number (FRAME_LINES (f)));
1735 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1737 clear_frame (f);
1738 clear_current_matrices (f);
1741 if ((height < old_height) && WINDOWP (f->tool_bar_window))
1742 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1744 /* Recalculate toolbar height. */
1745 f->n_tool_bar_rows = 0;
1747 adjust_frame_size (f, -1, -1,
1748 (!f->tool_bar_redisplayed_once ? 1
1749 : (old_height == 0 || height == 0) ? 2
1750 : 4),
1751 0, Qtool_bar_lines);
1753 /* adjust_frame_size might not have done anything, garbage frame
1754 here. */
1755 adjust_frame_glyphs (f);
1756 SET_FRAME_GARBAGED (f);
1757 if (FRAME_X_WINDOW (f))
1758 x_clear_under_internal_border (f);
1762 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1763 w32_id_name.
1765 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1766 name; if NAME is a string, set F's name to NAME and set
1767 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1769 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1770 suggesting a new name, which lisp code should override; if
1771 F->explicit_name is set, ignore the new name; otherwise, set it. */
1773 void
1774 x_set_name (struct frame *f, Lisp_Object name, int explicit)
1776 /* Make sure that requests from lisp code override requests from
1777 Emacs redisplay code. */
1778 if (explicit)
1780 /* If we're switching from explicit to implicit, we had better
1781 update the mode lines and thereby update the title. */
1782 if (f->explicit_name && NILP (name))
1783 update_mode_lines = 25;
1785 f->explicit_name = ! NILP (name);
1787 else if (f->explicit_name)
1788 return;
1790 /* If NAME is nil, set the name to the w32_id_name. */
1791 if (NILP (name))
1793 /* Check for no change needed in this very common case
1794 before we do any consing. */
1795 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1796 SDATA (f->name)))
1797 return;
1798 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1800 else
1801 CHECK_STRING (name);
1803 /* Don't change the name if it's already NAME. */
1804 if (! NILP (Fstring_equal (name, f->name)))
1805 return;
1807 fset_name (f, name);
1809 /* For setting the frame title, the title parameter should override
1810 the name parameter. */
1811 if (! NILP (f->title))
1812 name = f->title;
1814 if (FRAME_W32_WINDOW (f))
1816 block_input ();
1817 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1818 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1819 unblock_input ();
1823 /* This function should be called when the user's lisp code has
1824 specified a name for the frame; the name will override any set by the
1825 redisplay code. */
1826 void
1827 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1829 x_set_name (f, arg, 1);
1832 /* This function should be called by Emacs redisplay code to set the
1833 name; names set this way will never override names set by the user's
1834 lisp code. */
1835 void
1836 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1838 x_set_name (f, arg, 0);
1841 /* Change the title of frame F to NAME.
1842 If NAME is nil, use the frame name as the title. */
1844 void
1845 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1847 /* Don't change the title if it's already NAME. */
1848 if (EQ (name, f->title))
1849 return;
1851 update_mode_lines = 26;
1853 fset_title (f, name);
1855 if (NILP (name))
1856 name = f->name;
1858 if (FRAME_W32_WINDOW (f))
1860 block_input ();
1861 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1862 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1863 unblock_input ();
1867 void
1868 x_set_scroll_bar_default_width (struct frame *f)
1870 int unit = FRAME_COLUMN_WIDTH (f);
1872 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1873 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1874 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1878 void
1879 x_set_scroll_bar_default_height (struct frame *f)
1881 int unit = FRAME_LINE_HEIGHT (f);
1883 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
1884 FRAME_CONFIG_SCROLL_BAR_LINES (f)
1885 = (FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) + unit - 1) / unit;
1888 /* Subroutines for creating a frame. */
1890 Cursor
1891 w32_load_cursor (LPCTSTR name)
1893 /* Try first to load cursor from application resource. */
1894 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1895 name, IMAGE_CURSOR, 0, 0,
1896 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1897 if (!cursor)
1899 /* Then try to load a shared predefined cursor. */
1900 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1901 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1903 return cursor;
1906 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1908 #define INIT_WINDOW_CLASS(WC) \
1909 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1910 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1911 (WC).cbClsExtra = 0; \
1912 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1913 (WC).hInstance = hinst; \
1914 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1915 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1916 (WC).hbrBackground = NULL; \
1917 (WC).lpszMenuName = NULL; \
1919 static BOOL
1920 w32_init_class (HINSTANCE hinst)
1922 if (w32_unicode_gui)
1924 WNDCLASSW uwc;
1925 INIT_WINDOW_CLASS(uwc);
1926 uwc.lpszClassName = L"Emacs";
1928 return RegisterClassW (&uwc);
1930 else
1932 WNDCLASS wc;
1933 INIT_WINDOW_CLASS(wc);
1934 wc.lpszClassName = EMACS_CLASS;
1936 return RegisterClassA (&wc);
1940 static HWND
1941 w32_createvscrollbar (struct frame *f, struct scroll_bar * bar)
1943 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1944 /* Position and size of scroll bar. */
1945 bar->left, bar->top, bar->width, bar->height,
1946 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1949 static HWND
1950 w32_createhscrollbar (struct frame *f, struct scroll_bar * bar)
1952 return CreateWindow ("SCROLLBAR", "", SBS_HORZ | WS_CHILD | WS_VISIBLE,
1953 /* Position and size of scroll bar. */
1954 bar->left, bar->top, bar->width, bar->height,
1955 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1958 static void
1959 w32_createwindow (struct frame *f, int *coords)
1961 HWND hwnd;
1962 RECT rect;
1963 int top;
1964 int left;
1966 rect.left = rect.top = 0;
1967 rect.right = FRAME_PIXEL_WIDTH (f);
1968 rect.bottom = FRAME_PIXEL_HEIGHT (f);
1970 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
1971 FRAME_EXTERNAL_MENU_BAR (f));
1973 /* Do first time app init */
1975 w32_init_class (hinst);
1977 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
1979 left = f->left_pos;
1980 top = f->top_pos;
1982 else
1984 left = coords[0];
1985 top = coords[1];
1988 FRAME_W32_WINDOW (f) = hwnd
1989 = CreateWindow (EMACS_CLASS,
1990 f->namebuf,
1991 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
1992 left, top,
1993 rect.right - rect.left, rect.bottom - rect.top,
1994 NULL,
1995 NULL,
1996 hinst,
1997 NULL);
1999 if (hwnd)
2001 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
2002 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
2003 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
2004 SetWindowLong (hwnd, WND_VSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
2005 SetWindowLong (hwnd, WND_HSCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_HEIGHT (f));
2006 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
2008 /* Enable drag-n-drop. */
2009 DragAcceptFiles (hwnd, TRUE);
2011 /* Do this to discard the default setting specified by our parent. */
2012 ShowWindow (hwnd, SW_HIDE);
2014 /* Update frame positions. */
2015 GetWindowRect (hwnd, &rect);
2016 f->left_pos = rect.left;
2017 f->top_pos = rect.top;
2021 static void
2022 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2024 wmsg->msg.hwnd = hwnd;
2025 wmsg->msg.message = msg;
2026 wmsg->msg.wParam = wParam;
2027 wmsg->msg.lParam = lParam;
2028 wmsg->msg.time = GetMessageTime ();
2030 post_msg (wmsg);
2033 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2034 between left and right keys as advertised. We test for this
2035 support dynamically, and set a flag when the support is absent. If
2036 absent, we keep track of the left and right control and alt keys
2037 ourselves. This is particularly necessary on keyboards that rely
2038 upon the AltGr key, which is represented as having the left control
2039 and right alt keys pressed. For these keyboards, we need to know
2040 when the left alt key has been pressed in addition to the AltGr key
2041 so that we can properly support M-AltGr-key sequences (such as M-@
2042 on Swedish keyboards). */
2044 #define EMACS_LCONTROL 0
2045 #define EMACS_RCONTROL 1
2046 #define EMACS_LMENU 2
2047 #define EMACS_RMENU 3
2049 static int modifiers[4];
2050 static int modifiers_recorded;
2051 static int modifier_key_support_tested;
2053 static void
2054 test_modifier_support (unsigned int wparam)
2056 unsigned int l, r;
2058 if (wparam != VK_CONTROL && wparam != VK_MENU)
2059 return;
2060 if (wparam == VK_CONTROL)
2062 l = VK_LCONTROL;
2063 r = VK_RCONTROL;
2065 else
2067 l = VK_LMENU;
2068 r = VK_RMENU;
2070 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2071 modifiers_recorded = 1;
2072 else
2073 modifiers_recorded = 0;
2074 modifier_key_support_tested = 1;
2077 static void
2078 record_keydown (unsigned int wparam, unsigned int lparam)
2080 int i;
2082 if (!modifier_key_support_tested)
2083 test_modifier_support (wparam);
2085 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2086 return;
2088 if (wparam == VK_CONTROL)
2089 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2090 else
2091 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2093 modifiers[i] = 1;
2096 static void
2097 record_keyup (unsigned int wparam, unsigned int lparam)
2099 int i;
2101 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2102 return;
2104 if (wparam == VK_CONTROL)
2105 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2106 else
2107 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2109 modifiers[i] = 0;
2112 /* Emacs can lose focus while a modifier key has been pressed. When
2113 it regains focus, be conservative and clear all modifiers since
2114 we cannot reconstruct the left and right modifier state. */
2115 static void
2116 reset_modifiers (void)
2118 SHORT ctrl, alt;
2120 if (GetFocus () == NULL)
2121 /* Emacs doesn't have keyboard focus. Do nothing. */
2122 return;
2124 ctrl = GetAsyncKeyState (VK_CONTROL);
2125 alt = GetAsyncKeyState (VK_MENU);
2127 if (!(ctrl & 0x08000))
2128 /* Clear any recorded control modifier state. */
2129 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2131 if (!(alt & 0x08000))
2132 /* Clear any recorded alt modifier state. */
2133 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2135 /* Update the state of all modifier keys, because modifiers used in
2136 hot-key combinations can get stuck on if Emacs loses focus as a
2137 result of a hot-key being pressed. */
2139 BYTE keystate[256];
2141 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2143 memset (keystate, 0, sizeof (keystate));
2144 GetKeyboardState (keystate);
2145 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2146 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2147 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2148 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2149 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2150 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2151 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2152 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2153 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2154 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2155 SetKeyboardState (keystate);
2159 /* Synchronize modifier state with what is reported with the current
2160 keystroke. Even if we cannot distinguish between left and right
2161 modifier keys, we know that, if no modifiers are set, then neither
2162 the left or right modifier should be set. */
2163 static void
2164 sync_modifiers (void)
2166 if (!modifiers_recorded)
2167 return;
2169 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2170 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2172 if (!(GetKeyState (VK_MENU) & 0x8000))
2173 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2176 static int
2177 modifier_set (int vkey)
2179 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2180 toggle keys is not an omission! If you want to add it, you will
2181 have to make changes in the default sub-case of the WM_KEYDOWN
2182 switch, because if the NUMLOCK modifier is set, the code there
2183 will directly convert any key that looks like an ASCII letter,
2184 and also downcase those that look like upper-case ASCII. */
2185 if (vkey == VK_CAPITAL)
2187 if (NILP (Vw32_enable_caps_lock))
2188 return 0;
2189 else
2190 return (GetKeyState (vkey) & 0x1);
2192 if (vkey == VK_SCROLL)
2194 if (NILP (Vw32_scroll_lock_modifier)
2195 /* w32-scroll-lock-modifier can be any non-nil value that is
2196 not one of the modifiers, in which case it shall be ignored. */
2197 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2198 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2199 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2200 || EQ (Vw32_scroll_lock_modifier, Qalt)
2201 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2202 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2203 return 0;
2204 else
2205 return (GetKeyState (vkey) & 0x1);
2208 if (!modifiers_recorded)
2209 return (GetKeyState (vkey) & 0x8000);
2211 switch (vkey)
2213 case VK_LCONTROL:
2214 return modifiers[EMACS_LCONTROL];
2215 case VK_RCONTROL:
2216 return modifiers[EMACS_RCONTROL];
2217 case VK_LMENU:
2218 return modifiers[EMACS_LMENU];
2219 case VK_RMENU:
2220 return modifiers[EMACS_RMENU];
2222 return (GetKeyState (vkey) & 0x8000);
2225 /* Convert between the modifier bits W32 uses and the modifier bits
2226 Emacs uses. */
2228 unsigned int
2229 w32_key_to_modifier (int key)
2231 Lisp_Object key_mapping;
2233 switch (key)
2235 case VK_LWIN:
2236 key_mapping = Vw32_lwindow_modifier;
2237 break;
2238 case VK_RWIN:
2239 key_mapping = Vw32_rwindow_modifier;
2240 break;
2241 case VK_APPS:
2242 key_mapping = Vw32_apps_modifier;
2243 break;
2244 case VK_SCROLL:
2245 key_mapping = Vw32_scroll_lock_modifier;
2246 break;
2247 default:
2248 key_mapping = Qnil;
2251 /* NB. This code runs in the input thread, asynchronously to the lisp
2252 thread, so we must be careful to ensure access to lisp data is
2253 thread-safe. The following code is safe because the modifier
2254 variable values are updated atomically from lisp and symbols are
2255 not relocated by GC. Also, we don't have to worry about seeing GC
2256 markbits here. */
2257 if (EQ (key_mapping, Qhyper))
2258 return hyper_modifier;
2259 if (EQ (key_mapping, Qsuper))
2260 return super_modifier;
2261 if (EQ (key_mapping, Qmeta))
2262 return meta_modifier;
2263 if (EQ (key_mapping, Qalt))
2264 return alt_modifier;
2265 if (EQ (key_mapping, Qctrl))
2266 return ctrl_modifier;
2267 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2268 return ctrl_modifier;
2269 if (EQ (key_mapping, Qshift))
2270 return shift_modifier;
2272 /* Don't generate any modifier if not explicitly requested. */
2273 return 0;
2276 static unsigned int
2277 w32_get_modifiers (void)
2279 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2280 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2281 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2282 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2283 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2284 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2285 (modifier_set (VK_MENU) ?
2286 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2289 /* We map the VK_* modifiers into console modifier constants
2290 so that we can use the same routines to handle both console
2291 and window input. */
2293 static int
2294 construct_console_modifiers (void)
2296 int mods;
2298 mods = 0;
2299 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2300 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2301 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2302 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2303 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2304 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2305 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2306 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2307 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2308 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2309 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2311 return mods;
2314 static int
2315 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2317 int mods;
2319 /* Convert to emacs modifiers. */
2320 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2322 return mods;
2325 unsigned int
2326 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2328 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2329 return virt_key;
2331 if (virt_key == VK_RETURN)
2332 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2334 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2335 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2337 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2338 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2340 if (virt_key == VK_CLEAR)
2341 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2343 return virt_key;
2346 /* List of special key combinations which w32 would normally capture,
2347 but Emacs should grab instead. Not directly visible to lisp, to
2348 simplify synchronization. Each item is an integer encoding a virtual
2349 key code and modifier combination to capture. */
2350 static Lisp_Object w32_grabbed_keys;
2352 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2353 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2354 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2355 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2357 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2358 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2359 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2361 /* Register hot-keys for reserved key combinations when Emacs has
2362 keyboard focus, since this is the only way Emacs can receive key
2363 combinations like Alt-Tab which are used by the system. */
2365 static void
2366 register_hot_keys (HWND hwnd)
2368 Lisp_Object keylist;
2370 /* Use CONSP, since we are called asynchronously. */
2371 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2373 Lisp_Object key = XCAR (keylist);
2375 /* Deleted entries get set to nil. */
2376 if (!INTEGERP (key))
2377 continue;
2379 RegisterHotKey (hwnd, HOTKEY_ID (key),
2380 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2384 static void
2385 unregister_hot_keys (HWND hwnd)
2387 Lisp_Object keylist;
2389 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2391 Lisp_Object key = XCAR (keylist);
2393 if (!INTEGERP (key))
2394 continue;
2396 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2400 #if EMACSDEBUG
2401 const char*
2402 w32_name_of_message (UINT msg)
2404 unsigned i;
2405 static char buf[64];
2406 static const struct {
2407 UINT msg;
2408 const char* name;
2409 } msgnames[] = {
2410 #define M(msg) { msg, # msg }
2411 M (WM_PAINT),
2412 M (WM_TIMER),
2413 M (WM_USER),
2414 M (WM_MOUSEMOVE),
2415 M (WM_LBUTTONUP),
2416 M (WM_KEYDOWN),
2417 M (WM_EMACS_KILL),
2418 M (WM_EMACS_CREATEWINDOW),
2419 M (WM_EMACS_DONE),
2420 M (WM_EMACS_CREATEVSCROLLBAR),
2421 M (WM_EMACS_CREATEHSCROLLBAR),
2422 M (WM_EMACS_SHOWWINDOW),
2423 M (WM_EMACS_SETWINDOWPOS),
2424 M (WM_EMACS_DESTROYWINDOW),
2425 M (WM_EMACS_TRACKPOPUPMENU),
2426 M (WM_EMACS_SETFOCUS),
2427 M (WM_EMACS_SETFOREGROUND),
2428 M (WM_EMACS_SETLOCALE),
2429 M (WM_EMACS_SETKEYBOARDLAYOUT),
2430 M (WM_EMACS_REGISTER_HOT_KEY),
2431 M (WM_EMACS_UNREGISTER_HOT_KEY),
2432 M (WM_EMACS_TOGGLE_LOCK_KEY),
2433 M (WM_EMACS_TRACK_CARET),
2434 M (WM_EMACS_DESTROY_CARET),
2435 M (WM_EMACS_SHOW_CARET),
2436 M (WM_EMACS_HIDE_CARET),
2437 M (WM_EMACS_SETCURSOR),
2438 M (WM_EMACS_SHOWCURSOR),
2439 M (WM_EMACS_PAINT),
2440 M (WM_CHAR),
2441 #undef M
2442 { 0, 0 }
2445 for (i = 0; msgnames[i].name; ++i)
2446 if (msgnames[i].msg == msg)
2447 return msgnames[i].name;
2449 sprintf (buf, "message 0x%04x", (unsigned)msg);
2450 return buf;
2452 #endif /* EMACSDEBUG */
2454 /* Here's an overview of how Emacs input works in GUI sessions on
2455 MS-Windows. (For description of non-GUI input, see the commentary
2456 before w32_console_read_socket in w32inevt.c.)
2458 System messages are read and processed by w32_msg_pump below. This
2459 function runs in a separate thread. It handles a small number of
2460 custom WM_EMACS_* messages (posted by the main thread, look for
2461 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2462 is the main window procedure for the entire Emacs application.
2464 w32_wnd_proc also runs in the same separate input thread. It
2465 handles some messages, mostly those that need GDI calls, by itself.
2466 For the others, it calls my_post_msg, which inserts the messages
2467 into the input queue serviced by w32_read_socket.
2469 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2470 called synchronously from keyboard.c when it is known or suspected
2471 that some input is available. w32_read_socket either handles
2472 messages immediately, or converts them into Emacs input events and
2473 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2474 them and process them when read_char and its callers require
2475 input.
2477 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2478 select(2) takes the place of w32_read_socket.
2482 /* Main message dispatch loop. */
2484 static void
2485 w32_msg_pump (deferred_msg * msg_buf)
2487 MSG msg;
2488 WPARAM result;
2489 HWND focus_window;
2491 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2493 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2496 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2497 /* w32_name_of_message (msg.message), msg.time)); */
2499 if (msg.hwnd == NULL)
2501 switch (msg.message)
2503 case WM_NULL:
2504 /* Produced by complete_deferred_msg; just ignore. */
2505 break;
2506 case WM_EMACS_CREATEWINDOW:
2507 /* Initialize COM for this window. Even though we don't use it,
2508 some third party shell extensions can cause it to be used in
2509 system dialogs, which causes a crash if it is not initialized.
2510 This is a known bug in Windows, which was fixed long ago, but
2511 the patch for XP is not publicly available until XP SP3,
2512 and older versions will never be patched. */
2513 CoInitialize (NULL);
2514 w32_createwindow ((struct frame *) msg.wParam,
2515 (int *) msg.lParam);
2516 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2517 emacs_abort ();
2518 break;
2519 case WM_EMACS_SETLOCALE:
2520 SetThreadLocale (msg.wParam);
2521 /* Reply is not expected. */
2522 break;
2523 case WM_EMACS_SETKEYBOARDLAYOUT:
2524 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2525 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2526 result, 0))
2527 emacs_abort ();
2528 break;
2529 case WM_EMACS_REGISTER_HOT_KEY:
2530 focus_window = GetFocus ();
2531 if (focus_window != NULL)
2532 RegisterHotKey (focus_window,
2533 RAW_HOTKEY_ID (msg.wParam),
2534 RAW_HOTKEY_MODIFIERS (msg.wParam),
2535 RAW_HOTKEY_VK_CODE (msg.wParam));
2536 /* Reply is not expected. */
2537 break;
2538 case WM_EMACS_UNREGISTER_HOT_KEY:
2539 focus_window = GetFocus ();
2540 if (focus_window != NULL)
2541 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2542 /* Mark item as erased. NB: this code must be
2543 thread-safe. The next line is okay because the cons
2544 cell is never made into garbage and is not relocated by
2545 GC. */
2546 XSETCAR (make_lisp_ptr ((void *)msg.lParam, Lisp_Cons), Qnil);
2547 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2548 emacs_abort ();
2549 break;
2550 case WM_EMACS_TOGGLE_LOCK_KEY:
2552 int vk_code = (int) msg.wParam;
2553 int cur_state = (GetKeyState (vk_code) & 1);
2554 int new_state = msg.lParam;
2556 if (new_state == -1
2557 || ((new_state & 1) != cur_state))
2559 one_w32_display_info.faked_key = vk_code;
2561 keybd_event ((BYTE) vk_code,
2562 (BYTE) MapVirtualKey (vk_code, 0),
2563 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2564 keybd_event ((BYTE) vk_code,
2565 (BYTE) MapVirtualKey (vk_code, 0),
2566 KEYEVENTF_EXTENDEDKEY | 0, 0);
2567 keybd_event ((BYTE) vk_code,
2568 (BYTE) MapVirtualKey (vk_code, 0),
2569 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2570 cur_state = !cur_state;
2572 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2573 cur_state, 0))
2574 emacs_abort ();
2576 break;
2577 #ifdef MSG_DEBUG
2578 /* Broadcast messages make it here, so you need to be looking
2579 for something in particular for this to be useful. */
2580 default:
2581 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2582 #endif
2585 else
2587 if (w32_unicode_gui)
2588 DispatchMessageW (&msg);
2589 else
2590 DispatchMessageA (&msg);
2593 /* Exit nested loop when our deferred message has completed. */
2594 if (msg_buf->completed)
2595 break;
2599 deferred_msg * deferred_msg_head;
2601 static deferred_msg *
2602 find_deferred_msg (HWND hwnd, UINT msg)
2604 deferred_msg * item;
2606 /* Don't actually need synchronization for read access, since
2607 modification of single pointer is always atomic. */
2608 /* enter_crit (); */
2610 for (item = deferred_msg_head; item != NULL; item = item->next)
2611 if (item->w32msg.msg.hwnd == hwnd
2612 && item->w32msg.msg.message == msg)
2613 break;
2615 /* leave_crit (); */
2617 return item;
2620 static LRESULT
2621 send_deferred_msg (deferred_msg * msg_buf,
2622 HWND hwnd,
2623 UINT msg,
2624 WPARAM wParam,
2625 LPARAM lParam)
2627 /* Only input thread can send deferred messages. */
2628 if (GetCurrentThreadId () != dwWindowsThreadId)
2629 emacs_abort ();
2631 /* It is an error to send a message that is already deferred. */
2632 if (find_deferred_msg (hwnd, msg) != NULL)
2633 emacs_abort ();
2635 /* Enforced synchronization is not needed because this is the only
2636 function that alters deferred_msg_head, and the following critical
2637 section is guaranteed to only be serially reentered (since only the
2638 input thread can call us). */
2640 /* enter_crit (); */
2642 msg_buf->completed = 0;
2643 msg_buf->next = deferred_msg_head;
2644 deferred_msg_head = msg_buf;
2645 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2647 /* leave_crit (); */
2649 /* Start a new nested message loop to process other messages until
2650 this one is completed. */
2651 w32_msg_pump (msg_buf);
2653 deferred_msg_head = msg_buf->next;
2655 return msg_buf->result;
2658 void
2659 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2661 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2663 if (msg_buf == NULL)
2664 /* Message may have been canceled, so don't abort. */
2665 return;
2667 msg_buf->result = result;
2668 msg_buf->completed = 1;
2670 /* Ensure input thread is woken so it notices the completion. */
2671 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2674 static void
2675 cancel_all_deferred_msgs (void)
2677 deferred_msg * item;
2679 /* Don't actually need synchronization for read access, since
2680 modification of single pointer is always atomic. */
2681 /* enter_crit (); */
2683 for (item = deferred_msg_head; item != NULL; item = item->next)
2685 item->result = 0;
2686 item->completed = 1;
2689 /* leave_crit (); */
2691 /* Ensure input thread is woken so it notices the completion. */
2692 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2695 DWORD WINAPI
2696 w32_msg_worker (void *arg)
2698 MSG msg;
2699 deferred_msg dummy_buf;
2701 /* Ensure our message queue is created */
2703 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2705 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2706 emacs_abort ();
2708 memset (&dummy_buf, 0, sizeof (dummy_buf));
2709 dummy_buf.w32msg.msg.hwnd = NULL;
2710 dummy_buf.w32msg.msg.message = WM_NULL;
2712 /* This is the initial message loop which should only exit when the
2713 application quits. */
2714 w32_msg_pump (&dummy_buf);
2716 return 0;
2719 static void
2720 signal_user_input (void)
2722 /* Interrupt any lisp that wants to be interrupted by input. */
2723 if (!NILP (Vthrow_on_input))
2725 Vquit_flag = Vthrow_on_input;
2726 /* Doing a QUIT from this thread is a bad idea, since this
2727 unwinds the stack of the Lisp thread, and the Windows runtime
2728 rightfully barfs. Disabled. */
2729 #if 0
2730 /* If we're inside a function that wants immediate quits,
2731 do it now. */
2732 if (immediate_quit && NILP (Vinhibit_quit))
2734 immediate_quit = 0;
2735 QUIT;
2737 #endif
2742 static void
2743 post_character_message (HWND hwnd, UINT msg,
2744 WPARAM wParam, LPARAM lParam,
2745 DWORD modifiers)
2747 W32Msg wmsg;
2749 wmsg.dwModifiers = modifiers;
2751 /* Detect quit_char and set quit-flag directly. Note that we
2752 still need to post a message to ensure the main thread will be
2753 woken up if blocked in sys_select, but we do NOT want to post
2754 the quit_char message itself (because it will usually be as if
2755 the user had typed quit_char twice). Instead, we post a dummy
2756 message that has no particular effect. */
2758 int c = wParam;
2759 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2760 c = make_ctrl_char (c) & 0377;
2761 if (c == quit_char
2762 || (wmsg.dwModifiers == 0
2763 && w32_quit_key && wParam == w32_quit_key))
2765 Vquit_flag = Qt;
2767 /* The choice of message is somewhat arbitrary, as long as
2768 the main thread handler just ignores it. */
2769 msg = WM_NULL;
2771 /* Interrupt any blocking system calls. */
2772 signal_quit ();
2774 /* As a safety precaution, forcibly complete any deferred
2775 messages. This is a kludge, but I don't see any particularly
2776 clean way to handle the situation where a deferred message is
2777 "dropped" in the lisp thread, and will thus never be
2778 completed, eg. by the user trying to activate the menubar
2779 when the lisp thread is busy, and then typing C-g when the
2780 menubar doesn't open promptly (with the result that the
2781 menubar never responds at all because the deferred
2782 WM_INITMENU message is never completed). Another problem
2783 situation is when the lisp thread calls SendMessage (to send
2784 a window manager command) when a message has been deferred;
2785 the lisp thread gets blocked indefinitely waiting for the
2786 deferred message to be completed, which itself is waiting for
2787 the lisp thread to respond.
2789 Note that we don't want to block the input thread waiting for
2790 a response from the lisp thread (although that would at least
2791 solve the deadlock problem above), because we want to be able
2792 to receive C-g to interrupt the lisp thread. */
2793 cancel_all_deferred_msgs ();
2795 else
2796 signal_user_input ();
2799 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2802 /* Main window procedure */
2804 static LRESULT CALLBACK
2805 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2807 struct frame *f;
2808 struct w32_display_info *dpyinfo = &one_w32_display_info;
2809 W32Msg wmsg;
2810 int windows_translate;
2811 int key;
2813 /* Note that it is okay to call x_window_to_frame, even though we are
2814 not running in the main lisp thread, because frame deletion
2815 requires the lisp thread to synchronize with this thread. Thus, if
2816 a frame struct is returned, it can be used without concern that the
2817 lisp thread might make it disappear while we are using it.
2819 NB. Walking the frame list in this thread is safe (as long as
2820 writes of Lisp_Object slots are atomic, which they are on Windows).
2821 Although delete-frame can destructively modify the frame list while
2822 we are walking it, a garbage collection cannot occur until after
2823 delete-frame has synchronized with this thread.
2825 It is also safe to use functions that make GDI calls, such as
2826 w32_clear_rect, because these functions must obtain a DC handle
2827 from the frame struct using get_frame_dc which is thread-aware. */
2829 switch (msg)
2831 case WM_ERASEBKGND:
2832 f = x_window_to_frame (dpyinfo, hwnd);
2833 if (f)
2835 HDC hdc = get_frame_dc (f);
2836 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2837 w32_clear_rect (f, hdc, &wmsg.rect);
2838 release_frame_dc (f, hdc);
2840 #if defined (W32_DEBUG_DISPLAY)
2841 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2843 wmsg.rect.left, wmsg.rect.top,
2844 wmsg.rect.right, wmsg.rect.bottom));
2845 #endif /* W32_DEBUG_DISPLAY */
2847 return 1;
2848 case WM_PALETTECHANGED:
2849 /* ignore our own changes */
2850 if ((HWND)wParam != hwnd)
2852 f = x_window_to_frame (dpyinfo, hwnd);
2853 if (f)
2854 /* get_frame_dc will realize our palette and force all
2855 frames to be redrawn if needed. */
2856 release_frame_dc (f, get_frame_dc (f));
2858 return 0;
2859 case WM_PAINT:
2861 PAINTSTRUCT paintStruct;
2862 RECT update_rect;
2863 memset (&update_rect, 0, sizeof (update_rect));
2865 f = x_window_to_frame (dpyinfo, hwnd);
2866 if (f == 0)
2868 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2869 return 0;
2872 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2873 fails. Apparently this can happen under some
2874 circumstances. */
2875 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2877 enter_crit ();
2878 BeginPaint (hwnd, &paintStruct);
2880 /* The rectangles returned by GetUpdateRect and BeginPaint
2881 do not always match. Play it safe by assuming both areas
2882 are invalid. */
2883 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2885 #if defined (W32_DEBUG_DISPLAY)
2886 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2888 wmsg.rect.left, wmsg.rect.top,
2889 wmsg.rect.right, wmsg.rect.bottom));
2890 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2891 update_rect.left, update_rect.top,
2892 update_rect.right, update_rect.bottom));
2893 #endif
2894 EndPaint (hwnd, &paintStruct);
2895 leave_crit ();
2897 /* Change the message type to prevent Windows from
2898 combining WM_PAINT messages in the Lisp thread's queue,
2899 since Windows assumes that each message queue is
2900 dedicated to one frame and does not bother checking
2901 that hwnd matches before combining them. */
2902 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
2904 return 0;
2907 /* If GetUpdateRect returns 0 (meaning there is no update
2908 region), assume the whole window needs to be repainted. */
2909 GetClientRect (hwnd, &wmsg.rect);
2910 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2911 return 0;
2914 case WM_INPUTLANGCHANGE:
2915 /* Inform lisp thread of keyboard layout changes. */
2916 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2918 /* Clear dead keys in the keyboard state; for simplicity only
2919 preserve modifier key states. */
2921 int i;
2922 BYTE keystate[256];
2924 GetKeyboardState (keystate);
2925 for (i = 0; i < 256; i++)
2926 if (1
2927 && i != VK_SHIFT
2928 && i != VK_LSHIFT
2929 && i != VK_RSHIFT
2930 && i != VK_CAPITAL
2931 && i != VK_NUMLOCK
2932 && i != VK_SCROLL
2933 && i != VK_CONTROL
2934 && i != VK_LCONTROL
2935 && i != VK_RCONTROL
2936 && i != VK_MENU
2937 && i != VK_LMENU
2938 && i != VK_RMENU
2939 && i != VK_LWIN
2940 && i != VK_RWIN)
2941 keystate[i] = 0;
2942 SetKeyboardState (keystate);
2944 goto dflt;
2946 case WM_HOTKEY:
2947 /* Synchronize hot keys with normal input. */
2948 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2949 return (0);
2951 case WM_KEYUP:
2952 case WM_SYSKEYUP:
2953 record_keyup (wParam, lParam);
2954 goto dflt;
2956 case WM_KEYDOWN:
2957 case WM_SYSKEYDOWN:
2958 /* Ignore keystrokes we fake ourself; see below. */
2959 if (dpyinfo->faked_key == wParam)
2961 dpyinfo->faked_key = 0;
2962 /* Make sure TranslateMessage sees them though (as long as
2963 they don't produce WM_CHAR messages). This ensures that
2964 indicator lights are toggled promptly on Windows 9x, for
2965 example. */
2966 if (wParam < 256 && lispy_function_keys[wParam])
2968 windows_translate = 1;
2969 goto translate;
2971 return 0;
2974 /* Synchronize modifiers with current keystroke. */
2975 sync_modifiers ();
2976 record_keydown (wParam, lParam);
2977 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2979 windows_translate = 0;
2981 switch (wParam)
2983 case VK_LWIN:
2984 if (NILP (Vw32_pass_lwindow_to_system))
2986 /* Prevent system from acting on keyup (which opens the
2987 Start menu if no other key was pressed) by simulating a
2988 press of Space which we will ignore. */
2989 if (GetAsyncKeyState (wParam) & 1)
2991 if (NUMBERP (Vw32_phantom_key_code))
2992 key = XUINT (Vw32_phantom_key_code) & 255;
2993 else
2994 key = VK_SPACE;
2995 dpyinfo->faked_key = key;
2996 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2999 if (!NILP (Vw32_lwindow_modifier))
3000 return 0;
3001 break;
3002 case VK_RWIN:
3003 if (NILP (Vw32_pass_rwindow_to_system))
3005 if (GetAsyncKeyState (wParam) & 1)
3007 if (NUMBERP (Vw32_phantom_key_code))
3008 key = XUINT (Vw32_phantom_key_code) & 255;
3009 else
3010 key = VK_SPACE;
3011 dpyinfo->faked_key = key;
3012 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3015 if (!NILP (Vw32_rwindow_modifier))
3016 return 0;
3017 break;
3018 case VK_APPS:
3019 if (!NILP (Vw32_apps_modifier))
3020 return 0;
3021 break;
3022 case VK_MENU:
3023 if (NILP (Vw32_pass_alt_to_system))
3024 /* Prevent DefWindowProc from activating the menu bar if an
3025 Alt key is pressed and released by itself. */
3026 return 0;
3027 windows_translate = 1;
3028 break;
3029 case VK_CAPITAL:
3030 /* Decide whether to treat as modifier or function key. */
3031 if (NILP (Vw32_enable_caps_lock))
3032 goto disable_lock_key;
3033 windows_translate = 1;
3034 break;
3035 case VK_NUMLOCK:
3036 /* Decide whether to treat as modifier or function key. */
3037 if (NILP (Vw32_enable_num_lock))
3038 goto disable_lock_key;
3039 windows_translate = 1;
3040 break;
3041 case VK_SCROLL:
3042 /* Decide whether to treat as modifier or function key. */
3043 if (NILP (Vw32_scroll_lock_modifier))
3044 goto disable_lock_key;
3045 windows_translate = 1;
3046 break;
3047 disable_lock_key:
3048 /* Ensure the appropriate lock key state (and indicator light)
3049 remains in the same state. We do this by faking another
3050 press of the relevant key. Apparently, this really is the
3051 only way to toggle the state of the indicator lights. */
3052 dpyinfo->faked_key = wParam;
3053 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3054 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3055 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3056 KEYEVENTF_EXTENDEDKEY | 0, 0);
3057 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3058 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3059 /* Ensure indicator lights are updated promptly on Windows 9x
3060 (TranslateMessage apparently does this), after forwarding
3061 input event. */
3062 post_character_message (hwnd, msg, wParam, lParam,
3063 w32_get_key_modifiers (wParam, lParam));
3064 windows_translate = 1;
3065 break;
3066 case VK_CONTROL:
3067 case VK_SHIFT:
3068 case VK_PROCESSKEY: /* Generated by IME. */
3069 windows_translate = 1;
3070 break;
3071 case VK_CANCEL:
3072 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3073 which is confusing for purposes of key binding; convert
3074 VK_CANCEL events into VK_PAUSE events. */
3075 wParam = VK_PAUSE;
3076 break;
3077 case VK_PAUSE:
3078 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3079 for purposes of key binding; convert these back into
3080 VK_NUMLOCK events, at least when we want to see NumLock key
3081 presses. (Note that there is never any possibility that
3082 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3083 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3084 wParam = VK_NUMLOCK;
3085 break;
3086 default:
3087 /* If not defined as a function key, change it to a WM_CHAR message. */
3088 if (wParam > 255 || !lispy_function_keys[wParam])
3090 DWORD modifiers = construct_console_modifiers ();
3092 if (!NILP (Vw32_recognize_altgr)
3093 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3095 /* Always let TranslateMessage handle AltGr key chords;
3096 for some reason, ToAscii doesn't always process AltGr
3097 chords correctly. */
3098 windows_translate = 1;
3100 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3102 /* Handle key chords including any modifiers other
3103 than shift directly, in order to preserve as much
3104 modifier information as possible. */
3105 if ('A' <= wParam && wParam <= 'Z')
3107 /* Don't translate modified alphabetic keystrokes,
3108 so the user doesn't need to constantly switch
3109 layout to type control or meta keystrokes when
3110 the normal layout translates alphabetic
3111 characters to non-ascii characters. */
3112 if (!modifier_set (VK_SHIFT))
3113 wParam += ('a' - 'A');
3114 msg = WM_CHAR;
3116 else
3118 /* Try to handle other keystrokes by determining the
3119 base character (ie. translating the base key plus
3120 shift modifier). */
3121 int add;
3122 KEY_EVENT_RECORD key;
3124 key.bKeyDown = TRUE;
3125 key.wRepeatCount = 1;
3126 key.wVirtualKeyCode = wParam;
3127 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3128 key.uChar.AsciiChar = 0;
3129 key.dwControlKeyState = modifiers;
3131 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3132 /* 0 means an unrecognized keycode, negative means
3133 dead key. Ignore both. */
3134 while (--add >= 0)
3136 /* Forward asciified character sequence. */
3137 post_character_message
3138 (hwnd, WM_CHAR,
3139 (unsigned char) key.uChar.AsciiChar, lParam,
3140 w32_get_key_modifiers (wParam, lParam));
3141 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3143 return 0;
3146 else
3148 /* Let TranslateMessage handle everything else. */
3149 windows_translate = 1;
3154 translate:
3155 if (windows_translate)
3157 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3158 windows_msg.time = GetMessageTime ();
3159 TranslateMessage (&windows_msg);
3160 goto dflt;
3163 /* Fall through */
3165 case WM_SYSCHAR:
3166 case WM_CHAR:
3167 if (wParam > 255 )
3169 W32Msg wmsg;
3171 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3172 signal_user_input ();
3173 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3176 else
3177 post_character_message (hwnd, msg, wParam, lParam,
3178 w32_get_key_modifiers (wParam, lParam));
3179 break;
3181 case WM_UNICHAR:
3182 /* WM_UNICHAR looks promising from the docs, but the exact
3183 circumstances in which TranslateMessage sends it is one of those
3184 Microsoft secret API things that EU and US courts are supposed
3185 to have put a stop to already. Spy++ shows it being sent to Notepad
3186 and other MS apps, but never to Emacs.
3188 Some third party IMEs send it in accordance with the official
3189 documentation though, so handle it here.
3191 UNICODE_NOCHAR is used to test for support for this message.
3192 TRUE indicates that the message is supported. */
3193 if (wParam == UNICODE_NOCHAR)
3194 return TRUE;
3197 W32Msg wmsg;
3198 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3199 signal_user_input ();
3200 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3202 break;
3204 case WM_IME_CHAR:
3205 /* If we can't get the IME result as Unicode, use default processing,
3206 which will at least allow characters decodable in the system locale
3207 get through. */
3208 if (!get_composition_string_fn)
3209 goto dflt;
3211 else if (!ignore_ime_char)
3213 wchar_t * buffer;
3214 int size, i;
3215 W32Msg wmsg;
3216 HIMC context = get_ime_context_fn (hwnd);
3217 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3218 /* Get buffer size. */
3219 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3220 buffer = alloca (size);
3221 size = get_composition_string_fn (context, GCS_RESULTSTR,
3222 buffer, size);
3223 release_ime_context_fn (hwnd, context);
3225 signal_user_input ();
3226 for (i = 0; i < size / sizeof (wchar_t); i++)
3228 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3229 lParam);
3231 /* Ignore the messages for the rest of the
3232 characters in the string that was output above. */
3233 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3235 else
3236 ignore_ime_char--;
3238 break;
3240 case WM_IME_STARTCOMPOSITION:
3241 if (!set_ime_composition_window_fn)
3242 goto dflt;
3243 else
3245 COMPOSITIONFORM form;
3246 HIMC context;
3247 struct window *w;
3249 /* Implementation note: The code below does something that
3250 one shouldn't do: it accesses the window object from a
3251 separate thread, while the main (a.k.a. "Lisp") thread
3252 runs and can legitimately delete and even GC it. That is
3253 why we are extra careful not to futz with a window that
3254 is different from the one recorded when the system caret
3255 coordinates were last modified. That is also why we are
3256 careful not to move the IME window if the window
3257 described by W was deleted, as indicated by its buffer
3258 field being reset to nil. */
3259 f = x_window_to_frame (dpyinfo, hwnd);
3260 if (!(f && FRAME_LIVE_P (f)))
3261 break;
3262 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3263 /* Punt if someone changed the frame's selected window
3264 behind our back. */
3265 if (w != w32_system_caret_window)
3266 break;
3268 form.dwStyle = CFS_RECT;
3269 form.ptCurrentPos.x = w32_system_caret_x;
3270 form.ptCurrentPos.y = w32_system_caret_y;
3272 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3273 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3274 + w32_system_caret_hdr_height);
3275 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3276 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3277 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3278 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3279 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3280 - w32_system_caret_mode_height);
3282 /* Punt if the window was deleted behind our back. */
3283 if (!BUFFERP (w->contents))
3284 break;
3286 context = get_ime_context_fn (hwnd);
3288 if (!context)
3289 break;
3291 set_ime_composition_window_fn (context, &form);
3292 release_ime_context_fn (hwnd, context);
3294 break;
3296 case WM_IME_ENDCOMPOSITION:
3297 ignore_ime_char = 0;
3298 goto dflt;
3300 /* Simulate middle mouse button events when left and right buttons
3301 are used together, but only if user has two button mouse. */
3302 case WM_LBUTTONDOWN:
3303 case WM_RBUTTONDOWN:
3304 if (w32_num_mouse_buttons > 2)
3305 goto handle_plain_button;
3308 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3309 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3311 if (button_state & this)
3312 return 0;
3314 if (button_state == 0)
3315 SetCapture (hwnd);
3317 button_state |= this;
3319 if (button_state & other)
3321 if (mouse_button_timer)
3323 KillTimer (hwnd, mouse_button_timer);
3324 mouse_button_timer = 0;
3326 /* Generate middle mouse event instead. */
3327 msg = WM_MBUTTONDOWN;
3328 button_state |= MMOUSE;
3330 else if (button_state & MMOUSE)
3332 /* Ignore button event if we've already generated a
3333 middle mouse down event. This happens if the
3334 user releases and press one of the two buttons
3335 after we've faked a middle mouse event. */
3336 return 0;
3338 else
3340 /* Flush out saved message. */
3341 post_msg (&saved_mouse_button_msg);
3343 wmsg.dwModifiers = w32_get_modifiers ();
3344 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3345 signal_user_input ();
3347 /* Clear message buffer. */
3348 saved_mouse_button_msg.msg.hwnd = 0;
3350 else
3352 /* Hold onto message for now. */
3353 mouse_button_timer =
3354 SetTimer (hwnd, MOUSE_BUTTON_ID,
3355 w32_mouse_button_tolerance, NULL);
3356 saved_mouse_button_msg.msg.hwnd = hwnd;
3357 saved_mouse_button_msg.msg.message = msg;
3358 saved_mouse_button_msg.msg.wParam = wParam;
3359 saved_mouse_button_msg.msg.lParam = lParam;
3360 saved_mouse_button_msg.msg.time = GetMessageTime ();
3361 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3364 return 0;
3366 case WM_LBUTTONUP:
3367 case WM_RBUTTONUP:
3368 if (w32_num_mouse_buttons > 2)
3369 goto handle_plain_button;
3372 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3373 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3375 if ((button_state & this) == 0)
3376 return 0;
3378 button_state &= ~this;
3380 if (button_state & MMOUSE)
3382 /* Only generate event when second button is released. */
3383 if ((button_state & other) == 0)
3385 msg = WM_MBUTTONUP;
3386 button_state &= ~MMOUSE;
3388 if (button_state) emacs_abort ();
3390 else
3391 return 0;
3393 else
3395 /* Flush out saved message if necessary. */
3396 if (saved_mouse_button_msg.msg.hwnd)
3398 post_msg (&saved_mouse_button_msg);
3401 wmsg.dwModifiers = w32_get_modifiers ();
3402 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3403 signal_user_input ();
3405 /* Always clear message buffer and cancel timer. */
3406 saved_mouse_button_msg.msg.hwnd = 0;
3407 KillTimer (hwnd, mouse_button_timer);
3408 mouse_button_timer = 0;
3410 if (button_state == 0)
3411 ReleaseCapture ();
3413 return 0;
3415 case WM_XBUTTONDOWN:
3416 case WM_XBUTTONUP:
3417 if (w32_pass_extra_mouse_buttons_to_system)
3418 goto dflt;
3419 /* else fall through and process them. */
3420 case WM_MBUTTONDOWN:
3421 case WM_MBUTTONUP:
3422 handle_plain_button:
3424 BOOL up;
3425 int button;
3427 /* Ignore middle and extra buttons as long as the menu is active. */
3428 f = x_window_to_frame (dpyinfo, hwnd);
3429 if (f && f->output_data.w32->menubar_active)
3430 return 0;
3432 if (parse_button (msg, HIWORD (wParam), &button, &up))
3434 if (up) ReleaseCapture ();
3435 else SetCapture (hwnd);
3436 button = (button == 0) ? LMOUSE :
3437 ((button == 1) ? MMOUSE : RMOUSE);
3438 if (up)
3439 button_state &= ~button;
3440 else
3441 button_state |= button;
3445 wmsg.dwModifiers = w32_get_modifiers ();
3446 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3447 signal_user_input ();
3449 /* Need to return true for XBUTTON messages, false for others,
3450 to indicate that we processed the message. */
3451 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3453 case WM_MOUSEMOVE:
3454 /* Ignore mouse movements as long as the menu is active. These
3455 movements are processed by the window manager anyway, and
3456 it's wrong to handle them as if they happened on the
3457 underlying frame. */
3458 f = x_window_to_frame (dpyinfo, hwnd);
3459 if (f && f->output_data.w32->menubar_active)
3460 return 0;
3462 /* If the mouse has just moved into the frame, start tracking
3463 it, so we will be notified when it leaves the frame. Mouse
3464 tracking only works under W98 and NT4 and later. On earlier
3465 versions, there is no way of telling when the mouse leaves the
3466 frame, so we just have to put up with help-echo and mouse
3467 highlighting remaining while the frame is not active. */
3468 if (track_mouse_event_fn && !track_mouse_window
3469 /* If the menu bar is active, turning on tracking of mouse
3470 movement events might send these events to the tooltip
3471 frame, if the user happens to move the mouse pointer over
3472 the tooltip. But since we don't process events for
3473 tooltip frames, this causes Windows to present a
3474 hourglass cursor, which is ugly and unexpected. So don't
3475 enable tracking mouse events in this case; they will be
3476 restarted when the menu pops down. (Confusingly, the
3477 menubar_active member of f->output_data.w32, tested
3478 above, is only set when a menu was popped up _not_ from
3479 the frame's menu bar, but via x-popup-menu.) */
3480 && !menubar_in_use)
3482 TRACKMOUSEEVENT tme;
3483 tme.cbSize = sizeof (tme);
3484 tme.dwFlags = TME_LEAVE;
3485 tme.hwndTrack = hwnd;
3486 tme.dwHoverTime = HOVER_DEFAULT;
3488 track_mouse_event_fn (&tme);
3489 track_mouse_window = hwnd;
3491 case WM_HSCROLL:
3492 case WM_VSCROLL:
3493 if (w32_mouse_move_interval <= 0
3494 || (msg == WM_MOUSEMOVE && button_state == 0))
3496 wmsg.dwModifiers = w32_get_modifiers ();
3497 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3498 return 0;
3501 /* Hang onto mouse move and scroll messages for a bit, to avoid
3502 sending such events to Emacs faster than it can process them.
3503 If we get more events before the timer from the first message
3504 expires, we just replace the first message. */
3506 if (saved_mouse_move_msg.msg.hwnd == 0)
3507 mouse_move_timer =
3508 SetTimer (hwnd, MOUSE_MOVE_ID,
3509 w32_mouse_move_interval, NULL);
3511 /* Hold onto message for now. */
3512 saved_mouse_move_msg.msg.hwnd = hwnd;
3513 saved_mouse_move_msg.msg.message = msg;
3514 saved_mouse_move_msg.msg.wParam = wParam;
3515 saved_mouse_move_msg.msg.lParam = lParam;
3516 saved_mouse_move_msg.msg.time = GetMessageTime ();
3517 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3519 return 0;
3521 case WM_MOUSEWHEEL:
3522 case WM_DROPFILES:
3523 wmsg.dwModifiers = w32_get_modifiers ();
3524 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3525 signal_user_input ();
3526 return 0;
3528 case WM_APPCOMMAND:
3529 if (w32_pass_multimedia_buttons_to_system)
3530 goto dflt;
3531 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3532 case WM_MOUSEHWHEEL:
3533 wmsg.dwModifiers = w32_get_modifiers ();
3534 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3535 signal_user_input ();
3536 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3537 handled, to prevent the system trying to handle it by faking
3538 scroll bar events. */
3539 return 1;
3541 case WM_TIMER:
3542 /* Flush out saved messages if necessary. */
3543 if (wParam == mouse_button_timer)
3545 if (saved_mouse_button_msg.msg.hwnd)
3547 post_msg (&saved_mouse_button_msg);
3548 signal_user_input ();
3549 saved_mouse_button_msg.msg.hwnd = 0;
3551 KillTimer (hwnd, mouse_button_timer);
3552 mouse_button_timer = 0;
3554 else if (wParam == mouse_move_timer)
3556 if (saved_mouse_move_msg.msg.hwnd)
3558 post_msg (&saved_mouse_move_msg);
3559 saved_mouse_move_msg.msg.hwnd = 0;
3561 KillTimer (hwnd, mouse_move_timer);
3562 mouse_move_timer = 0;
3564 else if (wParam == menu_free_timer)
3566 KillTimer (hwnd, menu_free_timer);
3567 menu_free_timer = 0;
3568 f = x_window_to_frame (dpyinfo, hwnd);
3569 /* If a popup menu is active, don't wipe its strings. */
3570 if (menubar_in_use
3571 && current_popup_menu == NULL)
3573 /* Free memory used by owner-drawn and help-echo strings. */
3574 w32_free_menu_strings (hwnd);
3575 if (f)
3576 f->output_data.w32->menubar_active = 0;
3577 menubar_in_use = 0;
3580 return 0;
3582 case WM_NCACTIVATE:
3583 /* Windows doesn't send us focus messages when putting up and
3584 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3585 The only indication we get that something happened is receiving
3586 this message afterwards. So this is a good time to reset our
3587 keyboard modifiers' state. */
3588 reset_modifiers ();
3589 goto dflt;
3591 case WM_INITMENU:
3592 button_state = 0;
3593 ReleaseCapture ();
3594 /* We must ensure menu bar is fully constructed and up to date
3595 before allowing user interaction with it. To achieve this
3596 we send this message to the lisp thread and wait for a
3597 reply (whose value is not actually needed) to indicate that
3598 the menu bar is now ready for use, so we can now return.
3600 To remain responsive in the meantime, we enter a nested message
3601 loop that can process all other messages.
3603 However, we skip all this if the message results from calling
3604 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3605 thread a message because it is blocked on us at this point. We
3606 set menubar_active before calling TrackPopupMenu to indicate
3607 this (there is no possibility of confusion with real menubar
3608 being active). */
3610 f = x_window_to_frame (dpyinfo, hwnd);
3611 if (f
3612 && (f->output_data.w32->menubar_active
3613 /* We can receive this message even in the absence of a
3614 menubar (ie. when the system menu is activated) - in this
3615 case we do NOT want to forward the message, otherwise it
3616 will cause the menubar to suddenly appear when the user
3617 had requested it to be turned off! */
3618 || f->output_data.w32->menubar_widget == NULL))
3619 return 0;
3622 deferred_msg msg_buf;
3624 /* Detect if message has already been deferred; in this case
3625 we cannot return any sensible value to ignore this. */
3626 if (find_deferred_msg (hwnd, msg) != NULL)
3627 emacs_abort ();
3629 menubar_in_use = 1;
3631 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3634 case WM_EXITMENULOOP:
3635 f = x_window_to_frame (dpyinfo, hwnd);
3637 /* If a menu is still active, check again after a short delay,
3638 since Windows often (always?) sends the WM_EXITMENULOOP
3639 before the corresponding WM_COMMAND message.
3640 Don't do this if a popup menu is active, since it is only
3641 menubar menus that require cleaning up in this way.
3643 if (f && menubar_in_use && current_popup_menu == NULL)
3644 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3646 /* If hourglass cursor should be displayed, display it now. */
3647 if (f && f->output_data.w32->hourglass_p)
3648 SetCursor (f->output_data.w32->hourglass_cursor);
3650 goto dflt;
3652 case WM_MENUSELECT:
3653 /* Direct handling of help_echo in menus. Should be safe now
3654 that we generate the help_echo by placing a help event in the
3655 keyboard buffer. */
3657 HMENU menu = (HMENU) lParam;
3658 UINT menu_item = (UINT) LOWORD (wParam);
3659 UINT flags = (UINT) HIWORD (wParam);
3661 w32_menu_display_help (hwnd, menu, menu_item, flags);
3663 return 0;
3665 case WM_MEASUREITEM:
3666 f = x_window_to_frame (dpyinfo, hwnd);
3667 if (f)
3669 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3671 if (pMis->CtlType == ODT_MENU)
3673 /* Work out dimensions for popup menu titles. */
3674 char * title = (char *) pMis->itemData;
3675 HDC hdc = GetDC (hwnd);
3676 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3677 LOGFONT menu_logfont;
3678 HFONT old_font;
3679 SIZE size;
3681 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3682 menu_logfont.lfWeight = FW_BOLD;
3683 menu_font = CreateFontIndirect (&menu_logfont);
3684 old_font = SelectObject (hdc, menu_font);
3686 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3687 if (title)
3689 if (unicode_append_menu)
3690 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3691 wcslen ((WCHAR *) title),
3692 &size);
3693 else
3694 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3696 pMis->itemWidth = size.cx;
3697 if (pMis->itemHeight < size.cy)
3698 pMis->itemHeight = size.cy;
3700 else
3701 pMis->itemWidth = 0;
3703 SelectObject (hdc, old_font);
3704 DeleteObject (menu_font);
3705 ReleaseDC (hwnd, hdc);
3706 return TRUE;
3709 return 0;
3711 case WM_DRAWITEM:
3712 f = x_window_to_frame (dpyinfo, hwnd);
3713 if (f)
3715 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3717 if (pDis->CtlType == ODT_MENU)
3719 /* Draw popup menu title. */
3720 char * title = (char *) pDis->itemData;
3721 if (title)
3723 HDC hdc = pDis->hDC;
3724 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3725 LOGFONT menu_logfont;
3726 HFONT old_font;
3728 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3729 menu_logfont.lfWeight = FW_BOLD;
3730 menu_font = CreateFontIndirect (&menu_logfont);
3731 old_font = SelectObject (hdc, menu_font);
3733 /* Always draw title as if not selected. */
3734 if (unicode_append_menu)
3735 ExtTextOutW (hdc,
3736 pDis->rcItem.left
3737 + GetSystemMetrics (SM_CXMENUCHECK),
3738 pDis->rcItem.top,
3739 ETO_OPAQUE, &pDis->rcItem,
3740 (WCHAR *) title,
3741 wcslen ((WCHAR *) title), NULL);
3742 else
3743 ExtTextOut (hdc,
3744 pDis->rcItem.left
3745 + GetSystemMetrics (SM_CXMENUCHECK),
3746 pDis->rcItem.top,
3747 ETO_OPAQUE, &pDis->rcItem,
3748 title, strlen (title), NULL);
3750 SelectObject (hdc, old_font);
3751 DeleteObject (menu_font);
3753 return TRUE;
3756 return 0;
3758 #if 0
3759 /* Still not right - can't distinguish between clicks in the
3760 client area of the frame from clicks forwarded from the scroll
3761 bars - may have to hook WM_NCHITTEST to remember the mouse
3762 position and then check if it is in the client area ourselves. */
3763 case WM_MOUSEACTIVATE:
3764 /* Discard the mouse click that activates a frame, allowing the
3765 user to click anywhere without changing point (or worse!).
3766 Don't eat mouse clicks on scrollbars though!! */
3767 if (LOWORD (lParam) == HTCLIENT )
3768 return MA_ACTIVATEANDEAT;
3769 goto dflt;
3770 #endif
3772 case WM_MOUSELEAVE:
3773 /* No longer tracking mouse. */
3774 track_mouse_window = NULL;
3776 case WM_ACTIVATEAPP:
3777 case WM_ACTIVATE:
3778 case WM_WINDOWPOSCHANGED:
3779 case WM_SHOWWINDOW:
3780 /* Inform lisp thread that a frame might have just been obscured
3781 or exposed, so should recheck visibility of all frames. */
3782 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3783 goto dflt;
3785 case WM_SETFOCUS:
3786 dpyinfo->faked_key = 0;
3787 reset_modifiers ();
3788 register_hot_keys (hwnd);
3789 goto command;
3790 case WM_KILLFOCUS:
3791 unregister_hot_keys (hwnd);
3792 button_state = 0;
3793 ReleaseCapture ();
3794 /* Relinquish the system caret. */
3795 if (w32_system_caret_hwnd)
3797 w32_visible_system_caret_hwnd = NULL;
3798 w32_system_caret_hwnd = NULL;
3799 DestroyCaret ();
3801 goto command;
3802 case WM_COMMAND:
3803 menubar_in_use = 0;
3804 f = x_window_to_frame (dpyinfo, hwnd);
3805 if (f && HIWORD (wParam) == 0)
3807 if (menu_free_timer)
3809 KillTimer (hwnd, menu_free_timer);
3810 menu_free_timer = 0;
3813 case WM_MOVE:
3814 case WM_SIZE:
3815 command:
3816 wmsg.dwModifiers = w32_get_modifiers ();
3817 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3818 goto dflt;
3820 case WM_DESTROY:
3821 CoUninitialize ();
3822 return 0;
3824 case WM_CLOSE:
3825 wmsg.dwModifiers = w32_get_modifiers ();
3826 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3827 return 0;
3829 case WM_WINDOWPOSCHANGING:
3830 /* Don't restrict the sizing of any kind of frames. If the window
3831 manager doesn't, there's no reason to do it ourselves. */
3832 #if 0
3833 if (frame_resize_pixelwise || hwnd == tip_window)
3834 #endif
3835 return 0;
3837 #if 0
3838 /* Don't restrict the sizing of fullscreened frames, allowing them to be
3839 flush with the sides of the screen. */
3840 f = x_window_to_frame (dpyinfo, hwnd);
3841 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
3842 return 0;
3845 WINDOWPLACEMENT wp;
3846 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3848 wp.length = sizeof (WINDOWPLACEMENT);
3849 GetWindowPlacement (hwnd, &wp);
3851 if (wp.showCmd != SW_SHOWMAXIMIZED && wp.showCmd != SW_SHOWMINIMIZED
3852 && (lppos->flags & SWP_NOSIZE) == 0)
3854 RECT rect;
3855 int wdiff;
3856 int hdiff;
3857 DWORD font_width;
3858 DWORD line_height;
3859 DWORD internal_border;
3860 DWORD vscrollbar_extra;
3861 DWORD hscrollbar_extra;
3862 RECT wr;
3864 wp.length = sizeof (wp);
3865 GetWindowRect (hwnd, &wr);
3867 enter_crit ();
3869 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3870 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3871 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3872 vscrollbar_extra = GetWindowLong (hwnd, WND_VSCROLLBAR_INDEX);
3873 hscrollbar_extra = GetWindowLong (hwnd, WND_HSCROLLBAR_INDEX);
3875 leave_crit ();
3877 memset (&rect, 0, sizeof (rect));
3878 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3879 GetMenu (hwnd) != NULL);
3881 /* Force width and height of client area to be exact
3882 multiples of the character cell dimensions. */
3883 wdiff = (lppos->cx - (rect.right - rect.left)
3884 - 2 * internal_border - vscrollbar_extra)
3885 % font_width;
3886 hdiff = (lppos->cy - (rect.bottom - rect.top)
3887 - 2 * internal_border - hscrollbar_extra)
3888 % line_height;
3890 if (wdiff || hdiff)
3892 /* For right/bottom sizing we can just fix the sizes.
3893 However for top/left sizing we will need to fix the X
3894 and Y positions as well. */
3896 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3897 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3899 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3900 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3902 if (wp.showCmd != SW_SHOWMAXIMIZED
3903 && (lppos->flags & SWP_NOMOVE) == 0)
3905 if (lppos->x != wr.left || lppos->y != wr.top)
3907 lppos->x += wdiff;
3908 lppos->y += hdiff;
3910 else
3912 lppos->flags |= SWP_NOMOVE;
3916 return 0;
3921 goto dflt;
3922 #endif
3924 case WM_GETMINMAXINFO:
3925 /* Hack to allow resizing the Emacs frame above the screen size.
3926 Note that Windows 9x limits coordinates to 16-bits. */
3927 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3928 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3929 return 0;
3931 case WM_SETCURSOR:
3932 if (LOWORD (lParam) == HTCLIENT)
3934 f = x_window_to_frame (dpyinfo, hwnd);
3935 if (f && f->output_data.w32->hourglass_p
3936 && !menubar_in_use && !current_popup_menu)
3937 SetCursor (f->output_data.w32->hourglass_cursor);
3938 else if (f)
3939 SetCursor (f->output_data.w32->current_cursor);
3940 return 0;
3942 goto dflt;
3944 case WM_EMACS_SETCURSOR:
3946 Cursor cursor = (Cursor) wParam;
3947 f = x_window_to_frame (dpyinfo, hwnd);
3948 if (f && cursor)
3950 f->output_data.w32->current_cursor = cursor;
3951 if (!f->output_data.w32->hourglass_p)
3952 SetCursor (cursor);
3954 return 0;
3957 case WM_EMACS_SHOWCURSOR:
3959 ShowCursor ((BOOL) wParam);
3961 return 0;
3964 case WM_EMACS_CREATEVSCROLLBAR:
3965 return (LRESULT) w32_createvscrollbar ((struct frame *) wParam,
3966 (struct scroll_bar *) lParam);
3968 case WM_EMACS_CREATEHSCROLLBAR:
3969 return (LRESULT) w32_createhscrollbar ((struct frame *) wParam,
3970 (struct scroll_bar *) lParam);
3972 case WM_EMACS_SHOWWINDOW:
3973 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3975 case WM_EMACS_BRINGTOTOP:
3976 case WM_EMACS_SETFOREGROUND:
3978 HWND foreground_window;
3979 DWORD foreground_thread, retval;
3981 /* On NT 5.0, and apparently Windows 98, it is necessary to
3982 attach to the thread that currently has focus in order to
3983 pull the focus away from it. */
3984 foreground_window = GetForegroundWindow ();
3985 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3986 if (!foreground_window
3987 || foreground_thread == GetCurrentThreadId ()
3988 || !AttachThreadInput (GetCurrentThreadId (),
3989 foreground_thread, TRUE))
3990 foreground_thread = 0;
3992 retval = SetForegroundWindow ((HWND) wParam);
3993 if (msg == WM_EMACS_BRINGTOTOP)
3994 retval = BringWindowToTop ((HWND) wParam);
3996 /* Detach from the previous foreground thread. */
3997 if (foreground_thread)
3998 AttachThreadInput (GetCurrentThreadId (),
3999 foreground_thread, FALSE);
4001 return retval;
4004 case WM_EMACS_SETWINDOWPOS:
4006 WINDOWPOS * pos = (WINDOWPOS *) wParam;
4007 return SetWindowPos (hwnd, pos->hwndInsertAfter,
4008 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
4011 case WM_EMACS_DESTROYWINDOW:
4012 DragAcceptFiles ((HWND) wParam, FALSE);
4013 return DestroyWindow ((HWND) wParam);
4015 case WM_EMACS_HIDE_CARET:
4016 return HideCaret (hwnd);
4018 case WM_EMACS_SHOW_CARET:
4019 return ShowCaret (hwnd);
4021 case WM_EMACS_DESTROY_CARET:
4022 w32_system_caret_hwnd = NULL;
4023 w32_visible_system_caret_hwnd = NULL;
4024 return DestroyCaret ();
4026 case WM_EMACS_TRACK_CARET:
4027 /* If there is currently no system caret, create one. */
4028 if (w32_system_caret_hwnd == NULL)
4030 /* Use the default caret width, and avoid changing it
4031 unnecessarily, as it confuses screen reader software. */
4032 w32_system_caret_hwnd = hwnd;
4033 CreateCaret (hwnd, NULL, 0,
4034 w32_system_caret_height);
4037 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4038 return 0;
4039 /* Ensure visible caret gets turned on when requested. */
4040 else if (w32_use_visible_system_caret
4041 && w32_visible_system_caret_hwnd != hwnd)
4043 w32_visible_system_caret_hwnd = hwnd;
4044 return ShowCaret (hwnd);
4046 /* Ensure visible caret gets turned off when requested. */
4047 else if (!w32_use_visible_system_caret
4048 && w32_visible_system_caret_hwnd)
4050 w32_visible_system_caret_hwnd = NULL;
4051 return HideCaret (hwnd);
4053 else
4054 return 1;
4056 case WM_EMACS_TRACKPOPUPMENU:
4058 UINT flags;
4059 POINT *pos;
4060 int retval;
4061 pos = (POINT *)lParam;
4062 flags = TPM_CENTERALIGN;
4063 if (button_state & LMOUSE)
4064 flags |= TPM_LEFTBUTTON;
4065 else if (button_state & RMOUSE)
4066 flags |= TPM_RIGHTBUTTON;
4068 /* Remember we did a SetCapture on the initial mouse down event,
4069 so for safety, we make sure the capture is canceled now. */
4070 ReleaseCapture ();
4071 button_state = 0;
4073 /* Use menubar_active to indicate that WM_INITMENU is from
4074 TrackPopupMenu below, and should be ignored. */
4075 f = x_window_to_frame (dpyinfo, hwnd);
4076 if (f)
4077 f->output_data.w32->menubar_active = 1;
4079 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4080 0, hwnd, NULL))
4082 MSG amsg;
4083 /* Eat any mouse messages during popupmenu */
4084 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4085 PM_REMOVE));
4086 /* Get the menu selection, if any */
4087 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4089 retval = LOWORD (amsg.wParam);
4091 else
4093 retval = 0;
4096 else
4098 retval = -1;
4101 return retval;
4103 case WM_EMACS_FILENOTIFY:
4104 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4105 return 1;
4107 default:
4108 /* Check for messages registered at runtime. */
4109 if (msg == msh_mousewheel)
4111 wmsg.dwModifiers = w32_get_modifiers ();
4112 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4113 signal_user_input ();
4114 return 0;
4117 dflt:
4118 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4121 /* The most common default return code for handled messages is 0. */
4122 return 0;
4125 static void
4126 my_create_window (struct frame * f)
4128 MSG msg;
4129 static int coords[2];
4130 Lisp_Object left, top;
4131 struct w32_display_info *dpyinfo = &one_w32_display_info;
4133 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
4134 anything that is not a number and is not Qunbound. */
4135 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
4136 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
4137 if (EQ (left, Qunbound))
4138 coords[0] = CW_USEDEFAULT;
4139 else
4140 coords[0] = XINT (left);
4141 if (EQ (top, Qunbound))
4142 coords[1] = CW_USEDEFAULT;
4143 else
4144 coords[1] = XINT (top);
4146 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
4147 (WPARAM)f, (LPARAM)coords))
4148 emacs_abort ();
4149 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4153 /* Create a tooltip window. Unlike my_create_window, we do not do this
4154 indirectly via the Window thread, as we do not need to process Window
4155 messages for the tooltip. Creating tooltips indirectly also creates
4156 deadlocks when tooltips are created for menu items. */
4157 static void
4158 my_create_tip_window (struct frame *f)
4160 RECT rect;
4162 rect.left = rect.top = 0;
4163 rect.right = FRAME_PIXEL_WIDTH (f);
4164 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4166 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4167 FRAME_EXTERNAL_MENU_BAR (f));
4169 tip_window = FRAME_W32_WINDOW (f)
4170 = CreateWindow (EMACS_CLASS,
4171 f->namebuf,
4172 f->output_data.w32->dwStyle,
4173 f->left_pos,
4174 f->top_pos,
4175 rect.right - rect.left,
4176 rect.bottom - rect.top,
4177 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4178 NULL,
4179 hinst,
4180 NULL);
4182 if (tip_window)
4184 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4185 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4186 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4187 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4189 /* Tip frames have no scrollbars. */
4190 SetWindowLong (tip_window, WND_VSCROLLBAR_INDEX, 0);
4191 SetWindowLong (tip_window, WND_HSCROLLBAR_INDEX, 0);
4193 /* Do this to discard the default setting specified by our parent. */
4194 ShowWindow (tip_window, SW_HIDE);
4199 /* Create and set up the w32 window for frame F. */
4201 static void
4202 w32_window (struct frame *f, long window_prompting, int minibuffer_only)
4204 block_input ();
4206 /* Use the resource name as the top-level window name
4207 for looking up resources. Make a non-Lisp copy
4208 for the window manager, so GC relocation won't bother it.
4210 Elsewhere we specify the window name for the window manager. */
4211 f->namebuf = xstrdup (SSDATA (Vx_resource_name));
4213 my_create_window (f);
4215 validate_x_resource_name ();
4217 /* x_set_name normally ignores requests to set the name if the
4218 requested name is the same as the current name. This is the one
4219 place where that assumption isn't correct; f->name is set, but
4220 the server hasn't been told. */
4222 Lisp_Object name;
4223 int explicit = f->explicit_name;
4225 f->explicit_name = 0;
4226 name = f->name;
4227 fset_name (f, Qnil);
4228 x_set_name (f, name, explicit);
4231 unblock_input ();
4233 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4234 initialize_frame_menubar (f);
4236 if (FRAME_W32_WINDOW (f) == 0)
4237 error ("Unable to create window");
4240 /* Handle the icon stuff for this window. Perhaps later we might
4241 want an x_set_icon_position which can be called interactively as
4242 well. */
4244 static void
4245 x_icon (struct frame *f, Lisp_Object parms)
4247 Lisp_Object icon_x, icon_y;
4248 struct w32_display_info *dpyinfo = &one_w32_display_info;
4250 /* Set the position of the icon. Note that Windows 95 groups all
4251 icons in the tray. */
4252 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4253 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4254 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4256 CHECK_NUMBER (icon_x);
4257 CHECK_NUMBER (icon_y);
4259 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4260 error ("Both left and top icon corners of icon must be specified");
4262 block_input ();
4264 #if 0 /* TODO */
4265 /* Start up iconic or window? */
4266 x_wm_set_window_state
4267 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4268 ? IconicState
4269 : NormalState));
4271 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4272 ? f->icon_name
4273 : f->name)));
4274 #endif
4276 unblock_input ();
4280 static void
4281 x_make_gc (struct frame *f)
4283 XGCValues gc_values;
4285 block_input ();
4287 /* Create the GC's of this frame.
4288 Note that many default values are used. */
4290 /* Normal video */
4291 gc_values.font = FRAME_FONT (f);
4293 /* Cursor has cursor-color background, background-color foreground. */
4294 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4295 gc_values.background = f->output_data.w32->cursor_pixel;
4296 f->output_data.w32->cursor_gc
4297 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4298 (GCFont | GCForeground | GCBackground),
4299 &gc_values);
4301 /* Reliefs. */
4302 f->output_data.w32->white_relief.gc = 0;
4303 f->output_data.w32->black_relief.gc = 0;
4305 unblock_input ();
4309 /* Handler for signals raised during x_create_frame and
4310 x_create_tip_frame. FRAME is the frame which is partially
4311 constructed. */
4313 static Lisp_Object
4314 unwind_create_frame (Lisp_Object frame)
4316 struct frame *f = XFRAME (frame);
4318 /* If frame is ``official'', nothing to do. */
4319 if (NILP (Fmemq (frame, Vframe_list)))
4321 #ifdef GLYPH_DEBUG
4322 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4324 /* If the frame's image cache refcount is still the same as our
4325 private shadow variable, it means we are unwinding a frame
4326 for which we didn't yet call init_frame_faces, where the
4327 refcount is incremented. Therefore, we increment it here, so
4328 that free_frame_faces, called in x_free_frame_resources
4329 below, will not mistakenly decrement the counter that was not
4330 incremented yet to account for this new frame. */
4331 if (FRAME_IMAGE_CACHE (f) != NULL
4332 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
4333 FRAME_IMAGE_CACHE (f)->refcount++;
4334 #endif
4336 x_free_frame_resources (f);
4337 free_glyphs (f);
4339 #ifdef GLYPH_DEBUG
4340 /* Check that reference counts are indeed correct. */
4341 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4342 eassert ((dpyinfo->terminal->image_cache == NULL
4343 && image_cache_refcount == 0)
4344 || (dpyinfo->terminal->image_cache != NULL
4345 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
4346 #endif
4347 return Qt;
4350 return Qnil;
4353 static void
4354 do_unwind_create_frame (Lisp_Object frame)
4356 unwind_create_frame (frame);
4359 static void
4360 unwind_create_frame_1 (Lisp_Object val)
4362 inhibit_lisp_code = val;
4365 static void
4366 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4368 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4369 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4370 RES_TYPE_STRING);
4371 Lisp_Object font;
4372 if (EQ (font_param, Qunbound))
4373 font_param = Qnil;
4374 font = !NILP (font_param) ? font_param
4375 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4377 if (!STRINGP (font))
4379 int i;
4380 static char *names[]
4381 = { "Courier New-10",
4382 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4383 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4384 "Fixedsys",
4385 NULL };
4387 for (i = 0; names[i]; i++)
4389 font = font_open_by_name (f, build_unibyte_string (names[i]));
4390 if (! NILP (font))
4391 break;
4393 if (NILP (font))
4394 error ("No suitable font was found");
4396 else if (!NILP (font_param))
4398 /* Remember the explicit font parameter, so we can re-apply it after
4399 we've applied the `default' face settings. */
4400 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4402 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4405 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4406 1, 1, 0,
4407 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4408 Return an Emacs frame object.
4409 PARAMETERS is an alist of frame parameters.
4410 If the parameters specify that the frame should not have a minibuffer,
4411 and do not specify a specific minibuffer window to use,
4412 then `default-minibuffer-frame' must be a frame whose minibuffer can
4413 be shared by the new frame.
4415 This function is an internal primitive--use `make-frame' instead. */)
4416 (Lisp_Object parameters)
4418 struct frame *f;
4419 Lisp_Object frame, tem;
4420 Lisp_Object name;
4421 int minibuffer_only = 0;
4422 long window_prompting = 0;
4423 ptrdiff_t count = SPECPDL_INDEX ();
4424 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4425 Lisp_Object display;
4426 struct w32_display_info *dpyinfo = NULL;
4427 Lisp_Object parent;
4428 struct kboard *kb;
4430 if (!FRAME_W32_P (SELECTED_FRAME ())
4431 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4432 error ("Cannot create a GUI frame in a -nw session");
4434 /* Make copy of frame parameters because the original is in pure
4435 storage now. */
4436 parameters = Fcopy_alist (parameters);
4438 /* Use this general default value to start with
4439 until we know if this frame has a specified name. */
4440 Vx_resource_name = Vinvocation_name;
4442 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4443 if (EQ (display, Qunbound))
4444 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4445 if (EQ (display, Qunbound))
4446 display = Qnil;
4447 dpyinfo = check_x_display_info (display);
4448 kb = dpyinfo->terminal->kboard;
4450 if (!dpyinfo->terminal->name)
4451 error ("Terminal is not live, can't create new frames on it");
4453 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4454 if (!STRINGP (name)
4455 && ! EQ (name, Qunbound)
4456 && ! NILP (name))
4457 error ("Invalid frame name--not a string or nil");
4459 if (STRINGP (name))
4460 Vx_resource_name = name;
4462 /* See if parent window is specified. */
4463 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4464 if (EQ (parent, Qunbound))
4465 parent = Qnil;
4466 if (! NILP (parent))
4467 CHECK_NUMBER (parent);
4469 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4470 /* No need to protect DISPLAY because that's not used after passing
4471 it to make_frame_without_minibuffer. */
4472 frame = Qnil;
4473 GCPRO4 (parameters, parent, name, frame);
4474 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
4475 RES_TYPE_SYMBOL);
4476 if (EQ (tem, Qnone) || NILP (tem))
4477 f = make_frame_without_minibuffer (Qnil, kb, display);
4478 else if (EQ (tem, Qonly))
4480 f = make_minibuffer_frame ();
4481 minibuffer_only = 1;
4483 else if (WINDOWP (tem))
4484 f = make_frame_without_minibuffer (tem, kb, display);
4485 else
4486 f = make_frame (1);
4488 XSETFRAME (frame, f);
4490 /* By default, make scrollbars the system standard width and height. */
4491 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
4492 FRAME_CONFIG_SCROLL_BAR_HEIGHT (f) = GetSystemMetrics (SM_CXHSCROLL);
4494 f->terminal = dpyinfo->terminal;
4496 f->output_method = output_w32;
4497 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
4498 FRAME_FONTSET (f) = -1;
4500 fset_icon_name
4501 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
4502 RES_TYPE_STRING));
4503 if (! STRINGP (f->icon_name))
4504 fset_icon_name (f, Qnil);
4506 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
4508 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
4509 record_unwind_protect (do_unwind_create_frame, frame);
4511 #ifdef GLYPH_DEBUG
4512 image_cache_refcount =
4513 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
4514 dpyinfo_refcount = dpyinfo->reference_count;
4515 #endif /* GLYPH_DEBUG */
4517 /* Specify the parent under which to make this window. */
4518 if (!NILP (parent))
4520 /* Cast to UINT_PTR shuts up compiler warnings about cast to
4521 pointer from integer of different size. */
4522 f->output_data.w32->parent_desc = (Window) (UINT_PTR) XFASTINT (parent);
4523 f->output_data.w32->explicit_parent = 1;
4525 else
4527 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4528 f->output_data.w32->explicit_parent = 0;
4531 /* Set the name; the functions to which we pass f expect the name to
4532 be set. */
4533 if (EQ (name, Qunbound) || NILP (name))
4535 fset_name (f, build_string (dpyinfo->w32_id_name));
4536 f->explicit_name = 0;
4538 else
4540 fset_name (f, name);
4541 f->explicit_name = 1;
4542 /* Use the frame's title when getting resources for this frame. */
4543 specbind (Qx_resource_name, name);
4546 if (uniscribe_available)
4547 register_font_driver (&uniscribe_font_driver, f);
4548 register_font_driver (&w32font_driver, f);
4550 x_default_parameter (f, parameters, Qfont_backend, Qnil,
4551 "fontBackend", "FontBackend", RES_TYPE_STRING);
4553 /* Extract the window parameters from the supplied values
4554 that are needed to determine window geometry. */
4555 x_default_font_parameter (f, parameters);
4557 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4558 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4560 /* We recognize either internalBorderWidth or internalBorder
4561 (which is what xterm calls it). */
4562 if (NILP (Fassq (Qinternal_border_width, parameters)))
4564 Lisp_Object value;
4566 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
4567 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4568 if (! EQ (value, Qunbound))
4569 parameters = Fcons (Fcons (Qinternal_border_width, value),
4570 parameters);
4572 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4573 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4574 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4575 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
4576 NULL, NULL, RES_TYPE_NUMBER);
4577 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
4578 NULL, NULL, RES_TYPE_NUMBER);
4579 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4580 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4581 x_default_parameter (f, parameters, Qhorizontal_scroll_bars, Qnil,
4582 "horizontalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4584 /* Also do the stuff which must be set before the window exists. */
4585 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4586 "foreground", "Foreground", RES_TYPE_STRING);
4587 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4588 "background", "Background", RES_TYPE_STRING);
4589 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4590 "pointerColor", "Foreground", RES_TYPE_STRING);
4591 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4592 "borderColor", "BorderColor", RES_TYPE_STRING);
4593 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4594 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4595 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4596 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4597 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4598 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4599 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4600 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4601 /* Process alpha here (Bug#16619). */
4602 x_default_parameter (f, parameters, Qalpha, Qnil,
4603 "alpha", "Alpha", RES_TYPE_NUMBER);
4605 /* Init faces first since we need the frame's column width/line
4606 height in various occasions. */
4607 init_frame_faces (f);
4609 /* The following call of change_frame_size is needed since otherwise
4610 x_set_tool_bar_lines will already work with the character sizes
4611 installed by init_frame_faces while the frame's pixel size is
4612 still calculated from a character size of 1 and we subsequently
4613 hit the (height >= 0) assertion in window_box_height.
4615 The non-pixelwise code apparently worked around this because it
4616 had one frame line vs one toolbar line which left us with a zero
4617 root window height which was obviously wrong as well ... */
4618 adjust_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
4619 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 5, 1,
4620 Qx_create_frame_1);
4622 /* The X resources controlling the menu-bar and tool-bar are
4623 processed specially at startup, and reflected in the mode
4624 variables; ignore them here. */
4625 x_default_parameter (f, parameters, Qmenu_bar_lines,
4626 NILP (Vmenu_bar_mode)
4627 ? make_number (0) : make_number (1),
4628 NULL, NULL, RES_TYPE_NUMBER);
4629 x_default_parameter (f, parameters, Qtool_bar_lines,
4630 NILP (Vtool_bar_mode)
4631 ? make_number (0) : make_number (1),
4632 NULL, NULL, RES_TYPE_NUMBER);
4634 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4635 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4636 x_default_parameter (f, parameters, Qtitle, Qnil,
4637 "title", "Title", RES_TYPE_STRING);
4638 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4639 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4641 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4642 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4644 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4645 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4646 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4647 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4648 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4649 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4650 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
4652 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
4654 window_prompting = x_figure_window_size (f, parameters, 1);
4656 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4657 f->no_split = minibuffer_only || EQ (tem, Qt);
4659 w32_window (f, window_prompting, minibuffer_only);
4660 x_icon (f, parameters);
4662 x_make_gc (f);
4664 /* Now consider the frame official. */
4665 f->terminal->reference_count++;
4666 FRAME_DISPLAY_INFO (f)->reference_count++;
4667 Vframe_list = Fcons (frame, Vframe_list);
4669 /* We need to do this after creating the window, so that the
4670 icon-creation functions can say whose icon they're describing. */
4671 x_default_parameter (f, parameters, Qicon_type, Qnil,
4672 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4674 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4675 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4676 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4677 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4678 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4679 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4680 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4681 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4682 x_default_parameter (f, parameters, Qscroll_bar_height, Qnil,
4683 "scrollBarHeight", "ScrollBarHeight", RES_TYPE_NUMBER);
4685 /* Allow x_set_window_size, now. */
4686 f->can_x_set_window_size = true;
4688 adjust_frame_size (f, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 0, 1,
4689 Qx_create_frame_2);
4691 /* Tell the server what size and position, etc, we want, and how
4692 badly we want them. This should be done after we have the menu
4693 bar so that its size can be taken into account. */
4694 block_input ();
4695 x_wm_set_size_hint (f, window_prompting, 0);
4696 unblock_input ();
4698 /* Make the window appear on the frame and enable display, unless
4699 the caller says not to. However, with explicit parent, Emacs
4700 cannot control visibility, so don't try. */
4701 if (! f->output_data.w32->explicit_parent)
4703 Lisp_Object visibility;
4705 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4706 if (EQ (visibility, Qunbound))
4707 visibility = Qt;
4709 if (EQ (visibility, Qicon))
4710 x_iconify_frame (f);
4711 else if (! NILP (visibility))
4712 x_make_frame_visible (f);
4713 else
4714 /* Must have been Qnil. */
4718 /* Initialize `default-minibuffer-frame' in case this is the first
4719 frame on this terminal. */
4720 if (FRAME_HAS_MINIBUF_P (f)
4721 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
4722 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
4723 kset_default_minibuffer_frame (kb, frame);
4725 /* All remaining specified parameters, which have not been "used"
4726 by x_get_arg and friends, now go in the misc. alist of the frame. */
4727 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4728 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4729 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
4731 UNGCPRO;
4733 /* Make sure windows on this frame appear in calls to next-window
4734 and similar functions. */
4735 Vwindow_list = Qnil;
4737 return unbind_to (count, frame);
4740 /* FRAME is used only to get a handle on the X display. We don't pass the
4741 display info directly because we're called from frame.c, which doesn't
4742 know about that structure. */
4743 Lisp_Object
4744 x_get_focus_frame (struct frame *frame)
4746 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
4747 Lisp_Object xfocus;
4748 if (! dpyinfo->w32_focus_frame)
4749 return Qnil;
4751 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4752 return xfocus;
4755 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4756 doc: /* Internal function called by `color-defined-p', which see.
4757 \(Note that the Nextstep version of this function ignores FRAME.) */)
4758 (Lisp_Object color, Lisp_Object frame)
4760 XColor foo;
4761 struct frame *f = decode_window_system_frame (frame);
4763 CHECK_STRING (color);
4765 if (w32_defined_color (f, SDATA (color), &foo, 0))
4766 return Qt;
4767 else
4768 return Qnil;
4771 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
4772 doc: /* Internal function called by `color-values', which see. */)
4773 (Lisp_Object color, Lisp_Object frame)
4775 XColor foo;
4776 struct frame *f = decode_window_system_frame (frame);
4778 CHECK_STRING (color);
4780 if (w32_defined_color (f, SDATA (color), &foo, 0))
4781 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4782 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4783 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
4784 else
4785 return Qnil;
4788 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
4789 doc: /* Internal function called by `display-color-p', which see. */)
4790 (Lisp_Object display)
4792 struct w32_display_info *dpyinfo = check_x_display_info (display);
4794 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4795 return Qnil;
4797 return Qt;
4800 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4801 Sx_display_grayscale_p, 0, 1, 0,
4802 doc: /* Return t if DISPLAY supports shades of gray.
4803 Note that color displays do support shades of gray.
4804 The optional argument DISPLAY specifies which display to ask about.
4805 DISPLAY should be either a frame or a display name (a string).
4806 If omitted or nil, that stands for the selected frame's display. */)
4807 (Lisp_Object display)
4809 struct w32_display_info *dpyinfo = check_x_display_info (display);
4811 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4812 return Qnil;
4814 return Qt;
4817 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4818 Sx_display_pixel_width, 0, 1, 0,
4819 doc: /* Return the width in pixels of DISPLAY.
4820 The optional argument DISPLAY specifies which display to ask about.
4821 DISPLAY should be either a frame or a display name (a string).
4822 If omitted or nil, that stands for the selected frame's display.
4824 On \"multi-monitor\" setups this refers to the pixel width for all
4825 physical monitors associated with DISPLAY. To get information for
4826 each physical monitor, use `display-monitor-attributes-list'. */)
4827 (Lisp_Object display)
4829 struct w32_display_info *dpyinfo = check_x_display_info (display);
4831 return make_number (x_display_pixel_width (dpyinfo));
4834 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
4835 Sx_display_pixel_height, 0, 1, 0,
4836 doc: /* Return the height in pixels of DISPLAY.
4837 The optional argument DISPLAY specifies which display to ask about.
4838 DISPLAY should be either a frame or a display name (a string).
4839 If omitted or nil, that stands for the selected frame's display.
4841 On \"multi-monitor\" setups this refers to the pixel height for all
4842 physical monitors associated with DISPLAY. To get information for
4843 each physical monitor, use `display-monitor-attributes-list'. */)
4844 (Lisp_Object display)
4846 struct w32_display_info *dpyinfo = check_x_display_info (display);
4848 return make_number (x_display_pixel_height (dpyinfo));
4851 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
4852 0, 1, 0,
4853 doc: /* Return the number of bitplanes of DISPLAY.
4854 The optional argument DISPLAY specifies which display to ask about.
4855 DISPLAY should be either a frame or a display name (a string).
4856 If omitted or nil, that stands for the selected frame's display. */)
4857 (Lisp_Object display)
4859 struct w32_display_info *dpyinfo = check_x_display_info (display);
4861 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4864 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
4865 0, 1, 0,
4866 doc: /* Return the number of color cells of DISPLAY.
4867 The optional argument DISPLAY specifies which display to ask about.
4868 DISPLAY should be either a frame or a display name (a string).
4869 If omitted or nil, that stands for the selected frame's display. */)
4870 (Lisp_Object display)
4872 struct w32_display_info *dpyinfo = check_x_display_info (display);
4873 int cap;
4875 /* Don't use NCOLORS: it returns incorrect results under remote
4876 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4877 * overflow and because probably is more meaningful on Windows
4878 * anyway. */
4880 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
4881 return make_number (cap);
4884 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4885 Sx_server_max_request_size,
4886 0, 1, 0,
4887 doc: /* Return the maximum request size of the server of DISPLAY.
4888 The optional argument DISPLAY specifies which display to ask about.
4889 DISPLAY should be either a frame or a display name (a string).
4890 If omitted or nil, that stands for the selected frame's display. */)
4891 (Lisp_Object display)
4893 return make_number (1);
4896 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
4897 doc: /* Return the "vendor ID" string of the W32 system (Microsoft).
4898 The optional argument DISPLAY specifies which display to ask about.
4899 DISPLAY should be either a frame or a display name (a string).
4900 If omitted or nil, that stands for the selected frame's display. */)
4901 (Lisp_Object display)
4903 return build_string ("Microsoft Corp.");
4906 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
4907 doc: /* Return the version numbers of the server of DISPLAY.
4908 The value is a list of three integers: the major and minor
4909 version numbers of the X Protocol in use, and the distributor-specific
4910 release number. See also the function `x-server-vendor'.
4912 The optional argument DISPLAY specifies which display to ask about.
4913 DISPLAY should be either a frame or a display name (a string).
4914 If omitted or nil, that stands for the selected frame's display. */)
4915 (Lisp_Object display)
4917 return list3i (w32_major_version, w32_minor_version, w32_build_number);
4920 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
4921 doc: /* Return the number of screens on the server of DISPLAY.
4922 The optional argument DISPLAY specifies which display to ask about.
4923 DISPLAY should be either a frame or a display name (a string).
4924 If omitted or nil, that stands for the selected frame's display. */)
4925 (Lisp_Object display)
4927 return make_number (1);
4930 DEFUN ("x-display-mm-height", Fx_display_mm_height,
4931 Sx_display_mm_height, 0, 1, 0,
4932 doc: /* Return the height in millimeters of DISPLAY.
4933 The optional argument DISPLAY specifies which display to ask about.
4934 DISPLAY should be either a frame or a display name (a string).
4935 If omitted or nil, that stands for the selected frame's display.
4937 On \"multi-monitor\" setups this refers to the height in millimeters for
4938 all physical monitors associated with DISPLAY. To get information
4939 for each physical monitor, use `display-monitor-attributes-list'. */)
4940 (Lisp_Object display)
4942 struct w32_display_info *dpyinfo = check_x_display_info (display);
4943 HDC hdc;
4944 double mm_per_pixel;
4946 hdc = GetDC (NULL);
4947 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
4948 / GetDeviceCaps (hdc, VERTRES));
4949 ReleaseDC (NULL, hdc);
4951 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
4954 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
4955 doc: /* Return the width in millimeters of DISPLAY.
4956 The optional argument DISPLAY specifies which display to ask about.
4957 DISPLAY should be either a frame or a display name (a string).
4958 If omitted or nil, that stands for the selected frame's display.
4960 On \"multi-monitor\" setups this refers to the width in millimeters for
4961 all physical monitors associated with TERMINAL. To get information
4962 for each physical monitor, use `display-monitor-attributes-list'. */)
4963 (Lisp_Object display)
4965 struct w32_display_info *dpyinfo = check_x_display_info (display);
4966 HDC hdc;
4967 double mm_per_pixel;
4969 hdc = GetDC (NULL);
4970 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
4971 / GetDeviceCaps (hdc, HORZRES));
4972 ReleaseDC (NULL, hdc);
4974 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
4977 DEFUN ("x-display-backing-store", Fx_display_backing_store,
4978 Sx_display_backing_store, 0, 1, 0,
4979 doc: /* Return an indication of whether DISPLAY does backing store.
4980 The value may be `always', `when-mapped', or `not-useful'.
4981 The optional argument DISPLAY specifies which display to ask about.
4982 DISPLAY should be either a frame or a display name (a string).
4983 If omitted or nil, that stands for the selected frame's display. */)
4984 (Lisp_Object display)
4986 return intern ("not-useful");
4989 DEFUN ("x-display-visual-class", Fx_display_visual_class,
4990 Sx_display_visual_class, 0, 1, 0,
4991 doc: /* Return the visual class of DISPLAY.
4992 The value is one of the symbols `static-gray', `gray-scale',
4993 `static-color', `pseudo-color', `true-color', or `direct-color'.
4995 The optional argument DISPLAY specifies which display to ask about.
4996 DISPLAY should be either a frame or a display name (a string).
4997 If omitted or nil, that stands for the selected frame's display. */)
4998 (Lisp_Object display)
5000 struct w32_display_info *dpyinfo = check_x_display_info (display);
5001 Lisp_Object result = Qnil;
5003 if (dpyinfo->has_palette)
5004 result = intern ("pseudo-color");
5005 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
5006 result = intern ("static-grey");
5007 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5008 result = intern ("static-color");
5009 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5010 result = intern ("true-color");
5012 return result;
5015 DEFUN ("x-display-save-under", Fx_display_save_under,
5016 Sx_display_save_under, 0, 1, 0,
5017 doc: /* Return t if DISPLAY supports the save-under feature.
5018 The optional argument DISPLAY specifies which display to ask about.
5019 DISPLAY should be either a frame or a display name (a string).
5020 If omitted or nil, that stands for the selected frame's display. */)
5021 (Lisp_Object display)
5023 return Qnil;
5026 static BOOL CALLBACK ALIGN_STACK
5027 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5029 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5031 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5033 return TRUE;
5036 static Lisp_Object
5037 w32_display_monitor_attributes_list (void)
5039 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5040 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5041 int i, n_monitors;
5042 HMONITOR *monitors;
5043 struct gcpro gcpro1, gcpro2, gcpro3;
5045 if (!(enum_display_monitors_fn && get_monitor_info_fn
5046 && monitor_from_window_fn))
5047 return Qnil;
5049 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5050 (LPARAM) &monitor_list)
5051 || NILP (monitor_list))
5052 return Qnil;
5054 n_monitors = 0;
5055 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5056 n_monitors++;
5058 monitors = xmalloc (n_monitors * sizeof (*monitors));
5059 for (i = 0; i < n_monitors; i++)
5061 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5062 monitor_list = XCDR (monitor_list);
5065 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5066 FOR_EACH_FRAME (rest, frame)
5068 struct frame *f = XFRAME (frame);
5070 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5072 HMONITOR monitor =
5073 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5074 MONITOR_DEFAULT_TO_NEAREST);
5076 for (i = 0; i < n_monitors; i++)
5077 if (monitors[i] == monitor)
5078 break;
5080 if (i < n_monitors)
5081 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5085 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5087 for (i = 0; i < n_monitors; i++)
5089 Lisp_Object geometry, workarea, name, attributes = Qnil;
5090 HDC hdc;
5091 int width_mm, height_mm;
5092 struct MONITOR_INFO_EX mi;
5094 mi.cbSize = sizeof (mi);
5095 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5096 continue;
5098 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5099 if (hdc == NULL)
5100 continue;
5101 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5102 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5103 DeleteDC (hdc);
5105 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5106 attributes);
5108 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5110 attributes = Fcons (Fcons (Qname, name), attributes);
5112 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5113 attributes);
5115 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5116 mi.rcWork.right - mi.rcWork.left,
5117 mi.rcWork.bottom - mi.rcWork.top);
5118 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5120 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5121 mi.rcMonitor.right - mi.rcMonitor.left,
5122 mi.rcMonitor.bottom - mi.rcMonitor.top);
5123 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5125 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5126 primary_monitor_attributes = attributes;
5127 else
5128 attributes_list = Fcons (attributes, attributes_list);
5131 if (!NILP (primary_monitor_attributes))
5132 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5134 UNGCPRO;
5136 xfree (monitors);
5138 return attributes_list;
5141 static Lisp_Object
5142 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5144 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5145 HDC hdc;
5146 double mm_per_pixel;
5147 int pixel_width, pixel_height, width_mm, height_mm;
5148 RECT workarea_rect;
5150 /* Fallback: treat (possibly) multiple physical monitors as if they
5151 formed a single monitor as a whole. This should provide a
5152 consistent result at least on single monitor environments. */
5153 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5154 attributes);
5156 frames = Qnil;
5157 FOR_EACH_FRAME (rest, frame)
5159 struct frame *f = XFRAME (frame);
5161 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5162 frames = Fcons (frame, frames);
5164 attributes = Fcons (Fcons (Qframes, frames), attributes);
5166 pixel_width = x_display_pixel_width (dpyinfo);
5167 pixel_height = x_display_pixel_height (dpyinfo);
5169 hdc = GetDC (NULL);
5170 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5171 / GetDeviceCaps (hdc, HORZRES));
5172 width_mm = pixel_width * mm_per_pixel + 0.5;
5173 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5174 / GetDeviceCaps (hdc, VERTRES));
5175 height_mm = pixel_height * mm_per_pixel + 0.5;
5176 ReleaseDC (NULL, hdc);
5177 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5178 attributes);
5180 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5181 we don't care. */
5182 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5183 GetSystemMetrics (SM_YVIRTUALSCREEN),
5184 pixel_width, pixel_height);
5185 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5186 workarea = list4i (workarea_rect.left, workarea_rect.top,
5187 workarea_rect.right - workarea_rect.left,
5188 workarea_rect.bottom - workarea_rect.top);
5189 else
5190 workarea = geometry;
5191 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5193 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5195 return list1 (attributes);
5198 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5199 Sw32_display_monitor_attributes_list,
5200 0, 1, 0,
5201 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5203 The optional argument DISPLAY specifies which display to ask about.
5204 DISPLAY should be either a frame or a display name (a string).
5205 If omitted or nil, that stands for the selected frame's display.
5207 Internal use only, use `display-monitor-attributes-list' instead. */)
5208 (Lisp_Object display)
5210 struct w32_display_info *dpyinfo = check_x_display_info (display);
5211 Lisp_Object attributes_list;
5213 block_input ();
5214 attributes_list = w32_display_monitor_attributes_list ();
5215 if (NILP (attributes_list))
5216 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5217 unblock_input ();
5219 return attributes_list;
5222 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5223 doc: /* Set the sound generated when the bell is rung.
5224 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5225 to use the corresponding system sound for the bell. The 'silent sound
5226 prevents Emacs from making any sound at all.
5227 SOUND is nil to use the normal beep. */)
5228 (Lisp_Object sound)
5230 CHECK_SYMBOL (sound);
5232 if (NILP (sound))
5233 sound_type = 0xFFFFFFFF;
5234 else if (EQ (sound, intern ("asterisk")))
5235 sound_type = MB_ICONASTERISK;
5236 else if (EQ (sound, intern ("exclamation")))
5237 sound_type = MB_ICONEXCLAMATION;
5238 else if (EQ (sound, intern ("hand")))
5239 sound_type = MB_ICONHAND;
5240 else if (EQ (sound, intern ("question")))
5241 sound_type = MB_ICONQUESTION;
5242 else if (EQ (sound, intern ("ok")))
5243 sound_type = MB_OK;
5244 else if (EQ (sound, intern ("silent")))
5245 sound_type = MB_EMACS_SILENT;
5246 else
5247 sound_type = 0xFFFFFFFF;
5249 return sound;
5253 x_screen_planes (register struct frame *f)
5255 return FRAME_DISPLAY_INFO (f)->n_planes;
5258 /* Return the display structure for the display named NAME.
5259 Open a new connection if necessary. */
5261 struct w32_display_info *
5262 x_display_info_for_name (Lisp_Object name)
5264 struct w32_display_info *dpyinfo;
5266 CHECK_STRING (name);
5268 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5269 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5270 return dpyinfo;
5272 /* Use this general default value to start with. */
5273 Vx_resource_name = Vinvocation_name;
5275 validate_x_resource_name ();
5277 dpyinfo = w32_term_init (name, (unsigned char *)0,
5278 SSDATA (Vx_resource_name));
5280 if (dpyinfo == 0)
5281 error ("Cannot connect to server %s", SDATA (name));
5283 XSETFASTINT (Vwindow_system_version, w32_major_version);
5285 return dpyinfo;
5288 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5289 1, 3, 0, doc: /* Open a connection to a display server.
5290 DISPLAY is the name of the display to connect to.
5291 Optional second arg XRM-STRING is a string of resources in xrdb format.
5292 If the optional third arg MUST-SUCCEED is non-nil,
5293 terminate Emacs if we can't open the connection.
5294 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5295 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5297 unsigned char *xrm_option;
5298 struct w32_display_info *dpyinfo;
5300 CHECK_STRING (display);
5302 /* Signal an error in order to encourage correct use from callers.
5303 * If we ever support multiple window systems in the same Emacs,
5304 * we'll need callers to be precise about what window system they
5305 * want. */
5307 if (strcmp (SSDATA (display), "w32") != 0)
5308 error ("The name of the display in this Emacs must be \"w32\"");
5310 /* If initialization has already been done, return now to avoid
5311 overwriting critical parts of one_w32_display_info. */
5312 if (window_system_available (NULL))
5313 return Qnil;
5315 if (! NILP (xrm_string))
5316 CHECK_STRING (xrm_string);
5318 /* Allow color mapping to be defined externally; first look in user's
5319 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5321 Lisp_Object color_file;
5322 struct gcpro gcpro1;
5324 color_file = build_string ("~/rgb.txt");
5326 GCPRO1 (color_file);
5328 if (NILP (Ffile_readable_p (color_file)))
5329 color_file =
5330 Fexpand_file_name (build_string ("rgb.txt"),
5331 Fsymbol_value (intern ("data-directory")));
5333 Vw32_color_map = Fx_load_color_file (color_file);
5335 UNGCPRO;
5337 if (NILP (Vw32_color_map))
5338 Vw32_color_map = w32_default_color_map ();
5340 /* Merge in system logical colors. */
5341 add_system_logical_colors_to_map (&Vw32_color_map);
5343 if (! NILP (xrm_string))
5344 xrm_option = SDATA (xrm_string);
5345 else
5346 xrm_option = (unsigned char *) 0;
5348 /* Use this general default value to start with. */
5349 /* First remove .exe suffix from invocation-name - it looks ugly. */
5351 char basename[ MAX_PATH ], *str;
5353 lispstpcpy (basename, Vinvocation_name);
5354 str = strrchr (basename, '.');
5355 if (str) *str = 0;
5356 Vinvocation_name = build_string (basename);
5358 Vx_resource_name = Vinvocation_name;
5360 validate_x_resource_name ();
5362 /* This is what opens the connection and sets x_current_display.
5363 This also initializes many symbols, such as those used for input. */
5364 dpyinfo = w32_term_init (display, xrm_option,
5365 SSDATA (Vx_resource_name));
5367 if (dpyinfo == 0)
5369 if (!NILP (must_succeed))
5370 fatal ("Cannot connect to server %s.\n",
5371 SDATA (display));
5372 else
5373 error ("Cannot connect to server %s", SDATA (display));
5376 XSETFASTINT (Vwindow_system_version, w32_major_version);
5377 return Qnil;
5380 DEFUN ("x-close-connection", Fx_close_connection,
5381 Sx_close_connection, 1, 1, 0,
5382 doc: /* Close the connection to DISPLAY's server.
5383 For DISPLAY, specify either a frame or a display name (a string).
5384 If DISPLAY is nil, that stands for the selected frame's display. */)
5385 (Lisp_Object display)
5387 struct w32_display_info *dpyinfo = check_x_display_info (display);
5389 if (dpyinfo->reference_count > 0)
5390 error ("Display still has frames on it");
5392 block_input ();
5393 x_destroy_all_bitmaps (dpyinfo);
5395 x_delete_display (dpyinfo);
5396 unblock_input ();
5398 return Qnil;
5401 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5402 doc: /* Return the list of display names that Emacs has connections to. */)
5403 (void)
5405 Lisp_Object result = Qnil;
5406 struct w32_display_info *wdi;
5408 for (wdi = x_display_list; wdi; wdi = wdi->next)
5409 result = Fcons (XCAR (wdi->name_list_element), result);
5411 return result;
5414 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5415 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5416 This function only has an effect on X Windows. With MS Windows, it is
5417 defined but does nothing.
5419 If ON is nil, allow buffering of requests.
5420 Turning on synchronization prohibits the Xlib routines from buffering
5421 requests and seriously degrades performance, but makes debugging much
5422 easier.
5423 The optional second argument TERMINAL specifies which display to act on.
5424 TERMINAL should be a terminal object, a frame or a display name (a string).
5425 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5426 (Lisp_Object on, Lisp_Object display)
5428 return Qnil;
5433 /***********************************************************************
5434 Window properties
5435 ***********************************************************************/
5437 #if 0 /* TODO : port window properties to W32 */
5439 DEFUN ("x-change-window-property", Fx_change_window_property,
5440 Sx_change_window_property, 2, 6, 0,
5441 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5442 PROP must be a string. VALUE may be a string or a list of conses,
5443 numbers and/or strings. If an element in the list is a string, it is
5444 converted to an atom and the value of the Atom is used. If an element
5445 is a cons, it is converted to a 32 bit number where the car is the 16
5446 top bits and the cdr is the lower 16 bits.
5448 FRAME nil or omitted means use the selected frame.
5449 If TYPE is given and non-nil, it is the name of the type of VALUE.
5450 If TYPE is not given or nil, the type is STRING.
5451 FORMAT gives the size in bits of each element if VALUE is a list.
5452 It must be one of 8, 16 or 32.
5453 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
5454 If OUTER-P is non-nil, the property is changed for the outer X window of
5455 FRAME. Default is to change on the edit X window. */)
5456 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5457 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
5459 struct frame *f = decode_window_system_frame (frame);
5460 Atom prop_atom;
5462 CHECK_STRING (prop);
5463 CHECK_STRING (value);
5465 block_input ();
5466 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5467 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5468 prop_atom, XA_STRING, 8, PropModeReplace,
5469 SDATA (value), SCHARS (value));
5471 /* Make sure the property is set when we return. */
5472 XFlush (FRAME_W32_DISPLAY (f));
5473 unblock_input ();
5475 return value;
5479 DEFUN ("x-delete-window-property", Fx_delete_window_property,
5480 Sx_delete_window_property, 1, 2, 0,
5481 doc: /* Remove window property PROP from X window of FRAME.
5482 FRAME nil or omitted means use the selected frame. Value is PROP. */)
5483 (Lisp_Object prop, Lisp_Object frame)
5485 struct frame *f = decode_window_system_frame (frame);
5486 Atom prop_atom;
5488 CHECK_STRING (prop);
5489 block_input ();
5490 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5491 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
5493 /* Make sure the property is removed when we return. */
5494 XFlush (FRAME_W32_DISPLAY (f));
5495 unblock_input ();
5497 return prop;
5501 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
5502 1, 6, 0,
5503 doc: /* Value is the value of window property PROP on FRAME.
5504 If FRAME is nil or omitted, use the selected frame.
5506 On X Windows, the following optional arguments are also accepted:
5507 If TYPE is nil or omitted, get the property as a string.
5508 Otherwise TYPE is the name of the atom that denotes the type expected.
5509 If SOURCE is non-nil, get the property on that window instead of from
5510 FRAME. The number 0 denotes the root window.
5511 If DELETE-P is non-nil, delete the property after retrieving it.
5512 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5514 On MS Windows, this function accepts but ignores those optional arguments.
5516 Value is nil if FRAME hasn't a property with name PROP or if PROP has
5517 no value of TYPE (always string in the MS Windows case). */)
5518 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5519 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
5521 struct frame *f = decode_window_system_frame (frame);
5522 Atom prop_atom;
5523 int rc;
5524 Lisp_Object prop_value = Qnil;
5525 char *tmp_data = NULL;
5526 Atom actual_type;
5527 int actual_format;
5528 unsigned long actual_size, bytes_remaining;
5530 CHECK_STRING (prop);
5531 block_input ();
5532 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5533 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5534 prop_atom, 0, 0, False, XA_STRING,
5535 &actual_type, &actual_format, &actual_size,
5536 &bytes_remaining, (unsigned char **) &tmp_data);
5537 if (rc == Success)
5539 int size = bytes_remaining;
5541 XFree (tmp_data);
5542 tmp_data = NULL;
5544 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5545 prop_atom, 0, bytes_remaining,
5546 False, XA_STRING,
5547 &actual_type, &actual_format,
5548 &actual_size, &bytes_remaining,
5549 (unsigned char **) &tmp_data);
5550 if (rc == Success)
5551 prop_value = make_string (tmp_data, size);
5553 XFree (tmp_data);
5556 unblock_input ();
5558 return prop_value;
5560 return Qnil;
5563 #endif /* TODO */
5565 /***********************************************************************
5566 Tool tips
5567 ***********************************************************************/
5569 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5570 Lisp_Object, Lisp_Object);
5571 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5572 Lisp_Object, int, int, int *, int *);
5574 /* The frame of a currently visible tooltip. */
5576 Lisp_Object tip_frame;
5578 /* If non-nil, a timer started that hides the last tooltip when it
5579 fires. */
5581 Lisp_Object tip_timer;
5582 Window tip_window;
5584 /* If non-nil, a vector of 3 elements containing the last args
5585 with which x-show-tip was called. See there. */
5587 Lisp_Object last_show_tip_args;
5590 static void
5591 unwind_create_tip_frame (Lisp_Object frame)
5593 Lisp_Object deleted;
5595 deleted = unwind_create_frame (frame);
5596 if (EQ (deleted, Qt))
5598 tip_window = NULL;
5599 tip_frame = Qnil;
5604 /* Create a frame for a tooltip on the display described by DPYINFO.
5605 PARMS is a list of frame parameters. TEXT is the string to
5606 display in the tip frame. Value is the frame.
5608 Note that functions called here, esp. x_default_parameter can
5609 signal errors, for instance when a specified color name is
5610 undefined. We have to make sure that we're in a consistent state
5611 when this happens. */
5613 static Lisp_Object
5614 x_create_tip_frame (struct w32_display_info *dpyinfo,
5615 Lisp_Object parms, Lisp_Object text)
5617 struct frame *f;
5618 Lisp_Object frame;
5619 Lisp_Object name;
5620 long window_prompting = 0;
5621 int width, height;
5622 ptrdiff_t count = SPECPDL_INDEX ();
5623 struct gcpro gcpro1, gcpro2, gcpro3;
5624 struct kboard *kb;
5625 int face_change_count_before = face_change_count;
5626 Lisp_Object buffer;
5627 struct buffer *old_buffer;
5629 /* Use this general default value to start with until we know if
5630 this frame has a specified name. */
5631 Vx_resource_name = Vinvocation_name;
5633 kb = dpyinfo->terminal->kboard;
5635 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5636 avoid destructive changes behind our caller's back. */
5637 parms = Fcopy_alist (parms);
5639 /* Get the name of the frame to use for resource lookup. */
5640 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
5641 if (!STRINGP (name)
5642 && !EQ (name, Qunbound)
5643 && !NILP (name))
5644 error ("Invalid frame name--not a string or nil");
5645 Vx_resource_name = name;
5647 frame = Qnil;
5648 GCPRO3 (parms, name, frame);
5649 /* Make a frame without minibuffer nor mode-line. */
5650 f = make_frame (0);
5651 f->wants_modeline = 0;
5652 XSETFRAME (frame, f);
5654 AUTO_STRING (tip, " *tip*");
5655 buffer = Fget_buffer_create (tip);
5656 /* Use set_window_buffer instead of Fset_window_buffer (see
5657 discussion of bug#11984, bug#12025, bug#12026). */
5658 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, 0, 0);
5659 old_buffer = current_buffer;
5660 set_buffer_internal_1 (XBUFFER (buffer));
5661 bset_truncate_lines (current_buffer, Qnil);
5662 specbind (Qinhibit_read_only, Qt);
5663 specbind (Qinhibit_modification_hooks, Qt);
5664 Ferase_buffer ();
5665 Finsert (1, &text);
5666 set_buffer_internal_1 (old_buffer);
5668 record_unwind_protect (unwind_create_tip_frame, frame);
5670 /* By setting the output method, we're essentially saying that
5671 the frame is live, as per FRAME_LIVE_P. If we get a signal
5672 from this point on, x_destroy_window might screw up reference
5673 counts etc. */
5674 f->terminal = dpyinfo->terminal;
5675 f->output_method = output_w32;
5676 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5678 FRAME_FONTSET (f) = -1;
5679 fset_icon_name (f, Qnil);
5681 #ifdef GLYPH_DEBUG
5682 image_cache_refcount =
5683 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5684 dpyinfo_refcount = dpyinfo->reference_count;
5685 #endif /* GLYPH_DEBUG */
5686 FRAME_KBOARD (f) = kb;
5687 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5688 f->output_data.w32->explicit_parent = 0;
5690 /* Set the name; the functions to which we pass f expect the name to
5691 be set. */
5692 if (EQ (name, Qunbound) || NILP (name))
5694 fset_name (f, build_string (dpyinfo->w32_id_name));
5695 f->explicit_name = 0;
5697 else
5699 fset_name (f, name);
5700 f->explicit_name = 1;
5701 /* use the frame's title when getting resources for this frame. */
5702 specbind (Qx_resource_name, name);
5705 if (uniscribe_available)
5706 register_font_driver (&uniscribe_font_driver, f);
5707 register_font_driver (&w32font_driver, f);
5709 x_default_parameter (f, parms, Qfont_backend, Qnil,
5710 "fontBackend", "FontBackend", RES_TYPE_STRING);
5712 /* Extract the window parameters from the supplied values
5713 that are needed to determine window geometry. */
5714 x_default_font_parameter (f, parms);
5716 x_default_parameter (f, parms, Qborder_width, make_number (2),
5717 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5718 /* This defaults to 2 in order to match xterm. We recognize either
5719 internalBorderWidth or internalBorder (which is what xterm calls
5720 it). */
5721 if (NILP (Fassq (Qinternal_border_width, parms)))
5723 Lisp_Object value;
5725 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
5726 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5727 if (! EQ (value, Qunbound))
5728 parms = Fcons (Fcons (Qinternal_border_width, value),
5729 parms);
5731 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
5732 "internalBorderWidth", "internalBorderWidth",
5733 RES_TYPE_NUMBER);
5734 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5735 NULL, NULL, RES_TYPE_NUMBER);
5736 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5737 NULL, NULL, RES_TYPE_NUMBER);
5739 /* Also do the stuff which must be set before the window exists. */
5740 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5741 "foreground", "Foreground", RES_TYPE_STRING);
5742 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5743 "background", "Background", RES_TYPE_STRING);
5744 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5745 "pointerColor", "Foreground", RES_TYPE_STRING);
5746 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5747 "cursorColor", "Foreground", RES_TYPE_STRING);
5748 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5749 "borderColor", "BorderColor", RES_TYPE_STRING);
5750 x_default_parameter (f, parms, Qalpha, Qnil,
5751 "alpha", "Alpha", RES_TYPE_NUMBER);
5753 /* Init faces before x_default_parameter is called for the
5754 scroll-bar-width parameter because otherwise we end up in
5755 init_iterator with a null face cache, which should not happen. */
5756 init_frame_faces (f);
5758 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
5759 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5761 window_prompting = x_figure_window_size (f, parms, 0);
5763 /* No fringes on tip frame. */
5764 f->fringe_cols = 0;
5765 f->left_fringe_width = 0;
5766 f->right_fringe_width = 0;
5768 block_input ();
5769 my_create_tip_window (f);
5770 unblock_input ();
5772 x_make_gc (f);
5774 x_default_parameter (f, parms, Qauto_raise, Qnil,
5775 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5776 x_default_parameter (f, parms, Qauto_lower, Qnil,
5777 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5778 x_default_parameter (f, parms, Qcursor_type, Qbox,
5779 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5781 /* Dimensions, especially FRAME_LINES (f), must be done via
5782 change_frame_size. Change will not be effected unless different
5783 from the current FRAME_LINES (f). */
5784 width = FRAME_COLS (f);
5785 height = FRAME_LINES (f);
5786 SET_FRAME_COLS (f, 0);
5787 SET_FRAME_LINES (f, 0);
5788 adjust_frame_size (f, width * FRAME_COLUMN_WIDTH (f),
5789 height * FRAME_LINE_HEIGHT (f), 0, 1, Qnil);
5791 /* Add `tooltip' frame parameter's default value. */
5792 if (NILP (Fframe_parameter (frame, Qtooltip)))
5793 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
5795 /* Set up faces after all frame parameters are known. This call
5796 also merges in face attributes specified for new frames.
5798 Frame parameters may be changed if .Xdefaults contains
5799 specifications for the default font. For example, if there is an
5800 `Emacs.default.attributeBackground: pink', the `background-color'
5801 attribute of the frame get's set, which let's the internal border
5802 of the tooltip frame appear in pink. Prevent this. */
5804 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
5805 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5806 Lisp_Object colors = Qnil;
5808 /* Set tip_frame here, so that */
5809 tip_frame = frame;
5810 call2 (Qface_set_after_frame_default, frame, Qnil);
5812 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
5813 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5814 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5815 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5817 if (!NILP (colors))
5818 Fmodify_frame_parameters (frame, colors);
5821 f->no_split = 1;
5823 UNGCPRO;
5825 /* Now that the frame is official, it counts as a reference to
5826 its display. */
5827 FRAME_DISPLAY_INFO (f)->reference_count++;
5828 f->terminal->reference_count++;
5830 /* It is now ok to make the frame official even if we get an error
5831 below. And the frame needs to be on Vframe_list or making it
5832 visible won't work. */
5833 Vframe_list = Fcons (frame, Vframe_list);
5834 f->can_x_set_window_size = true;
5836 /* Setting attributes of faces of the tooltip frame from resources
5837 and similar will increment face_change_count, which leads to the
5838 clearing of all current matrices. Since this isn't necessary
5839 here, avoid it by resetting face_change_count to the value it
5840 had before we created the tip frame. */
5841 face_change_count = face_change_count_before;
5843 /* Discard the unwind_protect. */
5844 return unbind_to (count, frame);
5848 /* Compute where to display tip frame F. PARMS is the list of frame
5849 parameters for F. DX and DY are specified offsets from the current
5850 location of the mouse. WIDTH and HEIGHT are the width and height
5851 of the tooltip. Return coordinates relative to the root window of
5852 the display in *ROOT_X, and *ROOT_Y. */
5854 static void
5855 compute_tip_xy (struct frame *f,
5856 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5857 int width, int height, int *root_x, int *root_y)
5859 Lisp_Object left, top;
5860 int min_x, min_y, max_x, max_y;
5862 /* User-specified position? */
5863 left = Fcdr (Fassq (Qleft, parms));
5864 top = Fcdr (Fassq (Qtop, parms));
5866 /* Move the tooltip window where the mouse pointer is. Resize and
5867 show it. */
5868 if (!INTEGERP (left) || !INTEGERP (top))
5870 POINT pt;
5872 /* Default min and max values. */
5873 min_x = 0;
5874 min_y = 0;
5875 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5876 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
5878 block_input ();
5879 GetCursorPos (&pt);
5880 *root_x = pt.x;
5881 *root_y = pt.y;
5882 unblock_input ();
5884 /* If multiple monitor support is available, constrain the tip onto
5885 the current monitor. This improves the above by allowing negative
5886 co-ordinates if monitor positions are such that they are valid, and
5887 snaps a tooltip onto a single monitor if we are close to the edge
5888 where it would otherwise flow onto the other monitor (or into
5889 nothingness if there is a gap in the overlap). */
5890 if (monitor_from_point_fn && get_monitor_info_fn)
5892 struct MONITOR_INFO info;
5893 HMONITOR monitor
5894 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5895 info.cbSize = sizeof (info);
5897 if (get_monitor_info_fn (monitor, &info))
5899 min_x = info.rcWork.left;
5900 min_y = info.rcWork.top;
5901 max_x = info.rcWork.right;
5902 max_y = info.rcWork.bottom;
5907 if (INTEGERP (top))
5908 *root_y = XINT (top);
5909 else if (*root_y + XINT (dy) <= min_y)
5910 *root_y = min_y; /* Can happen for negative dy */
5911 else if (*root_y + XINT (dy) + height <= max_y)
5912 /* It fits below the pointer */
5913 *root_y += XINT (dy);
5914 else if (height + XINT (dy) + min_y <= *root_y)
5915 /* It fits above the pointer. */
5916 *root_y -= height + XINT (dy);
5917 else
5918 /* Put it on the top. */
5919 *root_y = min_y;
5921 if (INTEGERP (left))
5922 *root_x = XINT (left);
5923 else if (*root_x + XINT (dx) <= min_x)
5924 *root_x = 0; /* Can happen for negative dx */
5925 else if (*root_x + XINT (dx) + width <= max_x)
5926 /* It fits to the right of the pointer. */
5927 *root_x += XINT (dx);
5928 else if (width + XINT (dx) + min_x <= *root_x)
5929 /* It fits to the left of the pointer. */
5930 *root_x -= width + XINT (dx);
5931 else
5932 /* Put it left justified on the screen -- it ought to fit that way. */
5933 *root_x = min_x;
5937 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
5938 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
5939 A tooltip window is a small window displaying a string.
5941 This is an internal function; Lisp code should call `tooltip-show'.
5943 FRAME nil or omitted means use the selected frame.
5945 PARMS is an optional list of frame parameters which can be
5946 used to change the tooltip's appearance.
5948 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
5949 means use the default timeout of 5 seconds.
5951 If the list of frame parameters PARMS contains a `left' parameter,
5952 the tooltip is displayed at that x-position. Otherwise it is
5953 displayed at the mouse position, with offset DX added (default is 5 if
5954 DX isn't specified). Likewise for the y-position; if a `top' frame
5955 parameter is specified, it determines the y-position of the tooltip
5956 window, otherwise it is displayed at the mouse position, with offset
5957 DY added (default is -10).
5959 A tooltip's maximum size is specified by `x-max-tooltip-size'.
5960 Text larger than the specified size is clipped. */)
5961 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
5963 struct frame *f;
5964 struct window *w;
5965 int root_x, root_y;
5966 struct buffer *old_buffer;
5967 struct text_pos pos;
5968 int i, width, height, seen_reversed_p;
5969 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5970 int old_windows_or_buffers_changed = windows_or_buffers_changed;
5971 ptrdiff_t count = SPECPDL_INDEX ();
5973 specbind (Qinhibit_redisplay, Qt);
5975 GCPRO4 (string, parms, frame, timeout);
5977 CHECK_STRING (string);
5978 f = decode_window_system_frame (frame);
5979 if (NILP (timeout))
5980 timeout = make_number (5);
5981 else
5982 CHECK_NATNUM (timeout);
5984 if (NILP (dx))
5985 dx = make_number (5);
5986 else
5987 CHECK_NUMBER (dx);
5989 if (NILP (dy))
5990 dy = make_number (-10);
5991 else
5992 CHECK_NUMBER (dy);
5994 if (NILP (last_show_tip_args))
5995 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
5997 if (!NILP (tip_frame))
5999 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6000 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6001 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6003 if (EQ (frame, last_frame)
6004 && !NILP (Fequal (last_string, string))
6005 && !NILP (Fequal (last_parms, parms)))
6007 struct frame *f = XFRAME (tip_frame);
6009 /* Only DX and DY have changed. */
6010 if (!NILP (tip_timer))
6012 Lisp_Object timer = tip_timer;
6013 tip_timer = Qnil;
6014 call1 (Qcancel_timer, timer);
6017 block_input ();
6018 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6019 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6021 /* Put tooltip in topmost group and in position. */
6022 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6023 root_x, root_y, 0, 0,
6024 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6026 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6027 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6028 0, 0, 0, 0,
6029 SWP_NOMOVE | SWP_NOSIZE
6030 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6032 unblock_input ();
6033 goto start_timer;
6037 /* Hide a previous tip, if any. */
6038 Fx_hide_tip ();
6040 ASET (last_show_tip_args, 0, string);
6041 ASET (last_show_tip_args, 1, frame);
6042 ASET (last_show_tip_args, 2, parms);
6044 /* Add default values to frame parameters. */
6045 if (NILP (Fassq (Qname, parms)))
6046 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6047 if (NILP (Fassq (Qinternal_border_width, parms)))
6048 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6049 if (NILP (Fassq (Qright_divider_width, parms)))
6050 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6051 if (NILP (Fassq (Qbottom_divider_width, parms)))
6052 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6053 if (NILP (Fassq (Qborder_width, parms)))
6054 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6055 if (NILP (Fassq (Qborder_color, parms)))
6056 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6057 if (NILP (Fassq (Qbackground_color, parms)))
6058 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6059 parms);
6061 /* Block input until the tip has been fully drawn, to avoid crashes
6062 when drawing tips in menus. */
6063 block_input ();
6065 /* Create a frame for the tooltip, and record it in the global
6066 variable tip_frame. */
6067 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6068 f = XFRAME (frame);
6070 /* Set up the frame's root window. */
6071 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6072 w->left_col = 0;
6073 w->top_line = 0;
6074 w->pixel_left = 0;
6075 w->pixel_top = 0;
6077 if (CONSP (Vx_max_tooltip_size)
6078 && INTEGERP (XCAR (Vx_max_tooltip_size))
6079 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6080 && INTEGERP (XCDR (Vx_max_tooltip_size))
6081 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6083 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6084 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6086 else
6088 w->total_cols = 80;
6089 w->total_lines = 40;
6092 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6093 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6095 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6096 adjust_frame_glyphs (f);
6097 w->pseudo_window_p = 1;
6099 /* Display the tooltip text in a temporary buffer. */
6100 old_buffer = current_buffer;
6101 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6102 bset_truncate_lines (current_buffer, Qnil);
6103 clear_glyph_matrix (w->desired_matrix);
6104 clear_glyph_matrix (w->current_matrix);
6105 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6106 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6108 /* Compute width and height of the tooltip. */
6109 width = height = seen_reversed_p = 0;
6110 for (i = 0; i < w->desired_matrix->nrows; ++i)
6112 struct glyph_row *row = &w->desired_matrix->rows[i];
6113 struct glyph *last;
6114 int row_width;
6116 /* Stop at the first empty row at the end. */
6117 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6118 break;
6120 /* Let the row go over the full width of the frame. */
6121 row->full_width_p = 1;
6123 row_width = row->pixel_width;
6124 if (row->used[TEXT_AREA])
6126 if (!row->reversed_p)
6128 /* There's a glyph at the end of rows that is used to
6129 place the cursor there. Don't include the width of
6130 this glyph. */
6131 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6132 if (NILP (last->object))
6133 row_width -= last->pixel_width;
6135 else
6137 /* There could be a stretch glyph at the beginning of R2L
6138 rows that is produced by extend_face_to_end_of_line.
6139 Don't count that glyph. */
6140 struct glyph *g = row->glyphs[TEXT_AREA];
6142 if (g->type == STRETCH_GLYPH && NILP (g->object))
6144 row_width -= g->pixel_width;
6145 seen_reversed_p = 1;
6150 height += row->height;
6151 width = max (width, row_width);
6154 /* If we've seen partial-length R2L rows, we need to re-adjust the
6155 tool-tip frame width and redisplay it again, to avoid over-wide
6156 tips due to the stretch glyph that extends R2L lines to full
6157 width of the frame. */
6158 if (seen_reversed_p)
6160 /* PXW: Why do we do the pixel-to-cols conversion only if
6161 seen_reversed_p holds? Don't we have to set other fields of
6162 the window/frame structure?
6164 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6165 not in pixels. */
6166 w->pixel_width = width;
6167 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6168 w->total_cols = width;
6169 FRAME_TOTAL_COLS (f) = width;
6170 SET_FRAME_WIDTH (f, width);
6171 adjust_frame_glyphs (f);
6172 w->pseudo_window_p = 1;
6173 clear_glyph_matrix (w->desired_matrix);
6174 clear_glyph_matrix (w->current_matrix);
6175 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6176 width = height = 0;
6177 /* Recompute width and height of the tooltip. */
6178 for (i = 0; i < w->desired_matrix->nrows; ++i)
6180 struct glyph_row *row = &w->desired_matrix->rows[i];
6181 struct glyph *last;
6182 int row_width;
6184 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6185 break;
6186 row->full_width_p = 1;
6187 row_width = row->pixel_width;
6188 if (row->used[TEXT_AREA] && !row->reversed_p)
6190 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6191 if (NILP (last->object))
6192 row_width -= last->pixel_width;
6195 height += row->height;
6196 width = max (width, row_width);
6200 /* Add the frame's internal border to the width and height the w32
6201 window should have. */
6202 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6203 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6205 /* Move the tooltip window where the mouse pointer is. Resize and
6206 show it.
6208 PXW: This should use the frame's pixel coordinates. */
6209 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6212 /* Adjust Window size to take border into account. */
6213 RECT rect;
6214 rect.left = rect.top = 0;
6215 rect.right = width;
6216 rect.bottom = height;
6217 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6218 FRAME_EXTERNAL_MENU_BAR (f));
6220 /* Position and size tooltip, and put it in the topmost group.
6221 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6222 peculiarity of w32 display: without it, some fonts cause the
6223 last character of the tip to be truncated or wrapped around to
6224 the next line. */
6225 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6226 root_x, root_y,
6227 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6228 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6230 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6231 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6232 0, 0, 0, 0,
6233 SWP_NOMOVE | SWP_NOSIZE
6234 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6236 /* Let redisplay know that we have made the frame visible already. */
6237 SET_FRAME_VISIBLE (f, 1);
6239 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6242 /* Draw into the window. */
6243 w->must_be_updated_p = true;
6244 update_single_window (w);
6246 unblock_input ();
6248 /* Restore original current buffer. */
6249 set_buffer_internal_1 (old_buffer);
6250 windows_or_buffers_changed = old_windows_or_buffers_changed;
6252 start_timer:
6253 /* Let the tip disappear after timeout seconds. */
6254 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6255 intern ("x-hide-tip"));
6257 UNGCPRO;
6258 return unbind_to (count, Qnil);
6262 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6263 doc: /* Hide the current tooltip window, if there is any.
6264 Value is t if tooltip was open, nil otherwise. */)
6265 (void)
6267 ptrdiff_t count;
6268 Lisp_Object deleted, frame, timer;
6269 struct gcpro gcpro1, gcpro2;
6271 /* Return quickly if nothing to do. */
6272 if (NILP (tip_timer) && NILP (tip_frame))
6273 return Qnil;
6275 frame = tip_frame;
6276 timer = tip_timer;
6277 GCPRO2 (frame, timer);
6278 tip_frame = tip_timer = deleted = Qnil;
6280 count = SPECPDL_INDEX ();
6281 specbind (Qinhibit_redisplay, Qt);
6282 specbind (Qinhibit_quit, Qt);
6284 if (!NILP (timer))
6285 call1 (Qcancel_timer, timer);
6287 if (FRAMEP (frame))
6289 delete_frame (frame, Qnil);
6290 deleted = Qt;
6293 UNGCPRO;
6294 return unbind_to (count, deleted);
6297 /***********************************************************************
6298 File selection dialog
6299 ***********************************************************************/
6301 #define FILE_NAME_TEXT_FIELD edt1
6302 #define FILE_NAME_COMBO_BOX cmb13
6303 #define FILE_NAME_LIST lst1
6305 /* Callback for altering the behavior of the Open File dialog.
6306 Makes the Filename text field contain "Current Directory" and be
6307 read-only when "Directories" is selected in the filter. This
6308 allows us to work around the fact that the standard Open File
6309 dialog does not support directories. */
6310 static UINT_PTR CALLBACK
6311 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6313 if (msg == WM_NOTIFY)
6315 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6316 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6317 int dropdown_changed;
6318 int dir_index;
6319 #ifdef NTGUI_UNICODE
6320 const int use_unicode = 1;
6321 #else /* !NTGUI_UNICODE */
6322 int use_unicode = w32_unicode_filenames;
6323 #endif /* NTGUI_UNICODE */
6325 /* Detect when the Filter dropdown is changed. */
6326 if (use_unicode)
6327 dropdown_changed =
6328 notify_w->hdr.code == CDN_TYPECHANGE
6329 || notify_w->hdr.code == CDN_INITDONE;
6330 else
6331 dropdown_changed =
6332 notify_a->hdr.code == CDN_TYPECHANGE
6333 || notify_a->hdr.code == CDN_INITDONE;
6334 if (dropdown_changed)
6336 HWND dialog = GetParent (hwnd);
6337 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6338 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6339 int hdr_code;
6341 /* At least on Windows 7, the above attempt to get the window handle
6342 to the File Name Text Field fails. The following code does the
6343 job though. Note that this code is based on my examination of the
6344 window hierarchy using Microsoft Spy++. bk */
6345 if (edit_control == NULL)
6347 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6348 if (tmp)
6350 tmp = GetWindow (tmp, GW_CHILD);
6351 if (tmp)
6352 edit_control = GetWindow (tmp, GW_CHILD);
6356 /* Directories is in index 2. */
6357 if (use_unicode)
6359 dir_index = notify_w->lpOFN->nFilterIndex;
6360 hdr_code = notify_w->hdr.code;
6362 else
6364 dir_index = notify_a->lpOFN->nFilterIndex;
6365 hdr_code = notify_a->hdr.code;
6367 if (dir_index == 2)
6369 if (use_unicode)
6370 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6371 (LPARAM)L"Current Directory");
6372 else
6373 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6374 (LPARAM)"Current Directory");
6375 EnableWindow (edit_control, FALSE);
6376 /* Note that at least on Windows 7, the above call to EnableWindow
6377 disables the window that would ordinarily have focus. If we
6378 do not set focus to some other window here, focus will land in
6379 no man's land and the user will be unable to tab through the
6380 dialog box (pressing tab will only result in a beep).
6381 Avoid that problem by setting focus to the list here. */
6382 if (hdr_code == CDN_INITDONE)
6383 SetFocus (list);
6385 else
6387 /* Don't override default filename on init done. */
6388 if (hdr_code == CDN_TYPECHANGE)
6390 if (use_unicode)
6391 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6392 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6393 else
6394 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6395 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6397 EnableWindow (edit_control, TRUE);
6401 return 0;
6404 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6405 doc: /* Read file name, prompting with PROMPT in directory DIR.
6406 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6407 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6408 or directory must exist.
6410 This function is only defined on NS, MS Windows, and X Windows with the
6411 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6412 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6413 On Windows 7 and later, the file selection dialog "remembers" the last
6414 directory where the user selected a file, and will open that directory
6415 instead of DIR on subsequent invocations of this function with the same
6416 value of DIR as in previous invocations; this is standard Windows behavior. */)
6417 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6419 /* Filter index: 1: All Files, 2: Directories only */
6420 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6421 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6423 Lisp_Object filename = default_filename;
6424 struct frame *f = SELECTED_FRAME ();
6425 BOOL file_opened = FALSE;
6426 Lisp_Object orig_dir = dir;
6427 Lisp_Object orig_prompt = prompt;
6429 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6430 compatibility) we end up with the old file dialogs. Define a big
6431 enough struct for the new dialog to trick GetOpenFileName into
6432 giving us the new dialogs on newer versions of Windows. */
6433 struct {
6434 OPENFILENAMEW details;
6435 #if _WIN32_WINNT < 0x500 /* < win2k */
6436 PVOID pvReserved;
6437 DWORD dwReserved;
6438 DWORD FlagsEx;
6439 #endif /* < win2k */
6440 } new_file_details_w;
6442 #ifdef NTGUI_UNICODE
6443 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6444 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6445 const int use_unicode = 1;
6446 #else /* not NTGUI_UNICODE */
6447 struct {
6448 OPENFILENAMEA details;
6449 #if _WIN32_WINNT < 0x500 /* < win2k */
6450 PVOID pvReserved;
6451 DWORD dwReserved;
6452 DWORD FlagsEx;
6453 #endif /* < win2k */
6454 } new_file_details_a;
6455 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6456 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6457 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6458 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6459 int use_unicode = w32_unicode_filenames;
6460 wchar_t *prompt_w;
6461 char *prompt_a;
6462 int len;
6463 char fname_ret[MAX_UTF8_PATH];
6464 #endif /* NTGUI_UNICODE */
6466 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
6467 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
6470 struct gcpro gcpro1, gcpro2;
6471 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
6473 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6474 system file encoding expected by the platform APIs (e.g. Cygwin's
6475 POSIX implementation) may not be the same as the encoding expected
6476 by the Windows "ANSI" APIs! */
6478 CHECK_STRING (prompt);
6479 CHECK_STRING (dir);
6481 dir = Fexpand_file_name (dir, Qnil);
6483 if (STRINGP (filename))
6484 filename = Ffile_name_nondirectory (filename);
6485 else
6486 filename = empty_unibyte_string;
6488 #ifdef CYGWIN
6489 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
6490 if (SCHARS (filename) > 0)
6491 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
6492 #endif
6494 CHECK_STRING (dir);
6495 CHECK_STRING (filename);
6497 /* The code in file_dialog_callback that attempts to set the text
6498 of the file name edit window when handling the CDN_INITDONE
6499 WM_NOTIFY message does not work. Setting filename to "Current
6500 Directory" in the only_dir_p case here does work however. */
6501 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6502 filename = build_string ("Current Directory");
6504 /* Convert the values we've computed so far to system form. */
6505 #ifdef NTGUI_UNICODE
6506 to_unicode (prompt, &prompt);
6507 to_unicode (dir, &dir);
6508 to_unicode (filename, &filename);
6509 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6510 report_file_error ("filename too long", default_filename);
6512 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
6513 #else /* !NTGUI_UNICODE */
6514 prompt = ENCODE_FILE (prompt);
6515 dir = ENCODE_FILE (dir);
6516 filename = ENCODE_FILE (filename);
6518 /* We modify these in-place, so make copies for safety. */
6519 dir = Fcopy_sequence (dir);
6520 unixtodos_filename (SDATA (dir));
6521 filename = Fcopy_sequence (filename);
6522 unixtodos_filename (SDATA (filename));
6523 if (SBYTES (filename) >= MAX_UTF8_PATH)
6524 report_file_error ("filename too long", default_filename);
6525 if (w32_unicode_filenames)
6527 filename_to_utf16 (SSDATA (dir), dir_w);
6528 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6530 /* filename_to_utf16 sets errno to ENOENT when the file
6531 name is too long or cannot be converted to UTF-16. */
6532 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6533 report_file_error ("filename too long", default_filename);
6535 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6536 SSDATA (prompt), -1, NULL, 0);
6537 if (len > 32768)
6538 len = 32768;
6539 prompt_w = alloca (len * sizeof (wchar_t));
6540 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6541 SSDATA (prompt), -1, prompt_w, len);
6543 else
6545 filename_to_ansi (SSDATA (dir), dir_a);
6546 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6548 /* filename_to_ansi sets errno to ENOENT when the file
6549 name is too long or cannot be converted to UTF-16. */
6550 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6551 report_file_error ("filename too long", default_filename);
6553 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6554 SSDATA (prompt), -1, NULL, 0);
6555 if (len > 32768)
6556 len = 32768;
6557 prompt_w = alloca (len * sizeof (wchar_t));
6558 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6559 SSDATA (prompt), -1, prompt_w, len);
6560 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
6561 if (len > 32768)
6562 len = 32768;
6563 prompt_a = alloca (len);
6564 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
6566 #endif /* NTGUI_UNICODE */
6568 /* Fill in the structure for the call to GetOpenFileName below.
6569 For NTGUI_UNICODE builds (which run only on NT), we just use
6570 the actual size of the structure. For non-NTGUI_UNICODE
6571 builds, we tell the OS we're using an old version of the
6572 structure if the OS isn't new enough to support the newer
6573 version. */
6574 if (use_unicode)
6576 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6577 if (w32_major_version > 4 && w32_major_version < 95)
6578 file_details_w->lStructSize = sizeof (new_file_details_w);
6579 else
6580 file_details_w->lStructSize = sizeof (*file_details_w);
6581 /* Set up the inout parameter for the selected file name. */
6582 file_details_w->lpstrFile = filename_buf_w;
6583 file_details_w->nMaxFile =
6584 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6585 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6586 /* Undocumented Bug in Common File Dialog:
6587 If a filter is not specified, shell links are not resolved. */
6588 file_details_w->lpstrFilter = filter_w;
6589 #ifdef NTGUI_UNICODE
6590 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
6591 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
6592 #else
6593 file_details_w->lpstrInitialDir = dir_w;
6594 file_details_w->lpstrTitle = prompt_w;
6595 #endif
6596 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6597 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6598 | OFN_EXPLORER | OFN_ENABLEHOOK);
6599 if (!NILP (mustmatch))
6601 /* Require that the path to the parent directory exists. */
6602 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6603 /* If we are looking for a file, require that it exists. */
6604 if (NILP (only_dir_p))
6605 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6608 #ifndef NTGUI_UNICODE
6609 else
6611 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6612 if (w32_major_version > 4 && w32_major_version < 95)
6613 file_details_a->lStructSize = sizeof (new_file_details_a);
6614 else
6615 file_details_a->lStructSize = sizeof (*file_details_a);
6616 file_details_a->lpstrFile = filename_buf_a;
6617 file_details_a->nMaxFile =
6618 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6619 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6620 file_details_a->lpstrFilter = filter_a;
6621 file_details_a->lpstrInitialDir = dir_a;
6622 file_details_a->lpstrTitle = prompt_a;
6623 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6624 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6625 | OFN_EXPLORER | OFN_ENABLEHOOK);
6626 if (!NILP (mustmatch))
6628 /* Require that the path to the parent directory exists. */
6629 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6630 /* If we are looking for a file, require that it exists. */
6631 if (NILP (only_dir_p))
6632 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6635 #endif /* !NTGUI_UNICODE */
6638 int count = SPECPDL_INDEX ();
6639 /* Prevent redisplay. */
6640 specbind (Qinhibit_redisplay, Qt);
6641 block_input ();
6642 if (use_unicode)
6644 file_details_w->lpfnHook = file_dialog_callback;
6646 file_opened = GetOpenFileNameW (file_details_w);
6648 #ifndef NTGUI_UNICODE
6649 else
6651 file_details_a->lpfnHook = file_dialog_callback;
6653 file_opened = GetOpenFileNameA (file_details_a);
6655 #endif /* !NTGUI_UNICODE */
6656 unblock_input ();
6657 unbind_to (count, Qnil);
6660 if (file_opened)
6662 /* Get an Emacs string from the value Windows gave us. */
6663 #ifdef NTGUI_UNICODE
6664 filename = from_unicode_buffer (filename_buf_w);
6665 #else /* !NTGUI_UNICODE */
6666 if (use_unicode)
6667 filename_from_utf16 (filename_buf_w, fname_ret);
6668 else
6669 filename_from_ansi (filename_buf_a, fname_ret);
6670 dostounix_filename (fname_ret);
6671 filename = DECODE_FILE (build_unibyte_string (fname_ret));
6672 #endif /* NTGUI_UNICODE */
6674 #ifdef CYGWIN
6675 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
6676 #endif /* CYGWIN */
6678 /* Strip the dummy filename off the end of the string if we
6679 added it to select a directory. */
6680 if ((use_unicode && file_details_w->nFilterIndex == 2)
6681 #ifndef NTGUI_UNICODE
6682 || (!use_unicode && file_details_a->nFilterIndex == 2)
6683 #endif
6685 filename = Ffile_name_directory (filename);
6687 /* User canceled the dialog without making a selection. */
6688 else if (!CommDlgExtendedError ())
6689 filename = Qnil;
6690 /* An error occurred, fallback on reading from the mini-buffer. */
6691 else
6692 filename = Fcompleting_read (
6693 orig_prompt,
6694 intern ("read-file-name-internal"),
6695 orig_dir,
6696 mustmatch,
6697 orig_dir,
6698 Qfile_name_history,
6699 default_filename,
6700 Qnil);
6702 UNGCPRO;
6705 /* Make "Cancel" equivalent to C-g. */
6706 if (NILP (filename))
6707 Fsignal (Qquit, Qnil);
6709 RETURN_UNGCPRO (filename);
6713 #ifdef WINDOWSNT
6714 /* Moving files to the system recycle bin.
6715 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6716 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6717 Ssystem_move_file_to_trash, 1, 1, 0,
6718 doc: /* Move file or directory named FILENAME to the recycle bin. */)
6719 (Lisp_Object filename)
6721 Lisp_Object handler;
6722 Lisp_Object encoded_file;
6723 Lisp_Object operation;
6725 operation = Qdelete_file;
6726 if (!NILP (Ffile_directory_p (filename))
6727 && NILP (Ffile_symlink_p (filename)))
6729 operation = intern ("delete-directory");
6730 filename = Fdirectory_file_name (filename);
6733 /* Must have fully qualified file names for moving files to Recycle
6734 Bin. */
6735 filename = Fexpand_file_name (filename, Qnil);
6737 handler = Ffind_file_name_handler (filename, operation);
6738 if (!NILP (handler))
6739 return call2 (handler, operation, filename);
6740 else
6742 const char * path;
6743 int result;
6745 encoded_file = ENCODE_FILE (filename);
6747 path = map_w32_filename (SDATA (encoded_file), NULL);
6749 /* The Unicode version of SHFileOperation is not supported on
6750 Windows 9X. */
6751 if (w32_unicode_filenames && os_subtype != OS_9X)
6753 SHFILEOPSTRUCTW file_op_w;
6754 /* We need one more element beyond MAX_PATH because this is
6755 a list of file names, with the last element double-null
6756 terminated. */
6757 wchar_t tmp_path_w[MAX_PATH + 1];
6759 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6760 filename_to_utf16 (path, tmp_path_w);
6762 /* On Windows, write permission is required to delete/move files. */
6763 _wchmod (tmp_path_w, 0666);
6765 memset (&file_op_w, 0, sizeof (file_op_w));
6766 file_op_w.hwnd = HWND_DESKTOP;
6767 file_op_w.wFunc = FO_DELETE;
6768 file_op_w.pFrom = tmp_path_w;
6769 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6770 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6771 file_op_w.fAnyOperationsAborted = FALSE;
6773 result = SHFileOperationW (&file_op_w);
6775 else
6777 SHFILEOPSTRUCTA file_op_a;
6778 char tmp_path_a[MAX_PATH + 1];
6780 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6781 filename_to_ansi (path, tmp_path_a);
6783 /* If a file cannot be represented in ANSI codepage, don't
6784 let them inadvertently delete other files because some
6785 characters are interpreted as a wildcards. */
6786 if (_mbspbrk (tmp_path_a, "?*"))
6787 result = ERROR_FILE_NOT_FOUND;
6788 else
6790 _chmod (tmp_path_a, 0666);
6792 memset (&file_op_a, 0, sizeof (file_op_a));
6793 file_op_a.hwnd = HWND_DESKTOP;
6794 file_op_a.wFunc = FO_DELETE;
6795 file_op_a.pFrom = tmp_path_a;
6796 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6797 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6798 file_op_a.fAnyOperationsAborted = FALSE;
6800 result = SHFileOperationA (&file_op_a);
6803 if (result != 0)
6804 report_file_error ("Removing old name", list1 (filename));
6806 return Qnil;
6809 #endif /* WINDOWSNT */
6812 /***********************************************************************
6813 w32 specialized functions
6814 ***********************************************************************/
6816 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6817 Sw32_send_sys_command, 1, 2, 0,
6818 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
6819 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
6820 to minimize), #xf120 to restore frame to original size, and #xf100
6821 to activate the menubar for keyboard access. #xf140 activates the
6822 screen saver if defined.
6824 If optional parameter FRAME is not specified, use selected frame. */)
6825 (Lisp_Object command, Lisp_Object frame)
6827 struct frame *f = decode_window_system_frame (frame);
6829 CHECK_NUMBER (command);
6831 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
6833 return Qnil;
6836 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
6837 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6838 This is a wrapper around the ShellExecute system function, which
6839 invokes the application registered to handle OPERATION for DOCUMENT.
6841 OPERATION is either nil or a string that names a supported operation.
6842 What operations can be used depends on the particular DOCUMENT and its
6843 handler application, but typically it is one of the following common
6844 operations:
6846 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6847 executable program (application). If it is an application,
6848 that application is launched in the current buffer's default
6849 directory. Otherwise, the application associated with
6850 DOCUMENT is launched in the buffer's default directory.
6851 \"opennew\" - like \"open\", but instruct the application to open
6852 DOCUMENT in a new window.
6853 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
6854 \"print\" - print DOCUMENT, which must be a file.
6855 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
6856 The printer should be provided in PARAMETERS, see below.
6857 \"explore\" - start the Windows Explorer on DOCUMENT.
6858 \"edit\" - launch an editor and open DOCUMENT for editing; which
6859 editor is launched depends on the association for the
6860 specified DOCUMENT.
6861 \"find\" - initiate search starting from DOCUMENT, which must specify
6862 a directory.
6863 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
6864 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
6865 the clipboard.
6866 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
6867 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
6868 which must be a directory.
6869 \"pastelink\"
6870 - create a shortcut in DOCUMENT (which must be a directory)
6871 the file or directory whose name is in the clipboard.
6872 \"runas\" - run DOCUMENT, which must be an excutable file, with
6873 elevated privileges (a.k.a. \"as Administrator\").
6874 \"properties\"
6875 - open the property sheet dialog for DOCUMENT.
6876 nil - invoke the default OPERATION, or \"open\" if default is
6877 not defined or unavailable.
6879 DOCUMENT is typically the name of a document file or a URL, but can
6880 also be an executable program to run, or a directory to open in the
6881 Windows Explorer. If it is a file or a directory, it must be a local
6882 one; this function does not support remote file names.
6884 If DOCUMENT is an executable program, the optional third arg PARAMETERS
6885 can be a string containing command line parameters, separated by blanks,
6886 that will be passed to the program. Some values of OPERATION also require
6887 parameters (e.g., \"printto\" requires the printer address). Otherwise,
6888 PARAMETERS should be nil or unspecified. Note that double quote characters
6889 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
6891 Optional fourth argument SHOW-FLAG can be used to control how the
6892 application will be displayed when it is invoked. If SHOW-FLAG is nil
6893 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
6894 specified, otherwise it is an integer between 0 and 11 representing
6895 a ShowWindow flag:
6897 0 - start hidden
6898 1 - start as normal-size window
6899 3 - start in a maximized window
6900 6 - start in a minimized window
6901 10 - start as the application itself specifies; this is the default. */)
6902 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
6904 char *errstr;
6905 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6906 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
6907 #ifdef CYGWIN
6908 intptr_t result;
6909 #else
6910 int use_unicode = w32_unicode_filenames;
6911 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
6912 Lisp_Object absdoc, handler;
6913 BOOL success;
6914 struct gcpro gcpro1;
6915 #endif
6917 CHECK_STRING (document);
6919 #ifdef CYGWIN
6920 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
6921 document = Fcygwin_convert_file_name_to_windows (document, Qt);
6923 /* Encode filename, current directory and parameters. */
6924 current_dir = GUI_ENCODE_FILE (current_dir);
6925 document = GUI_ENCODE_FILE (document);
6926 doc_w = GUI_SDATA (document);
6927 if (STRINGP (parameters))
6929 parameters = GUI_ENCODE_SYSTEM (parameters);
6930 params_w = GUI_SDATA (parameters);
6932 if (STRINGP (operation))
6934 operation = GUI_ENCODE_SYSTEM (operation);
6935 ops_w = GUI_SDATA (operation);
6937 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6938 GUI_SDATA (current_dir),
6939 (INTEGERP (show_flag)
6940 ? XINT (show_flag) : SW_SHOWDEFAULT));
6942 if (result > 32)
6943 return Qt;
6945 switch (result)
6947 case SE_ERR_ACCESSDENIED:
6948 errstr = w32_strerror (ERROR_ACCESS_DENIED);
6949 break;
6950 case SE_ERR_ASSOCINCOMPLETE:
6951 case SE_ERR_NOASSOC:
6952 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
6953 break;
6954 case SE_ERR_DDEBUSY:
6955 case SE_ERR_DDEFAIL:
6956 errstr = w32_strerror (ERROR_DDE_FAIL);
6957 break;
6958 case SE_ERR_DDETIMEOUT:
6959 errstr = w32_strerror (ERROR_TIMEOUT);
6960 break;
6961 case SE_ERR_DLLNOTFOUND:
6962 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
6963 break;
6964 case SE_ERR_FNF:
6965 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
6966 break;
6967 case SE_ERR_OOM:
6968 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
6969 break;
6970 case SE_ERR_PNF:
6971 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
6972 break;
6973 case SE_ERR_SHARE:
6974 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
6975 break;
6976 default:
6977 errstr = w32_strerror (0);
6978 break;
6981 #else /* !CYGWIN */
6983 current_dir = ENCODE_FILE (current_dir);
6984 /* We have a situation here. If DOCUMENT is a relative file name,
6985 but its name includes leading directories, i.e. it lives not in
6986 CURRENT_DIR, but in its subdirectory, then ShellExecute below
6987 will fail to find it. So we need to make the file name is
6988 absolute. But DOCUMENT does not have to be a file, it can be a
6989 URL, for example. So we make it absolute only if it is an
6990 existing file; if it is a file that does not exist, tough. */
6991 GCPRO1 (absdoc);
6992 absdoc = Fexpand_file_name (document, Qnil);
6993 /* Don't call file handlers for file-exists-p, since they might
6994 attempt to access the file, which could fail or produce undesired
6995 consequences, see bug#16558 for an example. */
6996 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
6997 if (NILP (handler))
6999 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7001 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7003 /* ShellExecute fails if DOCUMENT is a UNC with forward
7004 slashes (expand-file-name above converts all backslashes
7005 to forward slashes). Now that we know DOCUMENT is a
7006 file, we can mirror all forward slashes into backslashes. */
7007 unixtodos_filename (SSDATA (absdoc_encoded));
7008 document = absdoc_encoded;
7010 else
7011 document = ENCODE_FILE (document);
7013 else
7014 document = ENCODE_FILE (document);
7015 UNGCPRO;
7016 if (use_unicode)
7018 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
7019 SHELLEXECUTEINFOW shexinfo_w;
7021 /* Encode filename, current directory and parameters, and
7022 convert operation to UTF-16. */
7023 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7024 filename_to_utf16 (SSDATA (document), document_w);
7025 doc_w = document_w;
7026 if (STRINGP (parameters))
7028 int len;
7030 parameters = ENCODE_SYSTEM (parameters);
7031 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7032 SSDATA (parameters), -1, NULL, 0);
7033 if (len > 32768)
7034 len = 32768;
7035 params_w = alloca (len * sizeof (wchar_t));
7036 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7037 SSDATA (parameters), -1, params_w, len);
7039 if (STRINGP (operation))
7041 /* Assume OPERATION is pure ASCII. */
7042 const char *s = SSDATA (operation);
7043 wchar_t *d;
7044 int len = SBYTES (operation) + 1;
7046 if (len > 32768)
7047 len = 32768;
7048 d = ops_w = alloca (len * sizeof (wchar_t));
7049 while (d < ops_w + len - 1)
7050 *d++ = *s++;
7051 *d = 0;
7054 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7055 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7056 able to invoke verbs from shortcut menu extensions, not just
7057 static verbs listed in the Registry. */
7058 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7059 shexinfo_w.cbSize = sizeof (shexinfo_w);
7060 shexinfo_w.fMask =
7061 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7062 shexinfo_w.hwnd = NULL;
7063 shexinfo_w.lpVerb = ops_w;
7064 shexinfo_w.lpFile = doc_w;
7065 shexinfo_w.lpParameters = params_w;
7066 shexinfo_w.lpDirectory = current_dir_w;
7067 shexinfo_w.nShow =
7068 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7069 success = ShellExecuteExW (&shexinfo_w);
7071 else
7073 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7074 SHELLEXECUTEINFOA shexinfo_a;
7076 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7077 filename_to_ansi (SSDATA (document), document_a);
7078 doc_a = document_a;
7079 if (STRINGP (parameters))
7081 parameters = ENCODE_SYSTEM (parameters);
7082 params_a = SSDATA (parameters);
7084 if (STRINGP (operation))
7086 /* Assume OPERATION is pure ASCII. */
7087 ops_a = SSDATA (operation);
7089 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7090 shexinfo_a.cbSize = sizeof (shexinfo_a);
7091 shexinfo_a.fMask =
7092 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7093 shexinfo_a.hwnd = NULL;
7094 shexinfo_a.lpVerb = ops_a;
7095 shexinfo_a.lpFile = doc_a;
7096 shexinfo_a.lpParameters = params_a;
7097 shexinfo_a.lpDirectory = current_dir_a;
7098 shexinfo_a.nShow =
7099 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7100 success = ShellExecuteExA (&shexinfo_a);
7103 if (success)
7104 return Qt;
7106 errstr = w32_strerror (0);
7108 #endif /* !CYGWIN */
7110 /* The error string might be encoded in the locale's encoding. */
7111 if (!NILP (Vlocale_coding_system))
7113 Lisp_Object decoded =
7114 code_convert_string_norecord (build_unibyte_string (errstr),
7115 Vlocale_coding_system, 0);
7116 errstr = SSDATA (decoded);
7118 error ("ShellExecute failed: %s", errstr);
7121 /* Lookup virtual keycode from string representing the name of a
7122 non-ascii keystroke into the corresponding virtual key, using
7123 lispy_function_keys. */
7124 static int
7125 lookup_vk_code (char *key)
7127 int i;
7129 for (i = 0; i < 256; i++)
7130 if (lispy_function_keys[i]
7131 && strcmp (lispy_function_keys[i], key) == 0)
7132 return i;
7134 return -1;
7137 /* Convert a one-element vector style key sequence to a hot key
7138 definition. */
7139 static Lisp_Object
7140 w32_parse_hot_key (Lisp_Object key)
7142 /* Copied from Fdefine_key and store_in_keymap. */
7143 register Lisp_Object c;
7144 int vk_code;
7145 int lisp_modifiers;
7146 int w32_modifiers;
7147 struct gcpro gcpro1;
7149 CHECK_VECTOR (key);
7151 if (ASIZE (key) != 1)
7152 return Qnil;
7154 GCPRO1 (key);
7156 c = AREF (key, 0);
7158 if (CONSP (c) && lucid_event_type_list_p (c))
7159 c = Fevent_convert_list (c);
7161 UNGCPRO;
7163 if (! INTEGERP (c) && ! SYMBOLP (c))
7164 error ("Key definition is invalid");
7166 /* Work out the base key and the modifiers. */
7167 if (SYMBOLP (c))
7169 c = parse_modifiers (c);
7170 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7171 c = Fcar (c);
7172 if (!SYMBOLP (c))
7173 emacs_abort ();
7174 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7176 else if (INTEGERP (c))
7178 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7179 /* Many ascii characters are their own virtual key code. */
7180 vk_code = XINT (c) & CHARACTERBITS;
7183 if (vk_code < 0 || vk_code > 255)
7184 return Qnil;
7186 if ((lisp_modifiers & meta_modifier) != 0
7187 && !NILP (Vw32_alt_is_meta))
7188 lisp_modifiers |= alt_modifier;
7190 /* Supply defs missing from mingw32. */
7191 #ifndef MOD_ALT
7192 #define MOD_ALT 0x0001
7193 #define MOD_CONTROL 0x0002
7194 #define MOD_SHIFT 0x0004
7195 #define MOD_WIN 0x0008
7196 #endif
7198 /* Convert lisp modifiers to Windows hot-key form. */
7199 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7200 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7201 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7202 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7204 return HOTKEY (vk_code, w32_modifiers);
7207 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7208 Sw32_register_hot_key, 1, 1, 0,
7209 doc: /* Register KEY as a hot-key combination.
7210 Certain key combinations like Alt-Tab are reserved for system use on
7211 Windows, and therefore are normally intercepted by the system. However,
7212 most of these key combinations can be received by registering them as
7213 hot-keys, overriding their special meaning.
7215 KEY must be a one element key definition in vector form that would be
7216 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7217 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7218 is always interpreted as the Windows modifier keys.
7220 The return value is the hotkey-id if registered, otherwise nil. */)
7221 (Lisp_Object key)
7223 key = w32_parse_hot_key (key);
7225 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7227 /* Reuse an empty slot if possible. */
7228 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7230 /* Safe to add new key to list, even if we have focus. */
7231 if (NILP (item))
7232 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7233 else
7234 XSETCAR (item, key);
7236 /* Notify input thread about new hot-key definition, so that it
7237 takes effect without needing to switch focus. */
7238 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7239 (WPARAM) XINT (key), 0);
7242 return key;
7245 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7246 Sw32_unregister_hot_key, 1, 1, 0,
7247 doc: /* Unregister KEY as a hot-key combination. */)
7248 (Lisp_Object key)
7250 Lisp_Object item;
7252 if (!INTEGERP (key))
7253 key = w32_parse_hot_key (key);
7255 item = Fmemq (key, w32_grabbed_keys);
7257 if (!NILP (item))
7259 LPARAM lparam;
7261 eassert (CONSP (item));
7262 /* Pass the tail of the list as a pointer to a Lisp_Cons cell,
7263 so that it works in a --with-wide-int build as well. */
7264 lparam = (LPARAM) XUNTAG (item, Lisp_Cons);
7266 /* Notify input thread about hot-key definition being removed, so
7267 that it takes effect without needing focus switch. */
7268 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7269 (WPARAM) XINT (XCAR (item)), lparam))
7271 MSG msg;
7272 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7274 return Qt;
7276 return Qnil;
7279 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7280 Sw32_registered_hot_keys, 0, 0, 0,
7281 doc: /* Return list of registered hot-key IDs. */)
7282 (void)
7284 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7287 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7288 Sw32_reconstruct_hot_key, 1, 1, 0,
7289 doc: /* Convert hot-key ID to a lisp key combination.
7290 usage: (w32-reconstruct-hot-key ID) */)
7291 (Lisp_Object hotkeyid)
7293 int vk_code, w32_modifiers;
7294 Lisp_Object key;
7296 CHECK_NUMBER (hotkeyid);
7298 vk_code = HOTKEY_VK_CODE (hotkeyid);
7299 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7301 if (vk_code < 256 && lispy_function_keys[vk_code])
7302 key = intern (lispy_function_keys[vk_code]);
7303 else
7304 key = make_number (vk_code);
7306 key = Fcons (key, Qnil);
7307 if (w32_modifiers & MOD_SHIFT)
7308 key = Fcons (Qshift, key);
7309 if (w32_modifiers & MOD_CONTROL)
7310 key = Fcons (Qctrl, key);
7311 if (w32_modifiers & MOD_ALT)
7312 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7313 if (w32_modifiers & MOD_WIN)
7314 key = Fcons (Qhyper, key);
7316 return key;
7319 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7320 Sw32_toggle_lock_key, 1, 2, 0,
7321 doc: /* Toggle the state of the lock key KEY.
7322 KEY can be `capslock', `kp-numlock', or `scroll'.
7323 If the optional parameter NEW-STATE is a number, then the state of KEY
7324 is set to off if the low bit of NEW-STATE is zero, otherwise on.
7325 If NEW-STATE is omitted or nil, the function toggles the state,
7327 Value is the new state of the key, or nil if the function failed
7328 to change the state. */)
7329 (Lisp_Object key, Lisp_Object new_state)
7331 int vk_code;
7332 LPARAM lparam;
7334 if (EQ (key, intern ("capslock")))
7335 vk_code = VK_CAPITAL;
7336 else if (EQ (key, intern ("kp-numlock")))
7337 vk_code = VK_NUMLOCK;
7338 else if (EQ (key, intern ("scroll")))
7339 vk_code = VK_SCROLL;
7340 else
7341 return Qnil;
7343 if (!dwWindowsThreadId)
7344 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7346 if (NILP (new_state))
7347 lparam = -1;
7348 else
7349 lparam = (XUINT (new_state)) & 1;
7350 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7351 (WPARAM) vk_code, lparam))
7353 MSG msg;
7354 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7355 return make_number (msg.wParam);
7357 return Qnil;
7360 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7361 2, 2, 0,
7362 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7364 This is a direct interface to the Windows API FindWindow function. */)
7365 (Lisp_Object class, Lisp_Object name)
7367 HWND hnd;
7369 if (!NILP (class))
7370 CHECK_STRING (class);
7371 if (!NILP (name))
7372 CHECK_STRING (name);
7374 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7375 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7376 if (!hnd)
7377 return Qnil;
7378 return Qt;
7381 DEFUN ("w32-frame-menu-bar-size", Fw32_frame_menu_bar_size, Sw32_frame_menu_bar_size, 0, 1, 0,
7382 doc: /* Return sizes of menu bar on frame FRAME.
7383 The return value is a list of four elements: The current width and
7384 height of FRAME's menu bar in pixels, the height of one menu bar line in
7385 a wrapped menu bar in pixels, and the height of a single line menu bar
7386 in pixels.
7388 If FRAME is omitted or nil, the selected frame is used. */)
7389 (Lisp_Object frame)
7391 struct frame *f = decode_any_frame (frame);
7392 MENUBARINFO menu_bar;
7393 int width, height, single_height, wrapped_height;
7395 block_input ();
7397 single_height = GetSystemMetrics (SM_CYMENU);
7398 wrapped_height = GetSystemMetrics (SM_CYMENUSIZE);
7399 menu_bar.cbSize = sizeof (menu_bar);
7400 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
7401 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
7402 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
7403 width = menu_bar.rcBar.right - menu_bar.rcBar.left;
7404 height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
7406 unblock_input ();
7408 return list4 (make_number (width), make_number (height),
7409 make_number (wrapped_height), make_number (single_height));
7412 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7413 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7414 FRAME must be a live frame and defaults to the selected one.
7416 The boundary rectangle is a list of four elements, specifying the left,
7417 top, right and bottom screen coordinates of FRAME including menu and
7418 title bar and decorations. Optional argument CLIENT non-nil means to
7419 return the boundaries of the client rectangle which excludes menu and
7420 title bar and decorations. */)
7421 (Lisp_Object frame, Lisp_Object client)
7423 struct frame *f = decode_live_frame (frame);
7424 RECT rect;
7426 block_input ();
7428 if (!NILP (client))
7429 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7430 else
7431 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7433 unblock_input ();
7435 return list4 (make_number (rect.left), make_number (rect.top),
7436 make_number (rect.right), make_number (rect.bottom));
7439 DEFUN ("x-frame-geometry", Fx_frame_geometry, Sx_frame_geometry, 0, 1, 0,
7440 doc: /* Return geometric attributes of frame FRAME.
7441 FRAME must be a live frame and defaults to the selected one.
7443 The return value is an association list containing the following
7444 elements (all size values are in pixels).
7446 - `frame-outer-size' is a cons of the outer width and height of FRAME.
7447 The outer size includes the title bar and the external borders as well
7448 as any menu and/or tool bar of frame.
7450 - `border' is a cons of the horizontal and vertical width of FRAME's
7451 external borders.
7453 - `title-bar-height' is the height of the title bar of FRAME.
7455 - `menu-bar-external' if `t' means the menu bar is by default external
7456 (not included in the inner size of FRAME).
7458 - `menu-bar-size' is a cons of the width and height of the menu bar of
7459 FRAME.
7461 - `tool-bar-external' if `t' means the tool bar is by default external
7462 (not included in the inner size of FRAME).
7464 - `tool-bar-side' tells tells on which side the tool bar on FRAME is by
7465 default and can be one of `left', `top', `right' or `bottom'.
7467 - `tool-bar-size' is a cons of the width and height of the tool bar of
7468 FRAME.
7470 - `frame-inner-size' is a cons of the inner width and height of FRAME.
7471 This excludes FRAME's title bar and external border as well as any
7472 external menu and/or tool bar. */)
7473 (Lisp_Object frame)
7475 struct frame *f = decode_live_frame (frame);
7476 Lisp_Object geometry = Qnil;
7477 RECT frame_outer_edges, frame_inner_edges;
7478 MENUBARINFO menu_bar;
7479 int border_width, border_height, title_height;
7480 int single_bar_height, wrapped_bar_height, menu_bar_height;
7481 Lisp_Object fullscreen = Fframe_parameter (frame, Qfullscreen);
7483 block_input ();
7485 /* Outer frame rectangle, including outer borders and title bar. */
7486 GetWindowRect (FRAME_W32_WINDOW (f), &frame_outer_edges);
7487 /* Inner frame rectangle, excluding borders and title bar. */
7488 GetClientRect (FRAME_W32_WINDOW (f), &frame_inner_edges);
7489 /* Outer border. */
7490 border_width = GetSystemMetrics (SM_CXFRAME);
7491 border_height = GetSystemMetrics (SM_CYFRAME);
7492 /* Title bar. */
7493 title_height = GetSystemMetrics (SM_CYCAPTION);
7494 /* Menu bar. */
7495 menu_bar.cbSize = sizeof (menu_bar);
7496 menu_bar.rcBar.right = menu_bar.rcBar.left = 0;
7497 menu_bar.rcBar.top = menu_bar.rcBar.bottom = 0;
7498 GetMenuBarInfo (FRAME_W32_WINDOW (f), 0xFFFFFFFD, 0, &menu_bar);
7499 single_bar_height = GetSystemMetrics (SM_CYMENU);
7500 wrapped_bar_height = GetSystemMetrics (SM_CYMENUSIZE);
7501 unblock_input ();
7503 menu_bar_height = menu_bar.rcBar.bottom - menu_bar.rcBar.top;
7504 /* Fix menu bar height reported by GetMenuBarInfo. */
7505 if (menu_bar_height > single_bar_height)
7506 /* A wrapped menu bar. */
7507 menu_bar_height += single_bar_height - wrapped_bar_height;
7508 else if (menu_bar_height > 0)
7509 /* A single line menu bar. */
7510 menu_bar_height = single_bar_height;
7512 return
7513 listn (CONSTYPE_PURE, 10,
7514 Fcons (Qframe_position,
7515 Fcons (make_number (frame_outer_edges.left),
7516 make_number (frame_outer_edges.top))),
7517 Fcons (Qframe_outer_size,
7518 Fcons (make_number
7519 (frame_outer_edges.right - frame_outer_edges.left),
7520 make_number
7521 (frame_outer_edges.bottom - frame_outer_edges.top))),
7522 Fcons (Qexternal_border_size,
7523 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
7524 ? Fcons (make_number (0), make_number (0))
7525 : Fcons (make_number (border_width),
7526 make_number (border_height)))),
7527 Fcons (Qtitle_height,
7528 ((EQ (fullscreen, Qfullboth) || EQ (fullscreen, Qfullscreen))
7529 ? make_number (0)
7530 : make_number (title_height))),
7531 Fcons (Qmenu_bar_external, Qt),
7532 Fcons (Qmenu_bar_size,
7533 Fcons (make_number
7534 (menu_bar.rcBar.right - menu_bar.rcBar.left),
7535 make_number (menu_bar_height))),
7536 Fcons (Qtool_bar_external, Qnil),
7537 Fcons (Qtool_bar_position, Qtop),
7538 Fcons (Qtool_bar_size,
7539 Fcons (make_number (FRAME_TOOL_BAR_LINES (f)
7540 ? (FRAME_PIXEL_WIDTH (f)
7541 - 2 * FRAME_INTERNAL_BORDER_WIDTH (f))
7542 : 0),
7543 make_number (FRAME_TOOL_BAR_HEIGHT (f)))),
7544 Fcons (Qframe_inner_size,
7545 Fcons (make_number
7546 (frame_inner_edges.right - frame_inner_edges.left),
7547 make_number
7548 (frame_inner_edges.bottom - frame_inner_edges.top))));
7551 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7552 doc: /* Get power status information from Windows system.
7554 The following %-sequences are provided:
7555 %L AC line status (verbose)
7556 %B Battery status (verbose)
7557 %b Battery status, empty means high, `-' means low,
7558 `!' means critical, and `+' means charging
7559 %p Battery load percentage
7560 %s Remaining time (to charge or discharge) in seconds
7561 %m Remaining time (to charge or discharge) in minutes
7562 %h Remaining time (to charge or discharge) in hours
7563 %t Remaining time (to charge or discharge) in the form `h:min' */)
7564 (void)
7566 Lisp_Object status = Qnil;
7568 SYSTEM_POWER_STATUS system_status;
7569 if (GetSystemPowerStatus (&system_status))
7571 Lisp_Object line_status, battery_status, battery_status_symbol;
7572 Lisp_Object load_percentage, seconds, minutes, hours, remain;
7574 long seconds_left = (long) system_status.BatteryLifeTime;
7576 if (system_status.ACLineStatus == 0)
7577 line_status = build_string ("off-line");
7578 else if (system_status.ACLineStatus == 1)
7579 line_status = build_string ("on-line");
7580 else
7581 line_status = build_string ("N/A");
7583 if (system_status.BatteryFlag & 128)
7585 battery_status = build_string ("N/A");
7586 battery_status_symbol = empty_unibyte_string;
7588 else if (system_status.BatteryFlag & 8)
7590 battery_status = build_string ("charging");
7591 battery_status_symbol = build_string ("+");
7592 if (system_status.BatteryFullLifeTime != -1L)
7593 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7595 else if (system_status.BatteryFlag & 4)
7597 battery_status = build_string ("critical");
7598 battery_status_symbol = build_string ("!");
7600 else if (system_status.BatteryFlag & 2)
7602 battery_status = build_string ("low");
7603 battery_status_symbol = build_string ("-");
7605 else if (system_status.BatteryFlag & 1)
7607 battery_status = build_string ("high");
7608 battery_status_symbol = empty_unibyte_string;
7610 else
7612 battery_status = build_string ("medium");
7613 battery_status_symbol = empty_unibyte_string;
7616 if (system_status.BatteryLifePercent > 100)
7617 load_percentage = build_string ("N/A");
7618 else
7620 char buffer[16];
7621 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
7622 load_percentage = build_string (buffer);
7625 if (seconds_left < 0)
7626 seconds = minutes = hours = remain = build_string ("N/A");
7627 else
7629 long m;
7630 float h;
7631 char buffer[16];
7632 snprintf (buffer, 16, "%ld", seconds_left);
7633 seconds = build_string (buffer);
7635 m = seconds_left / 60;
7636 snprintf (buffer, 16, "%ld", m);
7637 minutes = build_string (buffer);
7639 h = seconds_left / 3600.0;
7640 snprintf (buffer, 16, "%3.1f", h);
7641 hours = build_string (buffer);
7643 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
7644 remain = build_string (buffer);
7647 status = listn (CONSTYPE_HEAP, 8,
7648 Fcons (make_number ('L'), line_status),
7649 Fcons (make_number ('B'), battery_status),
7650 Fcons (make_number ('b'), battery_status_symbol),
7651 Fcons (make_number ('p'), load_percentage),
7652 Fcons (make_number ('s'), seconds),
7653 Fcons (make_number ('m'), minutes),
7654 Fcons (make_number ('h'), hours),
7655 Fcons (make_number ('t'), remain));
7657 return status;
7661 #ifdef WINDOWSNT
7662 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
7663 doc: /* Return storage information about the file system FILENAME is on.
7664 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7665 storage of the file system, FREE is the free storage, and AVAIL is the
7666 storage available to a non-superuser. All 3 numbers are in bytes.
7667 If the underlying system call fails, value is nil. */)
7668 (Lisp_Object filename)
7670 Lisp_Object encoded, value;
7672 CHECK_STRING (filename);
7673 filename = Fexpand_file_name (filename, Qnil);
7674 encoded = ENCODE_FILE (filename);
7676 value = Qnil;
7678 /* Determining the required information on Windows turns out, sadly,
7679 to be more involved than one would hope. The original Windows API
7680 call for this will return bogus information on some systems, but we
7681 must dynamically probe for the replacement api, since that was
7682 added rather late on. */
7684 HMODULE hKernel = GetModuleHandle ("kernel32");
7685 BOOL (WINAPI *pfn_GetDiskFreeSpaceExW)
7686 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7687 = GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7688 BOOL (WINAPI *pfn_GetDiskFreeSpaceExA)
7689 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7690 = GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
7691 bool have_pfn_GetDiskFreeSpaceEx =
7692 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
7693 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
7695 /* On Windows, we may need to specify the root directory of the
7696 volume holding FILENAME. */
7697 char rootname[MAX_UTF8_PATH];
7698 wchar_t rootname_w[MAX_PATH];
7699 char rootname_a[MAX_PATH];
7700 char *name = SDATA (encoded);
7701 BOOL result;
7703 /* find the root name of the volume if given */
7704 if (isalpha (name[0]) && name[1] == ':')
7706 rootname[0] = name[0];
7707 rootname[1] = name[1];
7708 rootname[2] = '\\';
7709 rootname[3] = 0;
7711 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7713 char *str = rootname;
7714 int slashes = 4;
7717 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7718 break;
7719 *str++ = *name++;
7721 while ( *name );
7723 *str++ = '\\';
7724 *str = 0;
7727 if (w32_unicode_filenames)
7728 filename_to_utf16 (rootname, rootname_w);
7729 else
7730 filename_to_ansi (rootname, rootname_a);
7732 if (have_pfn_GetDiskFreeSpaceEx)
7734 /* Unsigned large integers cannot be cast to double, so
7735 use signed ones instead. */
7736 LARGE_INTEGER availbytes;
7737 LARGE_INTEGER freebytes;
7738 LARGE_INTEGER totalbytes;
7740 if (w32_unicode_filenames)
7741 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7742 (ULARGE_INTEGER *)&availbytes,
7743 (ULARGE_INTEGER *)&totalbytes,
7744 (ULARGE_INTEGER *)&freebytes);
7745 else
7746 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7747 (ULARGE_INTEGER *)&availbytes,
7748 (ULARGE_INTEGER *)&totalbytes,
7749 (ULARGE_INTEGER *)&freebytes);
7750 if (result)
7751 value = list3 (make_float ((double) totalbytes.QuadPart),
7752 make_float ((double) freebytes.QuadPart),
7753 make_float ((double) availbytes.QuadPart));
7755 else
7757 DWORD sectors_per_cluster;
7758 DWORD bytes_per_sector;
7759 DWORD free_clusters;
7760 DWORD total_clusters;
7762 if (w32_unicode_filenames)
7763 result = GetDiskFreeSpaceW (rootname_w,
7764 &sectors_per_cluster,
7765 &bytes_per_sector,
7766 &free_clusters,
7767 &total_clusters);
7768 else
7769 result = GetDiskFreeSpaceA (rootname_a,
7770 &sectors_per_cluster,
7771 &bytes_per_sector,
7772 &free_clusters,
7773 &total_clusters);
7774 if (result)
7775 value = list3 (make_float ((double) total_clusters
7776 * sectors_per_cluster * bytes_per_sector),
7777 make_float ((double) free_clusters
7778 * sectors_per_cluster * bytes_per_sector),
7779 make_float ((double) free_clusters
7780 * sectors_per_cluster * bytes_per_sector));
7784 return value;
7786 #endif /* WINDOWSNT */
7789 #ifdef WINDOWSNT
7790 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7791 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
7792 (void)
7794 static char pname_buf[256];
7795 int err;
7796 HANDLE hPrn;
7797 PRINTER_INFO_2W *ppi2w = NULL;
7798 PRINTER_INFO_2A *ppi2a = NULL;
7799 DWORD dwNeeded = 0, dwReturned = 0;
7800 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7801 char port_name[MAX_UTF8_PATH];
7803 /* Retrieve the default string from Win.ini (the registry).
7804 * String will be in form "printername,drivername,portname".
7805 * This is the most portable way to get the default printer. */
7806 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7807 return Qnil;
7808 /* printername precedes first "," character */
7809 strtok (pname_buf, ",");
7810 /* We want to know more than the printer name */
7811 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7812 return Qnil;
7813 /* GetPrinterW is not supported by unicows.dll. */
7814 if (w32_unicode_filenames && os_subtype != OS_9X)
7815 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7816 else
7817 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
7818 if (dwNeeded == 0)
7820 ClosePrinter (hPrn);
7821 return Qnil;
7823 /* Call GetPrinter again with big enough memory block. */
7824 if (w32_unicode_filenames && os_subtype != OS_9X)
7826 /* Allocate memory for the PRINTER_INFO_2 struct. */
7827 ppi2w = xmalloc (dwNeeded);
7828 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
7829 ClosePrinter (hPrn);
7830 if (!err)
7832 xfree (ppi2w);
7833 return Qnil;
7836 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7837 && ppi2w->pServerName)
7839 filename_from_utf16 (ppi2w->pServerName, server_name);
7840 filename_from_utf16 (ppi2w->pShareName, share_name);
7842 else
7844 server_name[0] = '\0';
7845 filename_from_utf16 (ppi2w->pPortName, port_name);
7848 else
7850 ppi2a = xmalloc (dwNeeded);
7851 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7852 ClosePrinter (hPrn);
7853 if (!err)
7855 xfree (ppi2a);
7856 return Qnil;
7859 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7860 && ppi2a->pServerName)
7862 filename_from_ansi (ppi2a->pServerName, server_name);
7863 filename_from_ansi (ppi2a->pShareName, share_name);
7865 else
7867 server_name[0] = '\0';
7868 filename_from_ansi (ppi2a->pPortName, port_name);
7872 if (server_name[0])
7874 /* a remote printer */
7875 if (server_name[0] == '\\')
7876 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7877 share_name);
7878 else
7879 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7880 share_name);
7881 pname_buf[sizeof (pname_buf) - 1] = '\0';
7883 else
7885 /* a local printer */
7886 strncpy (pname_buf, port_name, sizeof (pname_buf));
7887 pname_buf[sizeof (pname_buf) - 1] = '\0';
7888 /* `pPortName' can include several ports, delimited by ','.
7889 * we only use the first one. */
7890 strtok (pname_buf, ",");
7893 return DECODE_FILE (build_unibyte_string (pname_buf));
7895 #endif /* WINDOWSNT */
7898 /* Equivalent of strerror for W32 error codes. */
7899 char *
7900 w32_strerror (int error_no)
7902 static char buf[500];
7903 DWORD ret;
7905 if (error_no == 0)
7906 error_no = GetLastError ();
7908 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7909 FORMAT_MESSAGE_IGNORE_INSERTS,
7910 NULL,
7911 error_no,
7912 0, /* choose most suitable language */
7913 buf, sizeof (buf), NULL);
7915 while (ret > 0 && (buf[ret - 1] == '\n' ||
7916 buf[ret - 1] == '\r' ))
7917 --ret;
7918 buf[ret] = '\0';
7919 if (!ret)
7920 sprintf (buf, "w32 error %u", error_no);
7922 return buf;
7925 /* For convenience when debugging. (You cannot call GetLastError
7926 directly from GDB: it will crash, because it uses the __stdcall
7927 calling convention, not the _cdecl convention assumed by GDB.) */
7928 DWORD
7929 w32_last_error (void)
7931 return GetLastError ();
7934 /* Cache information describing the NT system for later use. */
7935 void
7936 cache_system_info (void)
7938 union
7940 struct info
7942 char major;
7943 char minor;
7944 short platform;
7945 } info;
7946 DWORD data;
7947 } version;
7949 /* Cache the module handle of Emacs itself. */
7950 hinst = GetModuleHandle (NULL);
7952 /* Cache the version of the operating system. */
7953 version.data = GetVersion ();
7954 w32_major_version = version.info.major;
7955 w32_minor_version = version.info.minor;
7957 if (version.info.platform & 0x8000)
7958 os_subtype = OS_9X;
7959 else
7960 os_subtype = OS_NT;
7962 /* Cache page size, allocation unit, processor type, etc. */
7963 GetSystemInfo (&sysinfo_cache);
7964 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
7966 /* Cache os info. */
7967 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7968 GetVersionEx (&osinfo_cache);
7970 w32_build_number = osinfo_cache.dwBuildNumber;
7971 if (os_subtype == OS_9X)
7972 w32_build_number &= 0xffff;
7974 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
7977 #ifdef EMACSDEBUG
7978 void
7979 _DebPrint (const char *fmt, ...)
7981 char buf[1024];
7982 va_list args;
7984 va_start (args, fmt);
7985 vsprintf (buf, fmt, args);
7986 va_end (args);
7987 #if CYGWIN
7988 fprintf (stderr, "%s", buf);
7989 #endif
7990 OutputDebugString (buf);
7992 #endif
7995 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
7997 int cur_state = (GetKeyState (vk_code) & 1);
7999 if (NILP (new_state)
8000 || (NUMBERP (new_state)
8001 && ((XUINT (new_state)) & 1) != cur_state))
8003 #ifdef WINDOWSNT
8004 faked_key = vk_code;
8005 #endif /* WINDOWSNT */
8007 keybd_event ((BYTE) vk_code,
8008 (BYTE) MapVirtualKey (vk_code, 0),
8009 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8010 keybd_event ((BYTE) vk_code,
8011 (BYTE) MapVirtualKey (vk_code, 0),
8012 KEYEVENTF_EXTENDEDKEY | 0, 0);
8013 keybd_event ((BYTE) vk_code,
8014 (BYTE) MapVirtualKey (vk_code, 0),
8015 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
8016 cur_state = !cur_state;
8019 return cur_state;
8022 /* Translate console modifiers to emacs modifiers.
8023 German keyboard support (Kai Morgan Zeise 2/18/95). */
8025 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
8027 int retval = 0;
8029 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
8030 pressed, first remove those modifiers. */
8031 if (!NILP (Vw32_recognize_altgr)
8032 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8033 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
8034 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
8036 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
8037 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
8039 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8041 retval |= ctrl_modifier;
8042 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8043 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
8044 retval |= meta_modifier;
8047 if (mods & LEFT_WIN_PRESSED)
8048 retval |= w32_key_to_modifier (VK_LWIN);
8049 if (mods & RIGHT_WIN_PRESSED)
8050 retval |= w32_key_to_modifier (VK_RWIN);
8051 if (mods & APPS_PRESSED)
8052 retval |= w32_key_to_modifier (VK_APPS);
8053 if (mods & SCROLLLOCK_ON)
8054 retval |= w32_key_to_modifier (VK_SCROLL);
8056 /* Just in case someone wanted the original behavior, make it
8057 optional by setting w32-capslock-is-shiftlock to t. */
8058 if (NILP (Vw32_capslock_is_shiftlock)
8059 /* Keys that should _not_ be affected by CapsLock. */
8060 && ( (key == VK_BACK)
8061 || (key == VK_TAB)
8062 || (key == VK_CLEAR)
8063 || (key == VK_RETURN)
8064 || (key == VK_ESCAPE)
8065 || ((key >= VK_SPACE) && (key <= VK_HELP))
8066 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
8067 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
8070 /* Only consider shift state. */
8071 if ((mods & SHIFT_PRESSED) != 0)
8072 retval |= shift_modifier;
8074 else
8076 /* Ignore CapsLock state if not enabled. */
8077 if (NILP (Vw32_enable_caps_lock))
8078 mods &= ~CAPSLOCK_ON;
8079 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
8080 retval |= shift_modifier;
8083 return retval;
8086 /* The return code indicates key code size. cpID is the codepage to
8087 use for translation to Unicode; -1 means use the current console
8088 input codepage. */
8090 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
8092 unsigned int key_code = event->wVirtualKeyCode;
8093 unsigned int mods = event->dwControlKeyState;
8094 BYTE keystate[256];
8095 static BYTE ansi_code[4];
8096 static int isdead = 0;
8098 if (isdead == 2)
8100 event->uChar.AsciiChar = ansi_code[2];
8101 isdead = 0;
8102 return 1;
8104 if (event->uChar.AsciiChar != 0)
8105 return 1;
8107 memset (keystate, 0, sizeof (keystate));
8108 keystate[key_code] = 0x80;
8109 if (mods & SHIFT_PRESSED)
8110 keystate[VK_SHIFT] = 0x80;
8111 if (mods & CAPSLOCK_ON)
8112 keystate[VK_CAPITAL] = 1;
8113 /* If we recognize right-alt and left-ctrl as AltGr, set the key
8114 states accordingly before invoking ToAscii. */
8115 if (!NILP (Vw32_recognize_altgr)
8116 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
8118 keystate[VK_CONTROL] = 0x80;
8119 keystate[VK_LCONTROL] = 0x80;
8120 keystate[VK_MENU] = 0x80;
8121 keystate[VK_RMENU] = 0x80;
8124 #if 0
8125 /* Because of an OS bug, ToAscii corrupts the stack when called to
8126 convert a dead key in console mode on NT4. Unfortunately, trying
8127 to check for dead keys using MapVirtualKey doesn't work either -
8128 these functions apparently use internal information about keyboard
8129 layout which doesn't get properly updated in console programs when
8130 changing layout (though apparently it gets partly updated,
8131 otherwise ToAscii wouldn't crash). */
8132 if (is_dead_key (event->wVirtualKeyCode))
8133 return 0;
8134 #endif
8136 /* On NT, call ToUnicode instead and then convert to the current
8137 console input codepage. */
8138 if (os_subtype == OS_NT)
8140 WCHAR buf[128];
8142 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
8143 keystate, buf, 128, 0);
8144 if (isdead > 0)
8146 /* When we are called from the GUI message processing code,
8147 we are passed the current keyboard codepage, a positive
8148 number, to use below. */
8149 if (cpId == -1)
8150 cpId = GetConsoleCP ();
8152 event->uChar.UnicodeChar = buf[isdead - 1];
8153 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8154 ansi_code, 4, NULL, NULL);
8156 else
8157 isdead = 0;
8159 else
8161 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8162 keystate, (LPWORD) ansi_code, 0);
8165 if (isdead == 0)
8166 return 0;
8167 event->uChar.AsciiChar = ansi_code[0];
8168 return isdead;
8172 void
8173 w32_sys_ring_bell (struct frame *f)
8175 if (sound_type == 0xFFFFFFFF)
8177 Beep (666, 100);
8179 else if (sound_type == MB_EMACS_SILENT)
8181 /* Do nothing. */
8183 else
8184 MessageBeep (sound_type);
8188 /***********************************************************************
8189 Initialization
8190 ***********************************************************************/
8192 /* Keep this list in the same order as frame_parms in frame.c.
8193 Use 0 for unsupported frame parameters. */
8195 frame_parm_handler w32_frame_parm_handlers[] =
8197 x_set_autoraise,
8198 x_set_autolower,
8199 x_set_background_color,
8200 x_set_border_color,
8201 x_set_border_width,
8202 x_set_cursor_color,
8203 x_set_cursor_type,
8204 x_set_font,
8205 x_set_foreground_color,
8206 x_set_icon_name,
8207 x_set_icon_type,
8208 x_set_internal_border_width,
8209 x_set_right_divider_width,
8210 x_set_bottom_divider_width,
8211 x_set_menu_bar_lines,
8212 x_set_mouse_color,
8213 x_explicitly_set_name,
8214 x_set_scroll_bar_width,
8215 x_set_scroll_bar_height,
8216 x_set_title,
8217 x_set_unsplittable,
8218 x_set_vertical_scroll_bars,
8219 x_set_horizontal_scroll_bars,
8220 x_set_visibility,
8221 x_set_tool_bar_lines,
8222 0, /* x_set_scroll_bar_foreground, */
8223 0, /* x_set_scroll_bar_background, */
8224 x_set_screen_gamma,
8225 x_set_line_spacing,
8226 x_set_left_fringe,
8227 x_set_right_fringe,
8228 0, /* x_set_wait_for_wm, */
8229 x_set_fullscreen,
8230 x_set_font_backend,
8231 x_set_alpha,
8232 0, /* x_set_sticky */
8233 0, /* x_set_tool_bar_position */
8236 void
8237 syms_of_w32fns (void)
8239 globals_of_w32fns ();
8240 track_mouse_window = NULL;
8242 w32_visible_system_caret_hwnd = NULL;
8244 DEFSYM (Qundefined_color, "undefined-color");
8245 DEFSYM (Qcancel_timer, "cancel-timer");
8246 DEFSYM (Qhyper, "hyper");
8247 DEFSYM (Qsuper, "super");
8248 DEFSYM (Qmeta, "meta");
8249 DEFSYM (Qalt, "alt");
8250 DEFSYM (Qctrl, "ctrl");
8251 DEFSYM (Qcontrol, "control");
8252 DEFSYM (Qshift, "shift");
8253 DEFSYM (Qfont_param, "font-parameter");
8254 DEFSYM (Qgeometry, "geometry");
8255 DEFSYM (Qworkarea, "workarea");
8256 DEFSYM (Qmm_size, "mm-size");
8257 DEFSYM (Qframes, "frames");
8259 Fput (Qundefined_color, Qerror_conditions,
8260 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8261 Fput (Qundefined_color, Qerror_message,
8262 build_pure_c_string ("Undefined color"));
8264 staticpro (&w32_grabbed_keys);
8265 w32_grabbed_keys = Qnil;
8267 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8268 doc: /* An array of color name mappings for Windows. */);
8269 Vw32_color_map = Qnil;
8271 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8272 doc: /* Non-nil if Alt key presses are passed on to Windows.
8273 When non-nil, for example, Alt pressed and released and then space will
8274 open the System menu. When nil, Emacs processes the Alt key events, and
8275 then silently swallows them. */);
8276 Vw32_pass_alt_to_system = Qnil;
8278 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8279 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8280 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8281 Vw32_alt_is_meta = Qt;
8283 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8284 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8285 w32_quit_key = 0;
8287 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8288 Vw32_pass_lwindow_to_system,
8289 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8291 When non-nil, the Start menu is opened by tapping the key.
8292 If you set this to nil, the left \"Windows\" key is processed by Emacs
8293 according to the value of `w32-lwindow-modifier', which see.
8295 Note that some combinations of the left \"Windows\" key with other keys are
8296 caught by Windows at low level, and so binding them in Emacs will have no
8297 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8298 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8299 the doc string of `w32-phantom-key-code'. */);
8300 Vw32_pass_lwindow_to_system = Qt;
8302 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8303 Vw32_pass_rwindow_to_system,
8304 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8306 When non-nil, the Start menu is opened by tapping the key.
8307 If you set this to nil, the right \"Windows\" key is processed by Emacs
8308 according to the value of `w32-rwindow-modifier', which see.
8310 Note that some combinations of the right \"Windows\" key with other keys are
8311 caught by Windows at low level, and so binding them in Emacs will have no
8312 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8313 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8314 the doc string of `w32-phantom-key-code'. */);
8315 Vw32_pass_rwindow_to_system = Qt;
8317 DEFVAR_LISP ("w32-phantom-key-code",
8318 Vw32_phantom_key_code,
8319 doc: /* Virtual key code used to generate \"phantom\" key presses.
8320 Value is a number between 0 and 255.
8322 Phantom key presses are generated in order to stop the system from
8323 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8324 `w32-pass-rwindow-to-system' is nil. */);
8325 /* Although 255 is technically not a valid key code, it works and
8326 means that this hack won't interfere with any real key code. */
8327 XSETINT (Vw32_phantom_key_code, 255);
8329 DEFVAR_LISP ("w32-enable-num-lock",
8330 Vw32_enable_num_lock,
8331 doc: /* If non-nil, the Num Lock key acts normally.
8332 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8333 Vw32_enable_num_lock = Qt;
8335 DEFVAR_LISP ("w32-enable-caps-lock",
8336 Vw32_enable_caps_lock,
8337 doc: /* If non-nil, the Caps Lock key acts normally.
8338 Set to nil to handle Caps Lock as the `capslock' key. */);
8339 Vw32_enable_caps_lock = Qt;
8341 DEFVAR_LISP ("w32-scroll-lock-modifier",
8342 Vw32_scroll_lock_modifier,
8343 doc: /* Modifier to use for the Scroll Lock ON state.
8344 The value can be hyper, super, meta, alt, control or shift for the
8345 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8346 Any other value will cause the Scroll Lock key to be ignored. */);
8347 Vw32_scroll_lock_modifier = Qnil;
8349 DEFVAR_LISP ("w32-lwindow-modifier",
8350 Vw32_lwindow_modifier,
8351 doc: /* Modifier to use for the left \"Windows\" key.
8352 The value can be hyper, super, meta, alt, control or shift for the
8353 respective modifier, or nil to appear as the `lwindow' key.
8354 Any other value will cause the key to be ignored. */);
8355 Vw32_lwindow_modifier = Qnil;
8357 DEFVAR_LISP ("w32-rwindow-modifier",
8358 Vw32_rwindow_modifier,
8359 doc: /* Modifier to use for the right \"Windows\" key.
8360 The value can be hyper, super, meta, alt, control or shift for the
8361 respective modifier, or nil to appear as the `rwindow' key.
8362 Any other value will cause the key to be ignored. */);
8363 Vw32_rwindow_modifier = Qnil;
8365 DEFVAR_LISP ("w32-apps-modifier",
8366 Vw32_apps_modifier,
8367 doc: /* Modifier to use for the \"Apps\" key.
8368 The value can be hyper, super, meta, alt, control or shift for the
8369 respective modifier, or nil to appear as the `apps' key.
8370 Any other value will cause the key to be ignored. */);
8371 Vw32_apps_modifier = Qnil;
8373 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
8374 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8375 w32_enable_synthesized_fonts = 0;
8377 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
8378 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8379 Vw32_enable_palette = Qt;
8381 DEFVAR_INT ("w32-mouse-button-tolerance",
8382 w32_mouse_button_tolerance,
8383 doc: /* Analogue of double click interval for faking middle mouse events.
8384 The value is the minimum time in milliseconds that must elapse between
8385 left and right button down events before they are considered distinct events.
8386 If both mouse buttons are depressed within this interval, a middle mouse
8387 button down event is generated instead. */);
8388 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8390 DEFVAR_INT ("w32-mouse-move-interval",
8391 w32_mouse_move_interval,
8392 doc: /* Minimum interval between mouse move events.
8393 The value is the minimum time in milliseconds that must elapse between
8394 successive mouse move (or scroll bar drag) events before they are
8395 reported as lisp events. */);
8396 w32_mouse_move_interval = 0;
8398 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8399 w32_pass_extra_mouse_buttons_to_system,
8400 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8401 Recent versions of Windows support mice with up to five buttons.
8402 Since most applications don't support these extra buttons, most mouse
8403 drivers will allow you to map them to functions at the system level.
8404 If this variable is non-nil, Emacs will pass them on, allowing the
8405 system to handle them. */);
8406 w32_pass_extra_mouse_buttons_to_system = 0;
8408 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8409 w32_pass_multimedia_buttons_to_system,
8410 doc: /* If non-nil, media buttons are passed to Windows.
8411 Some modern keyboards contain buttons for controlling media players, web
8412 browsers and other applications. Generally these buttons are handled on a
8413 system wide basis, but by setting this to nil they are made available
8414 to Emacs for binding. Depending on your keyboard, additional keys that
8415 may be available are:
8417 browser-back, browser-forward, browser-refresh, browser-stop,
8418 browser-search, browser-favorites, browser-home,
8419 mail, mail-reply, mail-forward, mail-send,
8420 app-1, app-2,
8421 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8422 spell-check, correction-list, toggle-dictate-command,
8423 media-next, media-previous, media-stop, media-play-pause, media-select,
8424 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8425 media-channel-up, media-channel-down,
8426 volume-mute, volume-up, volume-down,
8427 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8428 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8429 w32_pass_multimedia_buttons_to_system = 1;
8431 #if 0 /* TODO: Mouse cursor customization. */
8432 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
8433 doc: /* The shape of the pointer when over text.
8434 Changing the value does not affect existing frames
8435 unless you set the mouse color. */);
8436 Vx_pointer_shape = Qnil;
8438 Vx_nontext_pointer_shape = Qnil;
8440 Vx_mode_pointer_shape = Qnil;
8442 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
8443 doc: /* The shape of the pointer when Emacs is busy.
8444 This variable takes effect when you create a new frame
8445 or when you set the mouse color. */);
8446 Vx_hourglass_pointer_shape = Qnil;
8448 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8449 Vx_sensitive_text_pointer_shape,
8450 doc: /* The shape of the pointer when over mouse-sensitive text.
8451 This variable takes effect when you create a new frame
8452 or when you set the mouse color. */);
8453 Vx_sensitive_text_pointer_shape = Qnil;
8455 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8456 Vx_window_horizontal_drag_shape,
8457 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8458 This variable takes effect when you create a new frame
8459 or when you set the mouse color. */);
8460 Vx_window_horizontal_drag_shape = Qnil;
8462 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8463 Vx_window_vertical_drag_shape,
8464 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8465 This variable takes effect when you create a new frame
8466 or when you set the mouse color. */);
8467 Vx_window_vertical_drag_shape = Qnil;
8468 #endif
8470 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
8471 doc: /* A string indicating the foreground color of the cursor box. */);
8472 Vx_cursor_fore_pixel = Qnil;
8474 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
8475 doc: /* Maximum size for tooltips.
8476 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8477 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8479 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
8480 doc: /* Non-nil if no window manager is in use.
8481 Emacs doesn't try to figure this out; this is always nil
8482 unless you set it to something else. */);
8483 /* We don't have any way to find this out, so set it to nil
8484 and maybe the user would like to set it to t. */
8485 Vx_no_window_manager = Qnil;
8487 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8488 Vx_pixel_size_width_font_regexp,
8489 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8491 Since Emacs gets width of a font matching with this regexp from
8492 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8493 such a font. This is especially effective for such large fonts as
8494 Chinese, Japanese, and Korean. */);
8495 Vx_pixel_size_width_font_regexp = Qnil;
8497 DEFVAR_LISP ("w32-bdf-filename-alist",
8498 Vw32_bdf_filename_alist,
8499 doc: /* List of bdf fonts and their corresponding filenames. */);
8500 Vw32_bdf_filename_alist = Qnil;
8502 DEFVAR_BOOL ("w32-strict-fontnames",
8503 w32_strict_fontnames,
8504 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8505 Default is nil, which allows old fontnames that are not XLFD compliant,
8506 and allows third-party CJK display to work by specifying false charset
8507 fields to trick Emacs into translating to Big5, SJIS etc.
8508 Setting this to t will prevent wrong fonts being selected when
8509 fontsets are automatically created. */);
8510 w32_strict_fontnames = 0;
8512 DEFVAR_BOOL ("w32-strict-painting",
8513 w32_strict_painting,
8514 doc: /* Non-nil means use strict rules for repainting frames.
8515 Set this to nil to get the old behavior for repainting; this should
8516 only be necessary if the default setting causes problems. */);
8517 w32_strict_painting = 1;
8519 #if 0 /* TODO: Port to W32 */
8520 defsubr (&Sx_change_window_property);
8521 defsubr (&Sx_delete_window_property);
8522 defsubr (&Sx_window_property);
8523 #endif
8524 defsubr (&Sxw_display_color_p);
8525 defsubr (&Sx_display_grayscale_p);
8526 defsubr (&Sxw_color_defined_p);
8527 defsubr (&Sxw_color_values);
8528 defsubr (&Sx_server_max_request_size);
8529 defsubr (&Sx_server_vendor);
8530 defsubr (&Sx_server_version);
8531 defsubr (&Sx_display_pixel_width);
8532 defsubr (&Sx_display_pixel_height);
8533 defsubr (&Sx_display_mm_width);
8534 defsubr (&Sx_display_mm_height);
8535 defsubr (&Sx_display_screens);
8536 defsubr (&Sx_display_planes);
8537 defsubr (&Sx_display_color_cells);
8538 defsubr (&Sx_display_visual_class);
8539 defsubr (&Sx_display_backing_store);
8540 defsubr (&Sx_display_save_under);
8541 defsubr (&Sx_create_frame);
8542 defsubr (&Sx_open_connection);
8543 defsubr (&Sx_close_connection);
8544 defsubr (&Sx_display_list);
8545 defsubr (&Sx_frame_geometry);
8546 defsubr (&Sx_synchronize);
8548 /* W32 specific functions */
8550 defsubr (&Sw32_define_rgb_color);
8551 defsubr (&Sw32_default_color_map);
8552 defsubr (&Sw32_display_monitor_attributes_list);
8553 defsubr (&Sw32_send_sys_command);
8554 defsubr (&Sw32_shell_execute);
8555 defsubr (&Sw32_register_hot_key);
8556 defsubr (&Sw32_unregister_hot_key);
8557 defsubr (&Sw32_registered_hot_keys);
8558 defsubr (&Sw32_reconstruct_hot_key);
8559 defsubr (&Sw32_toggle_lock_key);
8560 defsubr (&Sw32_window_exists_p);
8561 defsubr (&Sw32_frame_rect);
8562 defsubr (&Sw32_frame_menu_bar_size);
8563 defsubr (&Sw32_battery_status);
8565 #ifdef WINDOWSNT
8566 defsubr (&Sfile_system_info);
8567 defsubr (&Sdefault_printer_name);
8568 #endif
8570 defsubr (&Sset_message_beep);
8571 defsubr (&Sx_show_tip);
8572 defsubr (&Sx_hide_tip);
8573 tip_timer = Qnil;
8574 staticpro (&tip_timer);
8575 tip_frame = Qnil;
8576 staticpro (&tip_frame);
8578 last_show_tip_args = Qnil;
8579 staticpro (&last_show_tip_args);
8581 defsubr (&Sx_file_dialog);
8582 #ifdef WINDOWSNT
8583 defsubr (&Ssystem_move_file_to_trash);
8584 #endif
8589 /* Crashing and reporting backtrace. */
8591 #ifndef CYGWIN
8592 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8593 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8594 #endif
8595 static DWORD except_code;
8596 static PVOID except_addr;
8598 #ifndef CYGWIN
8599 /* This handler records the exception code and the address where it
8600 was triggered so that this info could be included in the backtrace.
8601 Without that, the backtrace in some cases has no information
8602 whatsoever about the offending code, and looks as if the top-level
8603 exception handler in the MinGW startup code di the one that
8604 crashed. */
8605 static LONG CALLBACK
8606 my_exception_handler (EXCEPTION_POINTERS * exception_data)
8608 except_code = exception_data->ExceptionRecord->ExceptionCode;
8609 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8611 if (prev_exception_handler)
8612 return prev_exception_handler (exception_data);
8613 return EXCEPTION_EXECUTE_HANDLER;
8615 #endif
8617 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8618 PULONG);
8620 #define BACKTRACE_LIMIT_MAX 62
8623 w32_backtrace (void **buffer, int limit)
8625 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8626 HMODULE hm_kernel32 = NULL;
8628 if (!s_pfn_CaptureStackBackTrace)
8630 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8631 s_pfn_CaptureStackBackTrace =
8632 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8633 "RtlCaptureStackBackTrace");
8635 if (s_pfn_CaptureStackBackTrace)
8636 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8637 buffer, NULL);
8638 return 0;
8641 void
8642 emacs_abort (void)
8644 int button;
8645 button = MessageBox (NULL,
8646 "A fatal error has occurred!\n\n"
8647 "Would you like to attach a debugger?\n\n"
8648 "Select:\n"
8649 "YES -- to debug Emacs, or\n"
8650 "NO -- to abort Emacs and produce a backtrace\n"
8651 " (emacs_backtrace.txt in current directory)."
8652 #if __GNUC__
8653 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8654 "\"continue\" inside GDB before clicking YES.)"
8655 #endif
8656 , "Emacs Abort Dialog",
8657 MB_ICONEXCLAMATION | MB_TASKMODAL
8658 | MB_SETFOREGROUND | MB_YESNO);
8659 switch (button)
8661 case IDYES:
8662 DebugBreak ();
8663 exit (2); /* tell the compiler we will never return */
8664 case IDNO:
8665 default:
8667 void *stack[BACKTRACE_LIMIT_MAX + 1];
8668 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8670 if (i)
8672 int errfile_fd = -1;
8673 int j;
8674 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
8675 /* The type below should really be 'void *', but
8676 INT_BUFSIZE_BOUND cannot handle that without
8677 triggering compiler warnings (under certain
8678 pedantic warning switches), it wants an
8679 integer type. */
8680 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
8681 #ifdef CYGWIN
8682 int stderr_fd = 2;
8683 #else
8684 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
8685 int stderr_fd = -1;
8687 if (errout && errout != INVALID_HANDLE_VALUE)
8688 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
8689 #endif
8691 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8692 but not on Windows 7. addr2line doesn't mind a missing
8693 "0x", but will be confused by an extra one. */
8694 if (except_addr)
8695 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8696 except_code, except_addr);
8697 if (stderr_fd >= 0)
8699 if (except_addr)
8700 write (stderr_fd, buf, strlen (buf));
8701 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8703 #ifdef CYGWIN
8704 #define _open open
8705 #endif
8706 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8707 if (errfile_fd >= 0)
8709 lseek (errfile_fd, 0L, SEEK_END);
8710 if (except_addr)
8711 write (errfile_fd, buf, strlen (buf));
8712 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8715 for (j = 0; j < i; j++)
8717 /* stack[] gives the return addresses, whereas we want
8718 the address of the call, so decrease each address
8719 by approximate size of 1 CALL instruction. */
8720 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
8721 if (stderr_fd >= 0)
8722 write (stderr_fd, buf, strlen (buf));
8723 if (errfile_fd >= 0)
8724 write (errfile_fd, buf, strlen (buf));
8726 if (i == BACKTRACE_LIMIT_MAX)
8728 if (stderr_fd >= 0)
8729 write (stderr_fd, "...\r\n", 5);
8730 if (errfile_fd >= 0)
8731 write (errfile_fd, "...\r\n", 5);
8733 if (errfile_fd >= 0)
8734 close (errfile_fd);
8736 abort ();
8737 break;
8744 /* Initialization. */
8747 globals_of_w32fns is used to initialize those global variables that
8748 must always be initialized on startup even when the global variable
8749 initialized is non zero (see the function main in emacs.c).
8750 globals_of_w32fns is called from syms_of_w32fns when the global
8751 variable initialized is 0 and directly from main when initialized
8752 is non zero.
8754 void
8755 globals_of_w32fns (void)
8757 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8759 TrackMouseEvent not available in all versions of Windows, so must load
8760 it dynamically. Do it once, here, instead of every time it is used.
8762 track_mouse_event_fn = (TrackMouseEvent_Proc)
8763 GetProcAddress (user32_lib, "TrackMouseEvent");
8765 monitor_from_point_fn = (MonitorFromPoint_Proc)
8766 GetProcAddress (user32_lib, "MonitorFromPoint");
8767 get_monitor_info_fn = (GetMonitorInfo_Proc)
8768 GetProcAddress (user32_lib, "GetMonitorInfoA");
8769 monitor_from_window_fn = (MonitorFromWindow_Proc)
8770 GetProcAddress (user32_lib, "MonitorFromWindow");
8771 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8772 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8775 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8776 get_composition_string_fn = (ImmGetCompositionString_Proc)
8777 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8778 get_ime_context_fn = (ImmGetContext_Proc)
8779 GetProcAddress (imm32_lib, "ImmGetContext");
8780 release_ime_context_fn = (ImmReleaseContext_Proc)
8781 GetProcAddress (imm32_lib, "ImmReleaseContext");
8782 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8783 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8786 except_code = 0;
8787 except_addr = 0;
8788 #ifndef CYGWIN
8789 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8790 #endif
8792 DEFVAR_INT ("w32-ansi-code-page",
8793 w32_ansi_code_page,
8794 doc: /* The ANSI code page used by the system. */);
8795 w32_ansi_code_page = GetACP ();
8797 if (os_subtype == OS_NT)
8798 w32_unicode_gui = 1;
8799 else
8800 w32_unicode_gui = 0;
8802 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8803 InitCommonControls ();
8805 syms_of_w32uniscribe ();
8808 #ifdef NTGUI_UNICODE
8810 Lisp_Object
8811 ntgui_encode_system (Lisp_Object str)
8813 Lisp_Object encoded;
8814 to_unicode (str, &encoded);
8815 return encoded;
8818 #endif /* NTGUI_UNICODE */