Bump version to 24.4.91
[emacs.git] / src / w32fns.c
blobed110317d170c1a45d28fe98e7eeb2876d2d0ea0
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 /* If non-NULL, a handle to a frame where to display the hourglass cursor. */
93 static HWND hourglass_hwnd = NULL;
95 #ifndef IDC_HAND
96 #define IDC_HAND MAKEINTRESOURCE(32649)
97 #endif
99 Lisp_Object Qsuppress_icon;
100 Lisp_Object Qundefined_color;
101 Lisp_Object Qcancel_timer;
102 Lisp_Object Qfont_param;
103 Lisp_Object Qhyper;
104 Lisp_Object Qsuper;
105 Lisp_Object Qmeta;
106 Lisp_Object Qalt;
107 Lisp_Object Qctrl;
108 Lisp_Object Qcontrol;
109 Lisp_Object Qshift;
110 static Lisp_Object Qgeometry, Qworkarea, Qmm_size, Qframes;
113 /* Prefix for system colors. */
114 #define SYSTEM_COLOR_PREFIX "System"
115 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
117 /* State variables for emulating a three button mouse. */
118 #define LMOUSE 1
119 #define MMOUSE 2
120 #define RMOUSE 4
122 static int button_state = 0;
123 static W32Msg saved_mouse_button_msg;
124 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
125 static W32Msg saved_mouse_move_msg;
126 static unsigned mouse_move_timer = 0;
128 /* Window that is tracking the mouse. */
129 static HWND track_mouse_window;
131 /* Multi-monitor API definitions that are not pulled from the headers
132 since we are compiling for NT 4. */
133 #ifndef MONITOR_DEFAULT_TO_NEAREST
134 #define MONITOR_DEFAULT_TO_NEAREST 2
135 #endif
136 #ifndef MONITORINFOF_PRIMARY
137 #define MONITORINFOF_PRIMARY 1
138 #endif
139 #ifndef SM_XVIRTUALSCREEN
140 #define SM_XVIRTUALSCREEN 76
141 #endif
142 #ifndef SM_YVIRTUALSCREEN
143 #define SM_YVIRTUALSCREEN 77
144 #endif
145 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
146 To avoid a compile error on one or the other, redefine with a new name. */
147 struct MONITOR_INFO
149 DWORD cbSize;
150 RECT rcMonitor;
151 RECT rcWork;
152 DWORD dwFlags;
155 #ifndef CCHDEVICENAME
156 #define CCHDEVICENAME 32
157 #endif
158 struct MONITOR_INFO_EX
160 DWORD cbSize;
161 RECT rcMonitor;
162 RECT rcWork;
163 DWORD dwFlags;
164 char szDevice[CCHDEVICENAME];
167 /* Reportedly, MSVC does not have this in its headers. */
168 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
169 DECLARE_HANDLE(HMONITOR);
170 #endif
172 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
173 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
174 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
175 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
176 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
177 typedef HWND (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
178 typedef HWND (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
179 IN COMPOSITIONFORM *form);
180 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
181 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
182 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
183 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
184 (IN HWND hwnd, IN DWORD dwFlags);
185 typedef BOOL CALLBACK (* MonitorEnum_Proc)
186 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
187 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
188 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
190 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
191 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
192 ImmGetContext_Proc get_ime_context_fn = NULL;
193 ImmReleaseContext_Proc release_ime_context_fn = NULL;
194 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
195 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
196 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
197 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
198 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
200 #ifdef NTGUI_UNICODE
201 #define unicode_append_menu AppendMenuW
202 #else /* !NTGUI_UNICODE */
203 extern AppendMenuW_Proc unicode_append_menu;
204 #endif /* NTGUI_UNICODE */
206 /* Flag to selectively ignore WM_IME_CHAR messages. */
207 static int ignore_ime_char = 0;
209 /* W95 mousewheel handler */
210 unsigned int msh_mousewheel = 0;
212 /* Timers */
213 #define MOUSE_BUTTON_ID 1
214 #define MOUSE_MOVE_ID 2
215 #define MENU_FREE_ID 3
216 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
217 is received. */
218 #define MENU_FREE_DELAY 1000
219 static unsigned menu_free_timer = 0;
221 #ifdef GLYPH_DEBUG
222 static int image_cache_refcount, dpyinfo_refcount;
223 #endif
225 static HWND w32_visible_system_caret_hwnd;
227 static int w32_unicode_gui;
229 /* From w32menu.c */
230 extern HMENU current_popup_menu;
231 static int menubar_in_use = 0;
233 /* From w32uniscribe.c */
234 extern void syms_of_w32uniscribe (void);
235 extern int uniscribe_available;
237 /* Function prototypes for hourglass support. */
238 static void w32_show_hourglass (struct frame *);
239 static void w32_hide_hourglass (void);
241 #ifdef WINDOWSNT
242 /* From w32inevt.c */
243 extern int faked_key;
244 #endif /* WINDOWSNT */
246 /* This gives us the page size and the size of the allocation unit on NT. */
247 SYSTEM_INFO sysinfo_cache;
249 /* This gives us version, build, and platform identification. */
250 OSVERSIONINFO osinfo_cache;
252 DWORD_PTR syspage_mask = 0;
254 /* The major and minor versions of NT. */
255 int w32_major_version;
256 int w32_minor_version;
257 int w32_build_number;
259 /* Distinguish between Windows NT and Windows 95. */
260 int os_subtype;
262 #ifdef HAVE_NTGUI
263 HINSTANCE hinst = NULL;
264 #endif
266 static unsigned int sound_type = 0xFFFFFFFF;
267 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
269 /* Let the user specify a display with a frame.
270 nil stands for the selected frame--or, if that is not a w32 frame,
271 the first display on the list. */
273 struct w32_display_info *
274 check_x_display_info (Lisp_Object frame)
276 if (NILP (frame))
278 struct frame *sf = XFRAME (selected_frame);
280 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
281 return FRAME_DISPLAY_INFO (sf);
282 else
283 return &one_w32_display_info;
285 else if (STRINGP (frame))
286 return x_display_info_for_name (frame);
287 else
289 struct frame *f;
291 CHECK_LIVE_FRAME (frame);
292 f = XFRAME (frame);
293 if (! FRAME_W32_P (f))
294 error ("Non-W32 frame used");
295 return FRAME_DISPLAY_INFO (f);
299 /* Return the Emacs frame-object corresponding to an w32 window.
300 It could be the frame's main window or an icon window. */
302 struct frame *
303 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
305 Lisp_Object tail, frame;
306 struct frame *f;
308 FOR_EACH_FRAME (tail, frame)
310 f = XFRAME (frame);
311 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
312 continue;
314 if (FRAME_W32_WINDOW (f) == wdesc)
315 return f;
317 return 0;
321 static Lisp_Object unwind_create_frame (Lisp_Object);
322 static void unwind_create_tip_frame (Lisp_Object);
323 static void my_create_window (struct frame *);
324 static void my_create_tip_window (struct frame *);
326 /* TODO: Native Input Method support; see x_create_im. */
327 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
328 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
329 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
330 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
331 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
332 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
333 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
334 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
335 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
336 void x_set_menu_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
337 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
338 void x_set_tool_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
343 /* Store the screen positions of frame F into XPTR and YPTR.
344 These are the positions of the containing window manager window,
345 not Emacs's own window. */
347 void
348 x_real_positions (struct frame *f, int *xptr, int *yptr)
350 POINT pt;
351 RECT rect;
353 /* Get the bounds of the WM window. */
354 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
356 pt.x = 0;
357 pt.y = 0;
359 /* Convert (0, 0) in the client area to screen co-ordinates. */
360 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
362 /* Remember x_pixels_diff and y_pixels_diff. */
363 f->x_pixels_diff = pt.x - rect.left;
364 f->y_pixels_diff = pt.y - rect.top;
366 *xptr = rect.left;
367 *yptr = rect.top;
370 /* Returns the window rectangle appropriate for the given fullscreen mode.
371 The normal rect parameter was the window's rectangle prior to entering
372 fullscreen mode. If multiple monitor support is available, the nearest
373 monitor to the window is chosen. */
375 void
376 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
378 struct MONITOR_INFO mi = { sizeof(mi) };
379 if (monitor_from_window_fn && get_monitor_info_fn)
381 HMONITOR monitor =
382 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
383 get_monitor_info_fn (monitor, &mi);
385 else
387 mi.rcMonitor.left = 0;
388 mi.rcMonitor.top = 0;
389 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
390 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
391 mi.rcWork.left = 0;
392 mi.rcWork.top = 0;
393 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
394 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
397 switch (fsmode)
399 case FULLSCREEN_BOTH:
400 rect->left = mi.rcMonitor.left;
401 rect->top = mi.rcMonitor.top;
402 rect->right = mi.rcMonitor.right;
403 rect->bottom = mi.rcMonitor.bottom;
404 break;
405 case FULLSCREEN_WIDTH:
406 rect->left = mi.rcWork.left;
407 rect->top = normal.top;
408 rect->right = mi.rcWork.right;
409 rect->bottom = normal.bottom;
410 break;
411 case FULLSCREEN_HEIGHT:
412 rect->left = normal.left;
413 rect->top = mi.rcWork.top;
414 rect->right = normal.right;
415 rect->bottom = mi.rcWork.bottom;
416 break;
417 default:
418 *rect = normal;
419 break;
425 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
426 Sw32_define_rgb_color, 4, 4, 0,
427 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
428 This adds or updates a named color to `w32-color-map', making it
429 available for use. The original entry's RGB ref is returned, or nil
430 if the entry is new. */)
431 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
433 Lisp_Object rgb;
434 Lisp_Object oldrgb = Qnil;
435 Lisp_Object entry;
437 CHECK_NUMBER (red);
438 CHECK_NUMBER (green);
439 CHECK_NUMBER (blue);
440 CHECK_STRING (name);
442 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
444 block_input ();
446 /* replace existing entry in w32-color-map or add new entry. */
447 entry = Fassoc (name, Vw32_color_map);
448 if (NILP (entry))
450 entry = Fcons (name, rgb);
451 Vw32_color_map = Fcons (entry, Vw32_color_map);
453 else
455 oldrgb = Fcdr (entry);
456 Fsetcdr (entry, rgb);
459 unblock_input ();
461 return (oldrgb);
464 /* The default colors for the w32 color map */
465 typedef struct colormap_t
467 char *name;
468 COLORREF colorref;
469 } colormap_t;
471 colormap_t w32_color_map[] =
473 {"snow" , PALETTERGB (255,250,250)},
474 {"ghost white" , PALETTERGB (248,248,255)},
475 {"GhostWhite" , PALETTERGB (248,248,255)},
476 {"white smoke" , PALETTERGB (245,245,245)},
477 {"WhiteSmoke" , PALETTERGB (245,245,245)},
478 {"gainsboro" , PALETTERGB (220,220,220)},
479 {"floral white" , PALETTERGB (255,250,240)},
480 {"FloralWhite" , PALETTERGB (255,250,240)},
481 {"old lace" , PALETTERGB (253,245,230)},
482 {"OldLace" , PALETTERGB (253,245,230)},
483 {"linen" , PALETTERGB (250,240,230)},
484 {"antique white" , PALETTERGB (250,235,215)},
485 {"AntiqueWhite" , PALETTERGB (250,235,215)},
486 {"papaya whip" , PALETTERGB (255,239,213)},
487 {"PapayaWhip" , PALETTERGB (255,239,213)},
488 {"blanched almond" , PALETTERGB (255,235,205)},
489 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
490 {"bisque" , PALETTERGB (255,228,196)},
491 {"peach puff" , PALETTERGB (255,218,185)},
492 {"PeachPuff" , PALETTERGB (255,218,185)},
493 {"navajo white" , PALETTERGB (255,222,173)},
494 {"NavajoWhite" , PALETTERGB (255,222,173)},
495 {"moccasin" , PALETTERGB (255,228,181)},
496 {"cornsilk" , PALETTERGB (255,248,220)},
497 {"ivory" , PALETTERGB (255,255,240)},
498 {"lemon chiffon" , PALETTERGB (255,250,205)},
499 {"LemonChiffon" , PALETTERGB (255,250,205)},
500 {"seashell" , PALETTERGB (255,245,238)},
501 {"honeydew" , PALETTERGB (240,255,240)},
502 {"mint cream" , PALETTERGB (245,255,250)},
503 {"MintCream" , PALETTERGB (245,255,250)},
504 {"azure" , PALETTERGB (240,255,255)},
505 {"alice blue" , PALETTERGB (240,248,255)},
506 {"AliceBlue" , PALETTERGB (240,248,255)},
507 {"lavender" , PALETTERGB (230,230,250)},
508 {"lavender blush" , PALETTERGB (255,240,245)},
509 {"LavenderBlush" , PALETTERGB (255,240,245)},
510 {"misty rose" , PALETTERGB (255,228,225)},
511 {"MistyRose" , PALETTERGB (255,228,225)},
512 {"white" , PALETTERGB (255,255,255)},
513 {"black" , PALETTERGB ( 0, 0, 0)},
514 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
515 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
516 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
517 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
518 {"dim gray" , PALETTERGB (105,105,105)},
519 {"DimGray" , PALETTERGB (105,105,105)},
520 {"dim grey" , PALETTERGB (105,105,105)},
521 {"DimGrey" , PALETTERGB (105,105,105)},
522 {"slate gray" , PALETTERGB (112,128,144)},
523 {"SlateGray" , PALETTERGB (112,128,144)},
524 {"slate grey" , PALETTERGB (112,128,144)},
525 {"SlateGrey" , PALETTERGB (112,128,144)},
526 {"light slate gray" , PALETTERGB (119,136,153)},
527 {"LightSlateGray" , PALETTERGB (119,136,153)},
528 {"light slate grey" , PALETTERGB (119,136,153)},
529 {"LightSlateGrey" , PALETTERGB (119,136,153)},
530 {"gray" , PALETTERGB (190,190,190)},
531 {"grey" , PALETTERGB (190,190,190)},
532 {"light grey" , PALETTERGB (211,211,211)},
533 {"LightGrey" , PALETTERGB (211,211,211)},
534 {"light gray" , PALETTERGB (211,211,211)},
535 {"LightGray" , PALETTERGB (211,211,211)},
536 {"midnight blue" , PALETTERGB ( 25, 25,112)},
537 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
538 {"navy" , PALETTERGB ( 0, 0,128)},
539 {"navy blue" , PALETTERGB ( 0, 0,128)},
540 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
541 {"cornflower blue" , PALETTERGB (100,149,237)},
542 {"CornflowerBlue" , PALETTERGB (100,149,237)},
543 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
544 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
545 {"slate blue" , PALETTERGB (106, 90,205)},
546 {"SlateBlue" , PALETTERGB (106, 90,205)},
547 {"medium slate blue" , PALETTERGB (123,104,238)},
548 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
549 {"light slate blue" , PALETTERGB (132,112,255)},
550 {"LightSlateBlue" , PALETTERGB (132,112,255)},
551 {"medium blue" , PALETTERGB ( 0, 0,205)},
552 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
553 {"royal blue" , PALETTERGB ( 65,105,225)},
554 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
555 {"blue" , PALETTERGB ( 0, 0,255)},
556 {"dodger blue" , PALETTERGB ( 30,144,255)},
557 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
558 {"deep sky blue" , PALETTERGB ( 0,191,255)},
559 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
560 {"sky blue" , PALETTERGB (135,206,235)},
561 {"SkyBlue" , PALETTERGB (135,206,235)},
562 {"light sky blue" , PALETTERGB (135,206,250)},
563 {"LightSkyBlue" , PALETTERGB (135,206,250)},
564 {"steel blue" , PALETTERGB ( 70,130,180)},
565 {"SteelBlue" , PALETTERGB ( 70,130,180)},
566 {"light steel blue" , PALETTERGB (176,196,222)},
567 {"LightSteelBlue" , PALETTERGB (176,196,222)},
568 {"light blue" , PALETTERGB (173,216,230)},
569 {"LightBlue" , PALETTERGB (173,216,230)},
570 {"powder blue" , PALETTERGB (176,224,230)},
571 {"PowderBlue" , PALETTERGB (176,224,230)},
572 {"pale turquoise" , PALETTERGB (175,238,238)},
573 {"PaleTurquoise" , PALETTERGB (175,238,238)},
574 {"dark turquoise" , PALETTERGB ( 0,206,209)},
575 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
576 {"medium turquoise" , PALETTERGB ( 72,209,204)},
577 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
578 {"turquoise" , PALETTERGB ( 64,224,208)},
579 {"cyan" , PALETTERGB ( 0,255,255)},
580 {"light cyan" , PALETTERGB (224,255,255)},
581 {"LightCyan" , PALETTERGB (224,255,255)},
582 {"cadet blue" , PALETTERGB ( 95,158,160)},
583 {"CadetBlue" , PALETTERGB ( 95,158,160)},
584 {"medium aquamarine" , PALETTERGB (102,205,170)},
585 {"MediumAquamarine" , PALETTERGB (102,205,170)},
586 {"aquamarine" , PALETTERGB (127,255,212)},
587 {"dark green" , PALETTERGB ( 0,100, 0)},
588 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
589 {"dark olive green" , PALETTERGB ( 85,107, 47)},
590 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
591 {"dark sea green" , PALETTERGB (143,188,143)},
592 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
593 {"sea green" , PALETTERGB ( 46,139, 87)},
594 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
595 {"medium sea green" , PALETTERGB ( 60,179,113)},
596 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
597 {"light sea green" , PALETTERGB ( 32,178,170)},
598 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
599 {"pale green" , PALETTERGB (152,251,152)},
600 {"PaleGreen" , PALETTERGB (152,251,152)},
601 {"spring green" , PALETTERGB ( 0,255,127)},
602 {"SpringGreen" , PALETTERGB ( 0,255,127)},
603 {"lawn green" , PALETTERGB (124,252, 0)},
604 {"LawnGreen" , PALETTERGB (124,252, 0)},
605 {"green" , PALETTERGB ( 0,255, 0)},
606 {"chartreuse" , PALETTERGB (127,255, 0)},
607 {"medium spring green" , PALETTERGB ( 0,250,154)},
608 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
609 {"green yellow" , PALETTERGB (173,255, 47)},
610 {"GreenYellow" , PALETTERGB (173,255, 47)},
611 {"lime green" , PALETTERGB ( 50,205, 50)},
612 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
613 {"yellow green" , PALETTERGB (154,205, 50)},
614 {"YellowGreen" , PALETTERGB (154,205, 50)},
615 {"forest green" , PALETTERGB ( 34,139, 34)},
616 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
617 {"olive drab" , PALETTERGB (107,142, 35)},
618 {"OliveDrab" , PALETTERGB (107,142, 35)},
619 {"dark khaki" , PALETTERGB (189,183,107)},
620 {"DarkKhaki" , PALETTERGB (189,183,107)},
621 {"khaki" , PALETTERGB (240,230,140)},
622 {"pale goldenrod" , PALETTERGB (238,232,170)},
623 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
624 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
625 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
626 {"light yellow" , PALETTERGB (255,255,224)},
627 {"LightYellow" , PALETTERGB (255,255,224)},
628 {"yellow" , PALETTERGB (255,255, 0)},
629 {"gold" , PALETTERGB (255,215, 0)},
630 {"light goldenrod" , PALETTERGB (238,221,130)},
631 {"LightGoldenrod" , PALETTERGB (238,221,130)},
632 {"goldenrod" , PALETTERGB (218,165, 32)},
633 {"dark goldenrod" , PALETTERGB (184,134, 11)},
634 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
635 {"rosy brown" , PALETTERGB (188,143,143)},
636 {"RosyBrown" , PALETTERGB (188,143,143)},
637 {"indian red" , PALETTERGB (205, 92, 92)},
638 {"IndianRed" , PALETTERGB (205, 92, 92)},
639 {"saddle brown" , PALETTERGB (139, 69, 19)},
640 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
641 {"sienna" , PALETTERGB (160, 82, 45)},
642 {"peru" , PALETTERGB (205,133, 63)},
643 {"burlywood" , PALETTERGB (222,184,135)},
644 {"beige" , PALETTERGB (245,245,220)},
645 {"wheat" , PALETTERGB (245,222,179)},
646 {"sandy brown" , PALETTERGB (244,164, 96)},
647 {"SandyBrown" , PALETTERGB (244,164, 96)},
648 {"tan" , PALETTERGB (210,180,140)},
649 {"chocolate" , PALETTERGB (210,105, 30)},
650 {"firebrick" , PALETTERGB (178,34, 34)},
651 {"brown" , PALETTERGB (165,42, 42)},
652 {"dark salmon" , PALETTERGB (233,150,122)},
653 {"DarkSalmon" , PALETTERGB (233,150,122)},
654 {"salmon" , PALETTERGB (250,128,114)},
655 {"light salmon" , PALETTERGB (255,160,122)},
656 {"LightSalmon" , PALETTERGB (255,160,122)},
657 {"orange" , PALETTERGB (255,165, 0)},
658 {"dark orange" , PALETTERGB (255,140, 0)},
659 {"DarkOrange" , PALETTERGB (255,140, 0)},
660 {"coral" , PALETTERGB (255,127, 80)},
661 {"light coral" , PALETTERGB (240,128,128)},
662 {"LightCoral" , PALETTERGB (240,128,128)},
663 {"tomato" , PALETTERGB (255, 99, 71)},
664 {"orange red" , PALETTERGB (255, 69, 0)},
665 {"OrangeRed" , PALETTERGB (255, 69, 0)},
666 {"red" , PALETTERGB (255, 0, 0)},
667 {"hot pink" , PALETTERGB (255,105,180)},
668 {"HotPink" , PALETTERGB (255,105,180)},
669 {"deep pink" , PALETTERGB (255, 20,147)},
670 {"DeepPink" , PALETTERGB (255, 20,147)},
671 {"pink" , PALETTERGB (255,192,203)},
672 {"light pink" , PALETTERGB (255,182,193)},
673 {"LightPink" , PALETTERGB (255,182,193)},
674 {"pale violet red" , PALETTERGB (219,112,147)},
675 {"PaleVioletRed" , PALETTERGB (219,112,147)},
676 {"maroon" , PALETTERGB (176, 48, 96)},
677 {"medium violet red" , PALETTERGB (199, 21,133)},
678 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
679 {"violet red" , PALETTERGB (208, 32,144)},
680 {"VioletRed" , PALETTERGB (208, 32,144)},
681 {"magenta" , PALETTERGB (255, 0,255)},
682 {"violet" , PALETTERGB (238,130,238)},
683 {"plum" , PALETTERGB (221,160,221)},
684 {"orchid" , PALETTERGB (218,112,214)},
685 {"medium orchid" , PALETTERGB (186, 85,211)},
686 {"MediumOrchid" , PALETTERGB (186, 85,211)},
687 {"dark orchid" , PALETTERGB (153, 50,204)},
688 {"DarkOrchid" , PALETTERGB (153, 50,204)},
689 {"dark violet" , PALETTERGB (148, 0,211)},
690 {"DarkViolet" , PALETTERGB (148, 0,211)},
691 {"blue violet" , PALETTERGB (138, 43,226)},
692 {"BlueViolet" , PALETTERGB (138, 43,226)},
693 {"purple" , PALETTERGB (160, 32,240)},
694 {"medium purple" , PALETTERGB (147,112,219)},
695 {"MediumPurple" , PALETTERGB (147,112,219)},
696 {"thistle" , PALETTERGB (216,191,216)},
697 {"gray0" , PALETTERGB ( 0, 0, 0)},
698 {"grey0" , PALETTERGB ( 0, 0, 0)},
699 {"dark grey" , PALETTERGB (169,169,169)},
700 {"DarkGrey" , PALETTERGB (169,169,169)},
701 {"dark gray" , PALETTERGB (169,169,169)},
702 {"DarkGray" , PALETTERGB (169,169,169)},
703 {"dark blue" , PALETTERGB ( 0, 0,139)},
704 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
705 {"dark cyan" , PALETTERGB ( 0,139,139)},
706 {"DarkCyan" , PALETTERGB ( 0,139,139)},
707 {"dark magenta" , PALETTERGB (139, 0,139)},
708 {"DarkMagenta" , PALETTERGB (139, 0,139)},
709 {"dark red" , PALETTERGB (139, 0, 0)},
710 {"DarkRed" , PALETTERGB (139, 0, 0)},
711 {"light green" , PALETTERGB (144,238,144)},
712 {"LightGreen" , PALETTERGB (144,238,144)},
715 static Lisp_Object
716 w32_default_color_map (void)
718 int i;
719 colormap_t *pc = w32_color_map;
720 Lisp_Object cmap;
722 block_input ();
724 cmap = Qnil;
726 for (i = 0; i < sizeof (w32_color_map) / sizeof (w32_color_map[0]);
727 pc++, i++)
728 cmap = Fcons (Fcons (build_string (pc->name),
729 make_number (pc->colorref)),
730 cmap);
732 unblock_input ();
734 return (cmap);
737 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
738 0, 0, 0, doc: /* Return the default color map. */)
739 (void)
741 return w32_default_color_map ();
744 static Lisp_Object
745 w32_color_map_lookup (const char *colorname)
747 Lisp_Object tail, ret = Qnil;
749 block_input ();
751 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
753 register Lisp_Object elt, tem;
755 elt = XCAR (tail);
756 if (!CONSP (elt)) continue;
758 tem = XCAR (elt);
760 if (lstrcmpi (SDATA (tem), colorname) == 0)
762 ret = Fcdr (elt);
763 break;
766 QUIT;
769 unblock_input ();
771 return ret;
775 static void
776 add_system_logical_colors_to_map (Lisp_Object *system_colors)
778 HKEY colors_key;
780 /* Other registry operations are done with input blocked. */
781 block_input ();
783 /* Look for "Control Panel/Colors" under User and Machine registry
784 settings. */
785 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
786 KEY_READ, &colors_key) == ERROR_SUCCESS
787 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
788 KEY_READ, &colors_key) == ERROR_SUCCESS)
790 /* List all keys. */
791 char color_buffer[64];
792 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
793 int index = 0;
794 DWORD name_size, color_size;
795 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
797 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
798 color_size = sizeof (color_buffer);
800 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
802 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
803 NULL, NULL, color_buffer, &color_size)
804 == ERROR_SUCCESS)
806 int r, g, b;
807 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
808 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
809 make_number (RGB (r, g, b))),
810 *system_colors);
812 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
813 color_size = sizeof (color_buffer);
814 index++;
816 RegCloseKey (colors_key);
819 unblock_input ();
823 static Lisp_Object
824 x_to_w32_color (const char * colorname)
826 register Lisp_Object ret = Qnil;
828 block_input ();
830 if (colorname[0] == '#')
832 /* Could be an old-style RGB Device specification. */
833 int size = strlen (colorname + 1);
834 char *color = alloca (size + 1);
836 strcpy (color, colorname + 1);
837 if (size == 3 || size == 6 || size == 9 || size == 12)
839 UINT colorval;
840 int i, pos;
841 pos = 0;
842 size /= 3;
843 colorval = 0;
845 for (i = 0; i < 3; i++)
847 char *end;
848 char t;
849 unsigned long value;
851 /* The check for 'x' in the following conditional takes into
852 account the fact that strtol allows a "0x" in front of
853 our numbers, and we don't. */
854 if (!isxdigit (color[0]) || color[1] == 'x')
855 break;
856 t = color[size];
857 color[size] = '\0';
858 value = strtoul (color, &end, 16);
859 color[size] = t;
860 if (errno == ERANGE || end - color != size)
861 break;
862 switch (size)
864 case 1:
865 value = value * 0x10;
866 break;
867 case 2:
868 break;
869 case 3:
870 value /= 0x10;
871 break;
872 case 4:
873 value /= 0x100;
874 break;
876 colorval |= (value << pos);
877 pos += 0x8;
878 if (i == 2)
880 unblock_input ();
881 XSETINT (ret, colorval);
882 return ret;
884 color = end;
888 else if (strnicmp (colorname, "rgb:", 4) == 0)
890 const char *color;
891 UINT colorval;
892 int i, pos;
893 pos = 0;
895 colorval = 0;
896 color = colorname + 4;
897 for (i = 0; i < 3; i++)
899 char *end;
900 unsigned long value;
902 /* The check for 'x' in the following conditional takes into
903 account the fact that strtol allows a "0x" in front of
904 our numbers, and we don't. */
905 if (!isxdigit (color[0]) || color[1] == 'x')
906 break;
907 value = strtoul (color, &end, 16);
908 if (errno == ERANGE)
909 break;
910 switch (end - color)
912 case 1:
913 value = value * 0x10 + value;
914 break;
915 case 2:
916 break;
917 case 3:
918 value /= 0x10;
919 break;
920 case 4:
921 value /= 0x100;
922 break;
923 default:
924 value = ULONG_MAX;
926 if (value == ULONG_MAX)
927 break;
928 colorval |= (value << pos);
929 pos += 0x8;
930 if (i == 2)
932 if (*end != '\0')
933 break;
934 unblock_input ();
935 XSETINT (ret, colorval);
936 return ret;
938 if (*end != '/')
939 break;
940 color = end + 1;
943 else if (strnicmp (colorname, "rgbi:", 5) == 0)
945 /* This is an RGB Intensity specification. */
946 const char *color;
947 UINT colorval;
948 int i, pos;
949 pos = 0;
951 colorval = 0;
952 color = colorname + 5;
953 for (i = 0; i < 3; i++)
955 char *end;
956 double value;
957 UINT val;
959 value = strtod (color, &end);
960 if (errno == ERANGE)
961 break;
962 if (value < 0.0 || value > 1.0)
963 break;
964 val = (UINT)(0x100 * value);
965 /* We used 0x100 instead of 0xFF to give a continuous
966 range between 0.0 and 1.0 inclusive. The next statement
967 fixes the 1.0 case. */
968 if (val == 0x100)
969 val = 0xFF;
970 colorval |= (val << pos);
971 pos += 0x8;
972 if (i == 2)
974 if (*end != '\0')
975 break;
976 unblock_input ();
977 XSETINT (ret, colorval);
978 return ret;
980 if (*end != '/')
981 break;
982 color = end + 1;
985 /* I am not going to attempt to handle any of the CIE color schemes
986 or TekHVC, since I don't know the algorithms for conversion to
987 RGB. */
989 /* If we fail to lookup the color name in w32_color_map, then check the
990 colorname to see if it can be crudely approximated: If the X color
991 ends in a number (e.g., "darkseagreen2"), strip the number and
992 return the result of looking up the base color name. */
993 ret = w32_color_map_lookup (colorname);
994 if (NILP (ret))
996 int len = strlen (colorname);
998 if (isdigit (colorname[len - 1]))
1000 char *ptr, *approx = alloca (len + 1);
1002 strcpy (approx, colorname);
1003 ptr = &approx[len - 1];
1004 while (ptr > approx && isdigit (*ptr))
1005 *ptr-- = '\0';
1007 ret = w32_color_map_lookup (approx);
1011 unblock_input ();
1012 return ret;
1015 void
1016 w32_regenerate_palette (struct frame *f)
1018 struct w32_palette_entry * list;
1019 LOGPALETTE * log_palette;
1020 HPALETTE new_palette;
1021 int i;
1023 /* don't bother trying to create palette if not supported */
1024 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1025 return;
1027 log_palette = (LOGPALETTE *)
1028 alloca (sizeof (LOGPALETTE) +
1029 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1030 log_palette->palVersion = 0x300;
1031 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1033 list = FRAME_DISPLAY_INFO (f)->color_list;
1034 for (i = 0;
1035 i < FRAME_DISPLAY_INFO (f)->num_colors;
1036 i++, list = list->next)
1037 log_palette->palPalEntry[i] = list->entry;
1039 new_palette = CreatePalette (log_palette);
1041 enter_crit ();
1043 if (FRAME_DISPLAY_INFO (f)->palette)
1044 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1045 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1047 /* Realize display palette and garbage all frames. */
1048 release_frame_dc (f, get_frame_dc (f));
1050 leave_crit ();
1053 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1054 #define SET_W32_COLOR(pe, color) \
1055 do \
1057 pe.peRed = GetRValue (color); \
1058 pe.peGreen = GetGValue (color); \
1059 pe.peBlue = GetBValue (color); \
1060 pe.peFlags = 0; \
1061 } while (0)
1063 #if 0
1064 /* Keep these around in case we ever want to track color usage. */
1065 void
1066 w32_map_color (struct frame *f, COLORREF color)
1068 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1070 if (NILP (Vw32_enable_palette))
1071 return;
1073 /* check if color is already mapped */
1074 while (list)
1076 if (W32_COLOR (list->entry) == color)
1078 ++list->refcount;
1079 return;
1081 list = list->next;
1084 /* not already mapped, so add to list and recreate Windows palette */
1085 list = xmalloc (sizeof (struct w32_palette_entry));
1086 SET_W32_COLOR (list->entry, color);
1087 list->refcount = 1;
1088 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1089 FRAME_DISPLAY_INFO (f)->color_list = list;
1090 FRAME_DISPLAY_INFO (f)->num_colors++;
1092 /* set flag that palette must be regenerated */
1093 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1096 void
1097 w32_unmap_color (struct frame *f, COLORREF color)
1099 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1100 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1102 if (NILP (Vw32_enable_palette))
1103 return;
1105 /* check if color is already mapped */
1106 while (list)
1108 if (W32_COLOR (list->entry) == color)
1110 if (--list->refcount == 0)
1112 *prev = list->next;
1113 xfree (list);
1114 FRAME_DISPLAY_INFO (f)->num_colors--;
1115 break;
1117 else
1118 return;
1120 prev = &list->next;
1121 list = list->next;
1124 /* set flag that palette must be regenerated */
1125 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1127 #endif
1130 /* Gamma-correct COLOR on frame F. */
1132 void
1133 gamma_correct (struct frame *f, COLORREF *color)
1135 if (f->gamma)
1137 *color = PALETTERGB (
1138 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1139 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1140 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1145 /* Decide if color named COLOR is valid for the display associated with
1146 the selected frame; if so, return the rgb values in COLOR_DEF.
1147 If ALLOC is nonzero, allocate a new colormap cell. */
1150 w32_defined_color (struct frame *f, const char *color, XColor *color_def, int alloc)
1152 register Lisp_Object tem;
1153 COLORREF w32_color_ref;
1155 tem = x_to_w32_color (color);
1157 if (!NILP (tem))
1159 if (f)
1161 /* Apply gamma correction. */
1162 w32_color_ref = XUINT (tem);
1163 gamma_correct (f, &w32_color_ref);
1164 XSETINT (tem, w32_color_ref);
1167 /* Map this color to the palette if it is enabled. */
1168 if (!NILP (Vw32_enable_palette))
1170 struct w32_palette_entry * entry =
1171 one_w32_display_info.color_list;
1172 struct w32_palette_entry ** prev =
1173 &one_w32_display_info.color_list;
1175 /* check if color is already mapped */
1176 while (entry)
1178 if (W32_COLOR (entry->entry) == XUINT (tem))
1179 break;
1180 prev = &entry->next;
1181 entry = entry->next;
1184 if (entry == NULL && alloc)
1186 /* not already mapped, so add to list */
1187 entry = xmalloc (sizeof (struct w32_palette_entry));
1188 SET_W32_COLOR (entry->entry, XUINT (tem));
1189 entry->next = NULL;
1190 *prev = entry;
1191 one_w32_display_info.num_colors++;
1193 /* set flag that palette must be regenerated */
1194 one_w32_display_info.regen_palette = TRUE;
1197 /* Ensure COLORREF value is snapped to nearest color in (default)
1198 palette by simulating the PALETTERGB macro. This works whether
1199 or not the display device has a palette. */
1200 w32_color_ref = XUINT (tem) | 0x2000000;
1202 color_def->pixel = w32_color_ref;
1203 color_def->red = GetRValue (w32_color_ref) * 256;
1204 color_def->green = GetGValue (w32_color_ref) * 256;
1205 color_def->blue = GetBValue (w32_color_ref) * 256;
1207 return 1;
1209 else
1211 return 0;
1215 /* Given a string ARG naming a color, compute a pixel value from it
1216 suitable for screen F.
1217 If F is not a color screen, return DEF (default) regardless of what
1218 ARG says. */
1221 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1223 XColor cdef;
1225 CHECK_STRING (arg);
1227 if (strcmp (SDATA (arg), "black") == 0)
1228 return BLACK_PIX_DEFAULT (f);
1229 else if (strcmp (SDATA (arg), "white") == 0)
1230 return WHITE_PIX_DEFAULT (f);
1232 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1233 return def;
1235 /* w32_defined_color is responsible for coping with failures
1236 by looking for a near-miss. */
1237 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1238 return cdef.pixel;
1240 /* defined_color failed; return an ultimate default. */
1241 return def;
1246 /* Functions called only from `x_set_frame_param'
1247 to set individual parameters.
1249 If FRAME_W32_WINDOW (f) is 0,
1250 the frame is being created and its window does not exist yet.
1251 In that case, just record the parameter's new value
1252 in the standard place; do not attempt to change the window. */
1254 void
1255 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1257 struct w32_output *x = f->output_data.w32;
1258 PIX_TYPE fg, old_fg;
1260 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1261 old_fg = FRAME_FOREGROUND_PIXEL (f);
1262 FRAME_FOREGROUND_PIXEL (f) = fg;
1264 if (FRAME_W32_WINDOW (f) != 0)
1266 if (x->cursor_pixel == old_fg)
1268 x->cursor_pixel = fg;
1269 x->cursor_gc->background = fg;
1272 update_face_from_frame_parameter (f, Qforeground_color, arg);
1273 if (FRAME_VISIBLE_P (f))
1274 redraw_frame (f);
1278 void
1279 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1281 FRAME_BACKGROUND_PIXEL (f)
1282 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1284 if (FRAME_W32_WINDOW (f) != 0)
1286 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1287 FRAME_BACKGROUND_PIXEL (f));
1289 update_face_from_frame_parameter (f, Qbackground_color, arg);
1291 if (FRAME_VISIBLE_P (f))
1292 redraw_frame (f);
1296 void
1297 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1299 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1300 int count;
1301 int mask_color;
1303 if (!EQ (Qnil, arg))
1304 f->output_data.w32->mouse_pixel
1305 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1306 mask_color = FRAME_BACKGROUND_PIXEL (f);
1308 /* Don't let pointers be invisible. */
1309 if (mask_color == f->output_data.w32->mouse_pixel
1310 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1311 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1313 #if 0 /* TODO : Mouse cursor customization. */
1314 block_input ();
1316 /* It's not okay to crash if the user selects a screwy cursor. */
1317 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1319 if (!EQ (Qnil, Vx_pointer_shape))
1321 CHECK_NUMBER (Vx_pointer_shape);
1322 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1324 else
1325 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1326 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1328 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1330 CHECK_NUMBER (Vx_nontext_pointer_shape);
1331 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1332 XINT (Vx_nontext_pointer_shape));
1334 else
1335 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1336 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1338 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1340 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1341 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1342 XINT (Vx_hourglass_pointer_shape));
1344 else
1345 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1346 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1348 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1349 if (!EQ (Qnil, Vx_mode_pointer_shape))
1351 CHECK_NUMBER (Vx_mode_pointer_shape);
1352 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1353 XINT (Vx_mode_pointer_shape));
1355 else
1356 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1357 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1359 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1361 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1362 hand_cursor
1363 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1364 XINT (Vx_sensitive_text_pointer_shape));
1366 else
1367 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1369 if (!NILP (Vx_window_horizontal_drag_shape))
1371 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1372 horizontal_drag_cursor
1373 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1374 XINT (Vx_window_horizontal_drag_shape));
1376 else
1377 horizontal_drag_cursor
1378 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1380 if (!NILP (Vx_window_vertical_drag_shape))
1382 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1383 vertical_drag_cursor
1384 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1385 XINT (Vx_window_vertical_drag_shape));
1387 else
1388 vertical_drag_cursor
1389 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_v_double_arrow);
1391 /* Check and report errors with the above calls. */
1392 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1393 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1396 XColor fore_color, back_color;
1398 fore_color.pixel = f->output_data.w32->mouse_pixel;
1399 back_color.pixel = mask_color;
1400 XQueryColor (FRAME_W32_DISPLAY (f),
1401 DefaultColormap (FRAME_W32_DISPLAY (f),
1402 DefaultScreen (FRAME_W32_DISPLAY (f))),
1403 &fore_color);
1404 XQueryColor (FRAME_W32_DISPLAY (f),
1405 DefaultColormap (FRAME_W32_DISPLAY (f),
1406 DefaultScreen (FRAME_W32_DISPLAY (f))),
1407 &back_color);
1408 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1409 &fore_color, &back_color);
1410 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1411 &fore_color, &back_color);
1412 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1413 &fore_color, &back_color);
1414 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1415 &fore_color, &back_color);
1416 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1417 &fore_color, &back_color);
1420 if (FRAME_W32_WINDOW (f) != 0)
1421 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1423 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1424 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1425 f->output_data.w32->text_cursor = cursor;
1427 if (nontext_cursor != f->output_data.w32->nontext_cursor
1428 && f->output_data.w32->nontext_cursor != 0)
1429 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1430 f->output_data.w32->nontext_cursor = nontext_cursor;
1432 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1433 && f->output_data.w32->hourglass_cursor != 0)
1434 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1435 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1437 if (mode_cursor != f->output_data.w32->modeline_cursor
1438 && f->output_data.w32->modeline_cursor != 0)
1439 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1440 f->output_data.w32->modeline_cursor = mode_cursor;
1442 if (hand_cursor != f->output_data.w32->hand_cursor
1443 && f->output_data.w32->hand_cursor != 0)
1444 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1445 f->output_data.w32->hand_cursor = hand_cursor;
1447 XFlush (FRAME_W32_DISPLAY (f));
1448 unblock_input ();
1450 update_face_from_frame_parameter (f, Qmouse_color, arg);
1451 #endif /* TODO */
1454 void
1455 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1457 unsigned long fore_pixel, pixel;
1459 if (!NILP (Vx_cursor_fore_pixel))
1460 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1461 WHITE_PIX_DEFAULT (f));
1462 else
1463 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1465 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1467 /* Make sure that the cursor color differs from the background color. */
1468 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1470 pixel = f->output_data.w32->mouse_pixel;
1471 if (pixel == fore_pixel)
1472 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1475 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1476 f->output_data.w32->cursor_pixel = pixel;
1478 if (FRAME_W32_WINDOW (f) != 0)
1480 block_input ();
1481 /* Update frame's cursor_gc. */
1482 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1483 f->output_data.w32->cursor_gc->background = pixel;
1485 unblock_input ();
1487 if (FRAME_VISIBLE_P (f))
1489 x_update_cursor (f, 0);
1490 x_update_cursor (f, 1);
1494 update_face_from_frame_parameter (f, Qcursor_color, arg);
1497 /* Set the border-color of frame F to pixel value PIX.
1498 Note that this does not fully take effect if done before
1499 F has a window. */
1501 void
1502 x_set_border_pixel (struct frame *f, int pix)
1505 f->output_data.w32->border_pixel = pix;
1507 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1509 if (FRAME_VISIBLE_P (f))
1510 redraw_frame (f);
1514 /* Set the border-color of frame F to value described by ARG.
1515 ARG can be a string naming a color.
1516 The border-color is used for the border that is drawn by the server.
1517 Note that this does not fully take effect if done before
1518 F has a window; it must be redone when the window is created. */
1520 void
1521 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1523 int pix;
1525 CHECK_STRING (arg);
1526 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1527 x_set_border_pixel (f, pix);
1528 update_face_from_frame_parameter (f, Qborder_color, arg);
1532 void
1533 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1535 set_frame_cursor_types (f, arg);
1538 void
1539 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1541 int result;
1543 if (NILP (arg) && NILP (oldval))
1544 return;
1546 if (STRINGP (arg) && STRINGP (oldval)
1547 && EQ (Fstring_equal (oldval, arg), Qt))
1548 return;
1550 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1551 return;
1553 block_input ();
1555 result = x_bitmap_icon (f, arg);
1556 if (result)
1558 unblock_input ();
1559 error ("No icon window available");
1562 unblock_input ();
1565 void
1566 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1568 if (STRINGP (arg))
1570 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1571 return;
1573 else if (!NILP (arg) || NILP (oldval))
1574 return;
1576 fset_icon_name (f, arg);
1578 #if 0
1579 if (f->output_data.w32->icon_bitmap != 0)
1580 return;
1582 block_input ();
1584 result = x_text_icon (f,
1585 SSDATA ((!NILP (f->icon_name)
1586 ? f->icon_name
1587 : !NILP (f->title)
1588 ? f->title
1589 : f->name)));
1591 if (result)
1593 unblock_input ();
1594 error ("No icon window available");
1597 /* If the window was unmapped (and its icon was mapped),
1598 the new icon is not mapped, so map the window in its stead. */
1599 if (FRAME_VISIBLE_P (f))
1601 #ifdef USE_X_TOOLKIT
1602 XtPopup (f->output_data.w32->widget, XtGrabNone);
1603 #endif
1604 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1607 XFlush (FRAME_W32_DISPLAY (f));
1608 unblock_input ();
1609 #endif
1613 void
1614 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1616 int nlines;
1618 /* Right now, menu bars don't work properly in minibuf-only frames;
1619 most of the commands try to apply themselves to the minibuffer
1620 frame itself, and get an error because you can't switch buffers
1621 in or split the minibuffer window. */
1622 if (FRAME_MINIBUF_ONLY_P (f))
1623 return;
1625 if (INTEGERP (value))
1626 nlines = XINT (value);
1627 else
1628 nlines = 0;
1630 FRAME_MENU_BAR_LINES (f) = 0;
1631 FRAME_MENU_BAR_HEIGHT (f) = 0;
1632 if (nlines)
1633 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1634 else
1636 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1637 free_frame_menubar (f);
1638 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1640 /* Adjust the frame size so that the client (text) dimensions
1641 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1642 set correctly. */
1643 x_set_window_size (f, 0, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 1);
1644 do_pending_window_change (0);
1646 adjust_frame_glyphs (f);
1650 /* Set the number of lines used for the tool bar of frame F to VALUE.
1651 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1652 the old number of tool bar lines (and is unused). This function may
1653 change the height of all windows on frame F to match the new tool bar
1654 height. By design, the frame's height doesn't change (but maybe it
1655 should if we don't get enough space otherwise). */
1657 void
1658 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1660 int delta, nlines, root_height;
1661 int unit = FRAME_LINE_HEIGHT (f);
1663 /* Treat tool bars like menu bars. */
1664 if (FRAME_MINIBUF_ONLY_P (f))
1665 return;
1667 /* Use VALUE only if an integer >= 0. */
1668 if (INTEGERP (value) && XINT (value) >= 0)
1669 nlines = XFASTINT (value);
1670 else
1671 nlines = 0;
1673 /* Make sure we redisplay all windows in this frame. */
1674 windows_or_buffers_changed = 23;
1676 /* DELTA is in pixels now. */
1677 delta = (nlines - FRAME_TOOL_BAR_LINES (f)) * unit;
1679 /* Don't resize the tool-bar to more than we have room for. Note: The
1680 calculations below and the subsequent call to resize_frame_windows
1681 are inherently flawed because they can make the toolbar higher than
1682 the containing frame. */
1683 if (delta > 0)
1685 root_height = WINDOW_PIXEL_HEIGHT (XWINDOW (FRAME_ROOT_WINDOW (f)));
1686 if (root_height - delta < unit)
1688 delta = root_height - unit;
1689 /* When creating a new frame and toolbar mode is enabled, we
1690 need at least one toolbar line. */
1691 nlines = max (FRAME_TOOL_BAR_LINES (f) + delta / unit, 1);
1695 FRAME_TOOL_BAR_LINES (f) = nlines;
1696 FRAME_TOOL_BAR_HEIGHT (f) = nlines * FRAME_LINE_HEIGHT (f);
1697 ++windows_or_buffers_changed;
1698 resize_frame_windows (f, FRAME_TEXT_HEIGHT (f), 0, 1);
1699 adjust_frame_glyphs (f);
1701 /* We also have to make sure that the internal border at the top of
1702 the frame, below the menu bar or tool bar, is redrawn when the
1703 tool bar disappears. This is so because the internal border is
1704 below the tool bar if one is displayed, but is below the menu bar
1705 if there isn't a tool bar. The tool bar draws into the area
1706 below the menu bar. */
1707 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1709 clear_frame (f);
1710 clear_current_matrices (f);
1713 /* If the tool bar gets smaller, the internal border below it
1714 has to be cleared. It was formerly part of the display
1715 of the larger tool bar, and updating windows won't clear it. */
1716 if (FRAME_INTERNAL_BORDER_WIDTH (f) != 0 && FRAME_VISIBLE_P (f))
1718 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1719 int width = FRAME_PIXEL_WIDTH (f);
1720 int y = nlines * unit;
1721 HDC hdc = get_frame_dc (f);
1723 block_input ();
1724 w32_clear_area (f, hdc, 0, y, width, height);
1725 release_frame_dc (f, hdc);
1726 unblock_input ();
1729 if (delta < 0 && WINDOWP (f->tool_bar_window))
1730 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1732 run_window_configuration_change_hook (f);
1735 static void
1736 w32_set_title_bar_text (struct frame *f, Lisp_Object name)
1738 if (FRAME_W32_WINDOW (f))
1740 block_input ();
1741 #ifdef __CYGWIN__
1742 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1743 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1744 #else
1745 /* The frame's title many times shows the name of the file
1746 visited in the selected window's buffer, so it makes sense to
1747 support non-ASCII characters outside of the current system
1748 codepage in the title. */
1749 if (w32_unicode_filenames)
1751 Lisp_Object encoded_title = ENCODE_UTF_8 (name);
1752 wchar_t *title_w;
1753 int tlen = pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title),
1754 -1, NULL, 0);
1756 if (tlen > 0)
1758 /* Windows truncates the title text beyond what fits on
1759 a single line, so we can limit the length to some
1760 reasonably large value, and use alloca. */
1761 if (tlen > 10000)
1762 tlen = 10000;
1763 title_w = alloca ((tlen + 1) * sizeof (wchar_t));
1764 pMultiByteToWideChar (CP_UTF8, 0, SSDATA (encoded_title), -1,
1765 title_w, tlen);
1766 title_w[tlen] = L'\0';
1767 SetWindowTextW (FRAME_W32_WINDOW (f), title_w);
1769 else /* Conversion to UTF-16 failed, so we punt. */
1770 SetWindowTextA (FRAME_W32_WINDOW (f),
1771 SSDATA (ENCODE_SYSTEM (name)));
1773 else
1774 SetWindowTextA (FRAME_W32_WINDOW (f), SSDATA (ENCODE_SYSTEM (name)));
1775 #endif
1776 unblock_input ();
1780 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1781 w32_id_name.
1783 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1784 name; if NAME is a string, set F's name to NAME and set
1785 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1787 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1788 suggesting a new name, which lisp code should override; if
1789 F->explicit_name is set, ignore the new name; otherwise, set it. */
1791 void
1792 x_set_name (struct frame *f, Lisp_Object name, int explicit)
1794 /* Make sure that requests from lisp code override requests from
1795 Emacs redisplay code. */
1796 if (explicit)
1798 /* If we're switching from explicit to implicit, we had better
1799 update the mode lines and thereby update the title. */
1800 if (f->explicit_name && NILP (name))
1801 update_mode_lines = 25;
1803 f->explicit_name = ! NILP (name);
1805 else if (f->explicit_name)
1806 return;
1808 /* If NAME is nil, set the name to the w32_id_name. */
1809 if (NILP (name))
1811 /* Check for no change needed in this very common case
1812 before we do any consing. */
1813 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1814 SDATA (f->name)))
1815 return;
1816 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1818 else
1819 CHECK_STRING (name);
1821 /* Don't change the name if it's already NAME. */
1822 if (! NILP (Fstring_equal (name, f->name)))
1823 return;
1825 fset_name (f, name);
1827 /* For setting the frame title, the title parameter should override
1828 the name parameter. */
1829 if (! NILP (f->title))
1830 name = f->title;
1832 w32_set_title_bar_text (f, name);
1835 /* This function should be called when the user's lisp code has
1836 specified a name for the frame; the name will override any set by the
1837 redisplay code. */
1838 void
1839 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1841 x_set_name (f, arg, 1);
1844 /* This function should be called by Emacs redisplay code to set the
1845 name; names set this way will never override names set by the user's
1846 lisp code. */
1847 void
1848 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1850 x_set_name (f, arg, 0);
1853 /* Change the title of frame F to NAME.
1854 If NAME is nil, use the frame name as the title. */
1856 void
1857 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1859 /* Don't change the title if it's already NAME. */
1860 if (EQ (name, f->title))
1861 return;
1863 update_mode_lines = 26;
1865 fset_title (f, name);
1867 if (NILP (name))
1868 name = f->name;
1870 w32_set_title_bar_text (f, name);
1873 void
1874 x_set_scroll_bar_default_width (struct frame *f)
1876 int unit = FRAME_COLUMN_WIDTH (f);
1878 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1879 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1880 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1884 /* Subroutines for creating a frame. */
1886 Cursor
1887 w32_load_cursor (LPCTSTR name)
1889 /* Try first to load cursor from application resource. */
1890 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1891 name, IMAGE_CURSOR, 0, 0,
1892 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1893 if (!cursor)
1895 /* Then try to load a shared predefined cursor. */
1896 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1897 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1899 return cursor;
1902 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1904 #define INIT_WINDOW_CLASS(WC) \
1905 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1906 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1907 (WC).cbClsExtra = 0; \
1908 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1909 (WC).hInstance = hinst; \
1910 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1911 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1912 (WC).hbrBackground = NULL; \
1913 (WC).lpszMenuName = NULL; \
1915 static BOOL
1916 w32_init_class (HINSTANCE hinst)
1918 if (w32_unicode_gui)
1920 WNDCLASSW uwc;
1921 INIT_WINDOW_CLASS(uwc);
1922 uwc.lpszClassName = L"Emacs";
1924 return RegisterClassW (&uwc);
1926 else
1928 WNDCLASS wc;
1929 INIT_WINDOW_CLASS(wc);
1930 wc.lpszClassName = EMACS_CLASS;
1932 return RegisterClassA (&wc);
1936 static HWND
1937 w32_createscrollbar (struct frame *f, struct scroll_bar * bar)
1939 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1940 /* Position and size of scroll bar. */
1941 bar->left, bar->top, bar->width, bar->height,
1942 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1945 static void
1946 w32_createwindow (struct frame *f, int *coords)
1948 HWND hwnd;
1949 RECT rect;
1950 int top;
1951 int left;
1953 rect.left = rect.top = 0;
1954 rect.right = FRAME_PIXEL_WIDTH (f);
1955 rect.bottom = FRAME_PIXEL_HEIGHT (f);
1957 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
1958 FRAME_EXTERNAL_MENU_BAR (f));
1960 /* Do first time app init */
1962 w32_init_class (hinst);
1964 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
1966 left = f->left_pos;
1967 top = f->top_pos;
1969 else
1971 left = coords[0];
1972 top = coords[1];
1975 FRAME_W32_WINDOW (f) = hwnd
1976 = CreateWindow (EMACS_CLASS,
1977 f->namebuf,
1978 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
1979 left, top,
1980 rect.right - rect.left, rect.bottom - rect.top,
1981 NULL,
1982 NULL,
1983 hinst,
1984 NULL);
1986 if (hwnd)
1988 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
1989 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
1990 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
1991 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
1992 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
1994 /* Enable drag-n-drop. */
1995 DragAcceptFiles (hwnd, TRUE);
1997 /* Do this to discard the default setting specified by our parent. */
1998 ShowWindow (hwnd, SW_HIDE);
2000 /* Update frame positions. */
2001 GetWindowRect (hwnd, &rect);
2002 f->left_pos = rect.left;
2003 f->top_pos = rect.top;
2007 static void
2008 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2010 wmsg->msg.hwnd = hwnd;
2011 wmsg->msg.message = msg;
2012 wmsg->msg.wParam = wParam;
2013 wmsg->msg.lParam = lParam;
2014 wmsg->msg.time = GetMessageTime ();
2016 post_msg (wmsg);
2019 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
2020 between left and right keys as advertised. We test for this
2021 support dynamically, and set a flag when the support is absent. If
2022 absent, we keep track of the left and right control and alt keys
2023 ourselves. This is particularly necessary on keyboards that rely
2024 upon the AltGr key, which is represented as having the left control
2025 and right alt keys pressed. For these keyboards, we need to know
2026 when the left alt key has been pressed in addition to the AltGr key
2027 so that we can properly support M-AltGr-key sequences (such as M-@
2028 on Swedish keyboards). */
2030 #define EMACS_LCONTROL 0
2031 #define EMACS_RCONTROL 1
2032 #define EMACS_LMENU 2
2033 #define EMACS_RMENU 3
2035 static int modifiers[4];
2036 static int modifiers_recorded;
2037 static int modifier_key_support_tested;
2039 static void
2040 test_modifier_support (unsigned int wparam)
2042 unsigned int l, r;
2044 if (wparam != VK_CONTROL && wparam != VK_MENU)
2045 return;
2046 if (wparam == VK_CONTROL)
2048 l = VK_LCONTROL;
2049 r = VK_RCONTROL;
2051 else
2053 l = VK_LMENU;
2054 r = VK_RMENU;
2056 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2057 modifiers_recorded = 1;
2058 else
2059 modifiers_recorded = 0;
2060 modifier_key_support_tested = 1;
2063 static void
2064 record_keydown (unsigned int wparam, unsigned int lparam)
2066 int i;
2068 if (!modifier_key_support_tested)
2069 test_modifier_support (wparam);
2071 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2072 return;
2074 if (wparam == VK_CONTROL)
2075 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2076 else
2077 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2079 modifiers[i] = 1;
2082 static void
2083 record_keyup (unsigned int wparam, unsigned int lparam)
2085 int i;
2087 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2088 return;
2090 if (wparam == VK_CONTROL)
2091 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2092 else
2093 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2095 modifiers[i] = 0;
2098 /* Emacs can lose focus while a modifier key has been pressed. When
2099 it regains focus, be conservative and clear all modifiers since
2100 we cannot reconstruct the left and right modifier state. */
2101 static void
2102 reset_modifiers (void)
2104 SHORT ctrl, alt;
2106 if (GetFocus () == NULL)
2107 /* Emacs doesn't have keyboard focus. Do nothing. */
2108 return;
2110 ctrl = GetAsyncKeyState (VK_CONTROL);
2111 alt = GetAsyncKeyState (VK_MENU);
2113 if (!(ctrl & 0x08000))
2114 /* Clear any recorded control modifier state. */
2115 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2117 if (!(alt & 0x08000))
2118 /* Clear any recorded alt modifier state. */
2119 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2121 /* Update the state of all modifier keys, because modifiers used in
2122 hot-key combinations can get stuck on if Emacs loses focus as a
2123 result of a hot-key being pressed. */
2125 BYTE keystate[256];
2127 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2129 memset (keystate, 0, sizeof (keystate));
2130 GetKeyboardState (keystate);
2131 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2132 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2133 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2134 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2135 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2136 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2137 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2138 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2139 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2140 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2141 SetKeyboardState (keystate);
2145 /* Synchronize modifier state with what is reported with the current
2146 keystroke. Even if we cannot distinguish between left and right
2147 modifier keys, we know that, if no modifiers are set, then neither
2148 the left or right modifier should be set. */
2149 static void
2150 sync_modifiers (void)
2152 if (!modifiers_recorded)
2153 return;
2155 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2156 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2158 if (!(GetKeyState (VK_MENU) & 0x8000))
2159 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2162 static int
2163 modifier_set (int vkey)
2165 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2166 toggle keys is not an omission! If you want to add it, you will
2167 have to make changes in the default sub-case of the WM_KEYDOWN
2168 switch, because if the NUMLOCK modifier is set, the code there
2169 will directly convert any key that looks like an ASCII letter,
2170 and also downcase those that look like upper-case ASCII. */
2171 if (vkey == VK_CAPITAL)
2173 if (NILP (Vw32_enable_caps_lock))
2174 return 0;
2175 else
2176 return (GetKeyState (vkey) & 0x1);
2178 if (vkey == VK_SCROLL)
2180 if (NILP (Vw32_scroll_lock_modifier)
2181 /* w32-scroll-lock-modifier can be any non-nil value that is
2182 not one of the modifiers, in which case it shall be ignored. */
2183 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2184 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2185 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2186 || EQ (Vw32_scroll_lock_modifier, Qalt)
2187 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2188 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2189 return 0;
2190 else
2191 return (GetKeyState (vkey) & 0x1);
2194 if (!modifiers_recorded)
2195 return (GetKeyState (vkey) & 0x8000);
2197 switch (vkey)
2199 case VK_LCONTROL:
2200 return modifiers[EMACS_LCONTROL];
2201 case VK_RCONTROL:
2202 return modifiers[EMACS_RCONTROL];
2203 case VK_LMENU:
2204 return modifiers[EMACS_LMENU];
2205 case VK_RMENU:
2206 return modifiers[EMACS_RMENU];
2208 return (GetKeyState (vkey) & 0x8000);
2211 /* Convert between the modifier bits W32 uses and the modifier bits
2212 Emacs uses. */
2214 unsigned int
2215 w32_key_to_modifier (int key)
2217 Lisp_Object key_mapping;
2219 switch (key)
2221 case VK_LWIN:
2222 key_mapping = Vw32_lwindow_modifier;
2223 break;
2224 case VK_RWIN:
2225 key_mapping = Vw32_rwindow_modifier;
2226 break;
2227 case VK_APPS:
2228 key_mapping = Vw32_apps_modifier;
2229 break;
2230 case VK_SCROLL:
2231 key_mapping = Vw32_scroll_lock_modifier;
2232 break;
2233 default:
2234 key_mapping = Qnil;
2237 /* NB. This code runs in the input thread, asynchronously to the lisp
2238 thread, so we must be careful to ensure access to lisp data is
2239 thread-safe. The following code is safe because the modifier
2240 variable values are updated atomically from lisp and symbols are
2241 not relocated by GC. Also, we don't have to worry about seeing GC
2242 markbits here. */
2243 if (EQ (key_mapping, Qhyper))
2244 return hyper_modifier;
2245 if (EQ (key_mapping, Qsuper))
2246 return super_modifier;
2247 if (EQ (key_mapping, Qmeta))
2248 return meta_modifier;
2249 if (EQ (key_mapping, Qalt))
2250 return alt_modifier;
2251 if (EQ (key_mapping, Qctrl))
2252 return ctrl_modifier;
2253 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2254 return ctrl_modifier;
2255 if (EQ (key_mapping, Qshift))
2256 return shift_modifier;
2258 /* Don't generate any modifier if not explicitly requested. */
2259 return 0;
2262 static unsigned int
2263 w32_get_modifiers (void)
2265 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2266 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2267 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2268 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2269 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2270 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2271 (modifier_set (VK_MENU) ?
2272 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2275 /* We map the VK_* modifiers into console modifier constants
2276 so that we can use the same routines to handle both console
2277 and window input. */
2279 static int
2280 construct_console_modifiers (void)
2282 int mods;
2284 mods = 0;
2285 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2286 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2287 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2288 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2289 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2290 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2291 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2292 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2293 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2294 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2295 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2297 return mods;
2300 static int
2301 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2303 int mods;
2305 /* Convert to emacs modifiers. */
2306 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2308 return mods;
2311 unsigned int
2312 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2314 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2315 return virt_key;
2317 if (virt_key == VK_RETURN)
2318 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2320 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2321 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2323 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2324 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2326 if (virt_key == VK_CLEAR)
2327 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2329 return virt_key;
2332 /* List of special key combinations which w32 would normally capture,
2333 but Emacs should grab instead. Not directly visible to lisp, to
2334 simplify synchronization. Each item is an integer encoding a virtual
2335 key code and modifier combination to capture. */
2336 static Lisp_Object w32_grabbed_keys;
2338 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2339 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2340 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2341 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2343 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2344 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2345 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2347 /* Register hot-keys for reserved key combinations when Emacs has
2348 keyboard focus, since this is the only way Emacs can receive key
2349 combinations like Alt-Tab which are used by the system. */
2351 static void
2352 register_hot_keys (HWND hwnd)
2354 Lisp_Object keylist;
2356 /* Use CONSP, since we are called asynchronously. */
2357 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2359 Lisp_Object key = XCAR (keylist);
2361 /* Deleted entries get set to nil. */
2362 if (!INTEGERP (key))
2363 continue;
2365 RegisterHotKey (hwnd, HOTKEY_ID (key),
2366 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2370 static void
2371 unregister_hot_keys (HWND hwnd)
2373 Lisp_Object keylist;
2375 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2377 Lisp_Object key = XCAR (keylist);
2379 if (!INTEGERP (key))
2380 continue;
2382 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2386 #if EMACSDEBUG
2387 const char*
2388 w32_name_of_message (UINT msg)
2390 unsigned i;
2391 static char buf[64];
2392 static const struct {
2393 UINT msg;
2394 const char* name;
2395 } msgnames[] = {
2396 #define M(msg) { msg, # msg }
2397 M (WM_PAINT),
2398 M (WM_TIMER),
2399 M (WM_USER),
2400 M (WM_MOUSEMOVE),
2401 M (WM_LBUTTONUP),
2402 M (WM_KEYDOWN),
2403 M (WM_EMACS_KILL),
2404 M (WM_EMACS_CREATEWINDOW),
2405 M (WM_EMACS_DONE),
2406 M (WM_EMACS_CREATESCROLLBAR),
2407 M (WM_EMACS_SHOWWINDOW),
2408 M (WM_EMACS_SETWINDOWPOS),
2409 M (WM_EMACS_DESTROYWINDOW),
2410 M (WM_EMACS_TRACKPOPUPMENU),
2411 M (WM_EMACS_SETFOCUS),
2412 M (WM_EMACS_SETFOREGROUND),
2413 M (WM_EMACS_SETLOCALE),
2414 M (WM_EMACS_SETKEYBOARDLAYOUT),
2415 M (WM_EMACS_REGISTER_HOT_KEY),
2416 M (WM_EMACS_UNREGISTER_HOT_KEY),
2417 M (WM_EMACS_TOGGLE_LOCK_KEY),
2418 M (WM_EMACS_TRACK_CARET),
2419 M (WM_EMACS_DESTROY_CARET),
2420 M (WM_EMACS_SHOW_CARET),
2421 M (WM_EMACS_HIDE_CARET),
2422 M (WM_EMACS_SETCURSOR),
2423 M (WM_EMACS_PAINT),
2424 M (WM_CHAR),
2425 #undef M
2426 { 0, 0 }
2429 for (i = 0; msgnames[i].name; ++i)
2430 if (msgnames[i].msg == msg)
2431 return msgnames[i].name;
2433 sprintf (buf, "message 0x%04x", (unsigned)msg);
2434 return buf;
2436 #endif /* EMACSDEBUG */
2438 /* Here's an overview of how Emacs input works in GUI sessions on
2439 MS-Windows. (For description of non-GUI input, see the commentary
2440 before w32_console_read_socket in w32inevt.c.)
2442 System messages are read and processed by w32_msg_pump below. This
2443 function runs in a separate thread. It handles a small number of
2444 custom WM_EMACS_* messages (posted by the main thread, look for
2445 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2446 is the main window procedure for the entire Emacs application.
2448 w32_wnd_proc also runs in the same separate input thread. It
2449 handles some messages, mostly those that need GDI calls, by itself.
2450 For the others, it calls my_post_msg, which inserts the messages
2451 into the input queue serviced by w32_read_socket.
2453 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2454 called synchronously from keyboard.c when it is known or suspected
2455 that some input is available. w32_read_socket either handles
2456 messages immediately, or converts them into Emacs input events and
2457 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2458 them and process them when read_char and its callers require
2459 input.
2461 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2462 select(2) takes the place of w32_read_socket.
2466 /* Main message dispatch loop. */
2468 static void
2469 w32_msg_pump (deferred_msg * msg_buf)
2471 MSG msg;
2472 WPARAM result;
2473 HWND focus_window;
2475 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2477 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2480 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2481 /* w32_name_of_message (msg.message), msg.time)); */
2483 if (msg.hwnd == NULL)
2485 switch (msg.message)
2487 case WM_NULL:
2488 /* Produced by complete_deferred_msg; just ignore. */
2489 break;
2490 case WM_EMACS_CREATEWINDOW:
2491 /* Initialize COM for this window. Even though we don't use it,
2492 some third party shell extensions can cause it to be used in
2493 system dialogs, which causes a crash if it is not initialized.
2494 This is a known bug in Windows, which was fixed long ago, but
2495 the patch for XP is not publicly available until XP SP3,
2496 and older versions will never be patched. */
2497 CoInitialize (NULL);
2498 w32_createwindow ((struct frame *) msg.wParam,
2499 (int *) msg.lParam);
2500 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2501 emacs_abort ();
2502 break;
2503 case WM_EMACS_SETLOCALE:
2504 SetThreadLocale (msg.wParam);
2505 /* Reply is not expected. */
2506 break;
2507 case WM_EMACS_SETKEYBOARDLAYOUT:
2508 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2509 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2510 result, 0))
2511 emacs_abort ();
2512 break;
2513 case WM_EMACS_REGISTER_HOT_KEY:
2514 focus_window = GetFocus ();
2515 if (focus_window != NULL)
2516 RegisterHotKey (focus_window,
2517 RAW_HOTKEY_ID (msg.wParam),
2518 RAW_HOTKEY_MODIFIERS (msg.wParam),
2519 RAW_HOTKEY_VK_CODE (msg.wParam));
2520 /* Reply is not expected. */
2521 break;
2522 case WM_EMACS_UNREGISTER_HOT_KEY:
2523 focus_window = GetFocus ();
2524 if (focus_window != NULL)
2525 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2526 /* Mark item as erased. NB: this code must be
2527 thread-safe. The next line is okay because the cons
2528 cell is never made into garbage and is not relocated by
2529 GC. */
2530 XSETCAR (XIL ((EMACS_INT) msg.lParam), Qnil);
2531 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2532 emacs_abort ();
2533 break;
2534 case WM_EMACS_TOGGLE_LOCK_KEY:
2536 int vk_code = (int) msg.wParam;
2537 int cur_state = (GetKeyState (vk_code) & 1);
2538 Lisp_Object new_state = XIL ((EMACS_INT) msg.lParam);
2540 /* NB: This code must be thread-safe. It is safe to
2541 call NILP because symbols are not relocated by GC,
2542 and pointer here is not touched by GC (so the markbit
2543 can't be set). Numbers are safe because they are
2544 immediate values. */
2545 if (NILP (new_state)
2546 || (NUMBERP (new_state)
2547 && ((XUINT (new_state)) & 1) != cur_state))
2549 one_w32_display_info.faked_key = vk_code;
2551 keybd_event ((BYTE) vk_code,
2552 (BYTE) MapVirtualKey (vk_code, 0),
2553 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2554 keybd_event ((BYTE) vk_code,
2555 (BYTE) MapVirtualKey (vk_code, 0),
2556 KEYEVENTF_EXTENDEDKEY | 0, 0);
2557 keybd_event ((BYTE) vk_code,
2558 (BYTE) MapVirtualKey (vk_code, 0),
2559 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2560 cur_state = !cur_state;
2562 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2563 cur_state, 0))
2564 emacs_abort ();
2566 break;
2567 #ifdef MSG_DEBUG
2568 /* Broadcast messages make it here, so you need to be looking
2569 for something in particular for this to be useful. */
2570 default:
2571 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2572 #endif
2575 else
2577 if (w32_unicode_gui)
2578 DispatchMessageW (&msg);
2579 else
2580 DispatchMessageA (&msg);
2583 /* Exit nested loop when our deferred message has completed. */
2584 if (msg_buf->completed)
2585 break;
2589 deferred_msg * deferred_msg_head;
2591 static deferred_msg *
2592 find_deferred_msg (HWND hwnd, UINT msg)
2594 deferred_msg * item;
2596 /* Don't actually need synchronization for read access, since
2597 modification of single pointer is always atomic. */
2598 /* enter_crit (); */
2600 for (item = deferred_msg_head; item != NULL; item = item->next)
2601 if (item->w32msg.msg.hwnd == hwnd
2602 && item->w32msg.msg.message == msg)
2603 break;
2605 /* leave_crit (); */
2607 return item;
2610 static LRESULT
2611 send_deferred_msg (deferred_msg * msg_buf,
2612 HWND hwnd,
2613 UINT msg,
2614 WPARAM wParam,
2615 LPARAM lParam)
2617 /* Only input thread can send deferred messages. */
2618 if (GetCurrentThreadId () != dwWindowsThreadId)
2619 emacs_abort ();
2621 /* It is an error to send a message that is already deferred. */
2622 if (find_deferred_msg (hwnd, msg) != NULL)
2623 emacs_abort ();
2625 /* Enforced synchronization is not needed because this is the only
2626 function that alters deferred_msg_head, and the following critical
2627 section is guaranteed to only be serially reentered (since only the
2628 input thread can call us). */
2630 /* enter_crit (); */
2632 msg_buf->completed = 0;
2633 msg_buf->next = deferred_msg_head;
2634 deferred_msg_head = msg_buf;
2635 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2637 /* leave_crit (); */
2639 /* Start a new nested message loop to process other messages until
2640 this one is completed. */
2641 w32_msg_pump (msg_buf);
2643 deferred_msg_head = msg_buf->next;
2645 return msg_buf->result;
2648 void
2649 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2651 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2653 if (msg_buf == NULL)
2654 /* Message may have been canceled, so don't abort. */
2655 return;
2657 msg_buf->result = result;
2658 msg_buf->completed = 1;
2660 /* Ensure input thread is woken so it notices the completion. */
2661 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2664 static void
2665 cancel_all_deferred_msgs (void)
2667 deferred_msg * item;
2669 /* Don't actually need synchronization for read access, since
2670 modification of single pointer is always atomic. */
2671 /* enter_crit (); */
2673 for (item = deferred_msg_head; item != NULL; item = item->next)
2675 item->result = 0;
2676 item->completed = 1;
2679 /* leave_crit (); */
2681 /* Ensure input thread is woken so it notices the completion. */
2682 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2685 DWORD WINAPI
2686 w32_msg_worker (void *arg)
2688 MSG msg;
2689 deferred_msg dummy_buf;
2691 /* Ensure our message queue is created */
2693 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2695 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2696 emacs_abort ();
2698 memset (&dummy_buf, 0, sizeof (dummy_buf));
2699 dummy_buf.w32msg.msg.hwnd = NULL;
2700 dummy_buf.w32msg.msg.message = WM_NULL;
2702 /* This is the initial message loop which should only exit when the
2703 application quits. */
2704 w32_msg_pump (&dummy_buf);
2706 return 0;
2709 static void
2710 signal_user_input (void)
2712 /* Interrupt any lisp that wants to be interrupted by input. */
2713 if (!NILP (Vthrow_on_input))
2715 Vquit_flag = Vthrow_on_input;
2716 /* Doing a QUIT from this thread is a bad idea, since this
2717 unwinds the stack of the Lisp thread, and the Windows runtime
2718 rightfully barfs. Disabled. */
2719 #if 0
2720 /* If we're inside a function that wants immediate quits,
2721 do it now. */
2722 if (immediate_quit && NILP (Vinhibit_quit))
2724 immediate_quit = 0;
2725 QUIT;
2727 #endif
2732 static void
2733 post_character_message (HWND hwnd, UINT msg,
2734 WPARAM wParam, LPARAM lParam,
2735 DWORD modifiers)
2737 W32Msg wmsg;
2739 wmsg.dwModifiers = modifiers;
2741 /* Detect quit_char and set quit-flag directly. Note that we
2742 still need to post a message to ensure the main thread will be
2743 woken up if blocked in sys_select, but we do NOT want to post
2744 the quit_char message itself (because it will usually be as if
2745 the user had typed quit_char twice). Instead, we post a dummy
2746 message that has no particular effect. */
2748 int c = wParam;
2749 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2750 c = make_ctrl_char (c) & 0377;
2751 if (c == quit_char
2752 || (wmsg.dwModifiers == 0
2753 && w32_quit_key && wParam == w32_quit_key))
2755 Vquit_flag = Qt;
2757 /* The choice of message is somewhat arbitrary, as long as
2758 the main thread handler just ignores it. */
2759 msg = WM_NULL;
2761 /* Interrupt any blocking system calls. */
2762 signal_quit ();
2764 /* As a safety precaution, forcibly complete any deferred
2765 messages. This is a kludge, but I don't see any particularly
2766 clean way to handle the situation where a deferred message is
2767 "dropped" in the lisp thread, and will thus never be
2768 completed, eg. by the user trying to activate the menubar
2769 when the lisp thread is busy, and then typing C-g when the
2770 menubar doesn't open promptly (with the result that the
2771 menubar never responds at all because the deferred
2772 WM_INITMENU message is never completed). Another problem
2773 situation is when the lisp thread calls SendMessage (to send
2774 a window manager command) when a message has been deferred;
2775 the lisp thread gets blocked indefinitely waiting for the
2776 deferred message to be completed, which itself is waiting for
2777 the lisp thread to respond.
2779 Note that we don't want to block the input thread waiting for
2780 a response from the lisp thread (although that would at least
2781 solve the deadlock problem above), because we want to be able
2782 to receive C-g to interrupt the lisp thread. */
2783 cancel_all_deferred_msgs ();
2785 else
2786 signal_user_input ();
2789 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2792 /* Main window procedure */
2794 static LRESULT CALLBACK
2795 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2797 struct frame *f;
2798 struct w32_display_info *dpyinfo = &one_w32_display_info;
2799 W32Msg wmsg;
2800 int windows_translate;
2801 int key;
2803 /* Note that it is okay to call x_window_to_frame, even though we are
2804 not running in the main lisp thread, because frame deletion
2805 requires the lisp thread to synchronize with this thread. Thus, if
2806 a frame struct is returned, it can be used without concern that the
2807 lisp thread might make it disappear while we are using it.
2809 NB. Walking the frame list in this thread is safe (as long as
2810 writes of Lisp_Object slots are atomic, which they are on Windows).
2811 Although delete-frame can destructively modify the frame list while
2812 we are walking it, a garbage collection cannot occur until after
2813 delete-frame has synchronized with this thread.
2815 It is also safe to use functions that make GDI calls, such as
2816 w32_clear_rect, because these functions must obtain a DC handle
2817 from the frame struct using get_frame_dc which is thread-aware. */
2819 switch (msg)
2821 case WM_ERASEBKGND:
2822 f = x_window_to_frame (dpyinfo, hwnd);
2823 if (f)
2825 HDC hdc = get_frame_dc (f);
2826 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2827 w32_clear_rect (f, hdc, &wmsg.rect);
2828 release_frame_dc (f, hdc);
2830 #if defined (W32_DEBUG_DISPLAY)
2831 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2833 wmsg.rect.left, wmsg.rect.top,
2834 wmsg.rect.right, wmsg.rect.bottom));
2835 #endif /* W32_DEBUG_DISPLAY */
2837 return 1;
2838 case WM_PALETTECHANGED:
2839 /* ignore our own changes */
2840 if ((HWND)wParam != hwnd)
2842 f = x_window_to_frame (dpyinfo, hwnd);
2843 if (f)
2844 /* get_frame_dc will realize our palette and force all
2845 frames to be redrawn if needed. */
2846 release_frame_dc (f, get_frame_dc (f));
2848 return 0;
2849 case WM_PAINT:
2851 PAINTSTRUCT paintStruct;
2852 RECT update_rect;
2853 memset (&update_rect, 0, sizeof (update_rect));
2855 f = x_window_to_frame (dpyinfo, hwnd);
2856 if (f == 0)
2858 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2859 return 0;
2862 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2863 fails. Apparently this can happen under some
2864 circumstances. */
2865 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2867 enter_crit ();
2868 BeginPaint (hwnd, &paintStruct);
2870 /* The rectangles returned by GetUpdateRect and BeginPaint
2871 do not always match. Play it safe by assuming both areas
2872 are invalid. */
2873 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2875 #if defined (W32_DEBUG_DISPLAY)
2876 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2878 wmsg.rect.left, wmsg.rect.top,
2879 wmsg.rect.right, wmsg.rect.bottom));
2880 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2881 update_rect.left, update_rect.top,
2882 update_rect.right, update_rect.bottom));
2883 #endif
2884 EndPaint (hwnd, &paintStruct);
2885 leave_crit ();
2887 /* Change the message type to prevent Windows from
2888 combining WM_PAINT messages in the Lisp thread's queue,
2889 since Windows assumes that each message queue is
2890 dedicated to one frame and does not bother checking
2891 that hwnd matches before combining them. */
2892 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
2894 return 0;
2897 /* If GetUpdateRect returns 0 (meaning there is no update
2898 region), assume the whole window needs to be repainted. */
2899 GetClientRect (hwnd, &wmsg.rect);
2900 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2901 return 0;
2904 case WM_INPUTLANGCHANGE:
2905 /* Inform lisp thread of keyboard layout changes. */
2906 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2908 /* Clear dead keys in the keyboard state; for simplicity only
2909 preserve modifier key states. */
2911 int i;
2912 BYTE keystate[256];
2914 GetKeyboardState (keystate);
2915 for (i = 0; i < 256; i++)
2916 if (1
2917 && i != VK_SHIFT
2918 && i != VK_LSHIFT
2919 && i != VK_RSHIFT
2920 && i != VK_CAPITAL
2921 && i != VK_NUMLOCK
2922 && i != VK_SCROLL
2923 && i != VK_CONTROL
2924 && i != VK_LCONTROL
2925 && i != VK_RCONTROL
2926 && i != VK_MENU
2927 && i != VK_LMENU
2928 && i != VK_RMENU
2929 && i != VK_LWIN
2930 && i != VK_RWIN)
2931 keystate[i] = 0;
2932 SetKeyboardState (keystate);
2934 goto dflt;
2936 case WM_HOTKEY:
2937 /* Synchronize hot keys with normal input. */
2938 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2939 return (0);
2941 case WM_KEYUP:
2942 case WM_SYSKEYUP:
2943 record_keyup (wParam, lParam);
2944 goto dflt;
2946 case WM_KEYDOWN:
2947 case WM_SYSKEYDOWN:
2948 /* Ignore keystrokes we fake ourself; see below. */
2949 if (dpyinfo->faked_key == wParam)
2951 dpyinfo->faked_key = 0;
2952 /* Make sure TranslateMessage sees them though (as long as
2953 they don't produce WM_CHAR messages). This ensures that
2954 indicator lights are toggled promptly on Windows 9x, for
2955 example. */
2956 if (wParam < 256 && lispy_function_keys[wParam])
2958 windows_translate = 1;
2959 goto translate;
2961 return 0;
2964 /* Synchronize modifiers with current keystroke. */
2965 sync_modifiers ();
2966 record_keydown (wParam, lParam);
2967 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2969 windows_translate = 0;
2971 switch (wParam)
2973 case VK_LWIN:
2974 if (NILP (Vw32_pass_lwindow_to_system))
2976 /* Prevent system from acting on keyup (which opens the
2977 Start menu if no other key was pressed) by simulating a
2978 press of Space which we will ignore. */
2979 if (GetAsyncKeyState (wParam) & 1)
2981 if (NUMBERP (Vw32_phantom_key_code))
2982 key = XUINT (Vw32_phantom_key_code) & 255;
2983 else
2984 key = VK_SPACE;
2985 dpyinfo->faked_key = key;
2986 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2989 if (!NILP (Vw32_lwindow_modifier))
2990 return 0;
2991 break;
2992 case VK_RWIN:
2993 if (NILP (Vw32_pass_rwindow_to_system))
2995 if (GetAsyncKeyState (wParam) & 1)
2997 if (NUMBERP (Vw32_phantom_key_code))
2998 key = XUINT (Vw32_phantom_key_code) & 255;
2999 else
3000 key = VK_SPACE;
3001 dpyinfo->faked_key = key;
3002 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
3005 if (!NILP (Vw32_rwindow_modifier))
3006 return 0;
3007 break;
3008 case VK_APPS:
3009 if (!NILP (Vw32_apps_modifier))
3010 return 0;
3011 break;
3012 case VK_MENU:
3013 if (NILP (Vw32_pass_alt_to_system))
3014 /* Prevent DefWindowProc from activating the menu bar if an
3015 Alt key is pressed and released by itself. */
3016 return 0;
3017 windows_translate = 1;
3018 break;
3019 case VK_CAPITAL:
3020 /* Decide whether to treat as modifier or function key. */
3021 if (NILP (Vw32_enable_caps_lock))
3022 goto disable_lock_key;
3023 windows_translate = 1;
3024 break;
3025 case VK_NUMLOCK:
3026 /* Decide whether to treat as modifier or function key. */
3027 if (NILP (Vw32_enable_num_lock))
3028 goto disable_lock_key;
3029 windows_translate = 1;
3030 break;
3031 case VK_SCROLL:
3032 /* Decide whether to treat as modifier or function key. */
3033 if (NILP (Vw32_scroll_lock_modifier))
3034 goto disable_lock_key;
3035 windows_translate = 1;
3036 break;
3037 disable_lock_key:
3038 /* Ensure the appropriate lock key state (and indicator light)
3039 remains in the same state. We do this by faking another
3040 press of the relevant key. Apparently, this really is the
3041 only way to toggle the state of the indicator lights. */
3042 dpyinfo->faked_key = wParam;
3043 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3044 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3045 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3046 KEYEVENTF_EXTENDEDKEY | 0, 0);
3047 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3048 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3049 /* Ensure indicator lights are updated promptly on Windows 9x
3050 (TranslateMessage apparently does this), after forwarding
3051 input event. */
3052 post_character_message (hwnd, msg, wParam, lParam,
3053 w32_get_key_modifiers (wParam, lParam));
3054 windows_translate = 1;
3055 break;
3056 case VK_CONTROL:
3057 case VK_SHIFT:
3058 case VK_PROCESSKEY: /* Generated by IME. */
3059 windows_translate = 1;
3060 break;
3061 case VK_CANCEL:
3062 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3063 which is confusing for purposes of key binding; convert
3064 VK_CANCEL events into VK_PAUSE events. */
3065 wParam = VK_PAUSE;
3066 break;
3067 case VK_PAUSE:
3068 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3069 for purposes of key binding; convert these back into
3070 VK_NUMLOCK events, at least when we want to see NumLock key
3071 presses. (Note that there is never any possibility that
3072 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3073 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3074 wParam = VK_NUMLOCK;
3075 break;
3076 default:
3077 /* If not defined as a function key, change it to a WM_CHAR message. */
3078 if (wParam > 255 || !lispy_function_keys[wParam])
3080 DWORD modifiers = construct_console_modifiers ();
3082 if (!NILP (Vw32_recognize_altgr)
3083 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3085 /* Always let TranslateMessage handle AltGr key chords;
3086 for some reason, ToAscii doesn't always process AltGr
3087 chords correctly. */
3088 windows_translate = 1;
3090 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3092 /* Handle key chords including any modifiers other
3093 than shift directly, in order to preserve as much
3094 modifier information as possible. */
3095 if ('A' <= wParam && wParam <= 'Z')
3097 /* Don't translate modified alphabetic keystrokes,
3098 so the user doesn't need to constantly switch
3099 layout to type control or meta keystrokes when
3100 the normal layout translates alphabetic
3101 characters to non-ascii characters. */
3102 if (!modifier_set (VK_SHIFT))
3103 wParam += ('a' - 'A');
3104 msg = WM_CHAR;
3106 else
3108 /* Try to handle other keystrokes by determining the
3109 base character (ie. translating the base key plus
3110 shift modifier). */
3111 int add;
3112 KEY_EVENT_RECORD key;
3114 key.bKeyDown = TRUE;
3115 key.wRepeatCount = 1;
3116 key.wVirtualKeyCode = wParam;
3117 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3118 key.uChar.AsciiChar = 0;
3119 key.dwControlKeyState = modifiers;
3121 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3122 /* 0 means an unrecognized keycode, negative means
3123 dead key. Ignore both. */
3124 while (--add >= 0)
3126 /* Forward asciified character sequence. */
3127 post_character_message
3128 (hwnd, WM_CHAR,
3129 (unsigned char) key.uChar.AsciiChar, lParam,
3130 w32_get_key_modifiers (wParam, lParam));
3131 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3133 return 0;
3136 else
3138 /* Let TranslateMessage handle everything else. */
3139 windows_translate = 1;
3144 translate:
3145 if (windows_translate)
3147 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3148 windows_msg.time = GetMessageTime ();
3149 TranslateMessage (&windows_msg);
3150 goto dflt;
3153 /* Fall through */
3155 case WM_SYSCHAR:
3156 case WM_CHAR:
3157 if (wParam > 255 )
3159 W32Msg wmsg;
3161 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3162 signal_user_input ();
3163 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3166 else
3167 post_character_message (hwnd, msg, wParam, lParam,
3168 w32_get_key_modifiers (wParam, lParam));
3169 break;
3171 case WM_UNICHAR:
3172 /* WM_UNICHAR looks promising from the docs, but the exact
3173 circumstances in which TranslateMessage sends it is one of those
3174 Microsoft secret API things that EU and US courts are supposed
3175 to have put a stop to already. Spy++ shows it being sent to Notepad
3176 and other MS apps, but never to Emacs.
3178 Some third party IMEs send it in accordance with the official
3179 documentation though, so handle it here.
3181 UNICODE_NOCHAR is used to test for support for this message.
3182 TRUE indicates that the message is supported. */
3183 if (wParam == UNICODE_NOCHAR)
3184 return TRUE;
3187 W32Msg wmsg;
3188 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3189 signal_user_input ();
3190 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3192 break;
3194 case WM_IME_CHAR:
3195 /* If we can't get the IME result as Unicode, use default processing,
3196 which will at least allow characters decodable in the system locale
3197 get through. */
3198 if (!get_composition_string_fn)
3199 goto dflt;
3201 else if (!ignore_ime_char)
3203 wchar_t * buffer;
3204 int size, i;
3205 W32Msg wmsg;
3206 HIMC context = get_ime_context_fn (hwnd);
3207 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3208 /* Get buffer size. */
3209 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3210 buffer = alloca (size);
3211 size = get_composition_string_fn (context, GCS_RESULTSTR,
3212 buffer, size);
3213 release_ime_context_fn (hwnd, context);
3215 signal_user_input ();
3216 for (i = 0; i < size / sizeof (wchar_t); i++)
3218 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3219 lParam);
3221 /* Ignore the messages for the rest of the
3222 characters in the string that was output above. */
3223 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3225 else
3226 ignore_ime_char--;
3228 break;
3230 case WM_IME_STARTCOMPOSITION:
3231 if (!set_ime_composition_window_fn)
3232 goto dflt;
3233 else
3235 COMPOSITIONFORM form;
3236 HIMC context;
3237 struct window *w;
3239 /* Implementation note: The code below does something that
3240 one shouldn't do: it accesses the window object from a
3241 separate thread, while the main (a.k.a. "Lisp") thread
3242 runs and can legitimately delete and even GC it. That is
3243 why we are extra careful not to futz with a window that
3244 is different from the one recorded when the system caret
3245 coordinates were last modified. That is also why we are
3246 careful not to move the IME window if the window
3247 described by W was deleted, as indicated by its buffer
3248 field being reset to nil. */
3249 f = x_window_to_frame (dpyinfo, hwnd);
3250 if (!(f && FRAME_LIVE_P (f)))
3251 break;
3252 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3253 /* Punt if someone changed the frame's selected window
3254 behind our back. */
3255 if (w != w32_system_caret_window)
3256 break;
3258 form.dwStyle = CFS_RECT;
3259 form.ptCurrentPos.x = w32_system_caret_x;
3260 form.ptCurrentPos.y = w32_system_caret_y;
3262 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3263 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3264 + w32_system_caret_hdr_height);
3265 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3266 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3267 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3268 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3269 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3270 - w32_system_caret_mode_height);
3272 /* Punt if the window was deleted behind our back. */
3273 if (!BUFFERP (w->contents))
3274 break;
3276 context = get_ime_context_fn (hwnd);
3278 if (!context)
3279 break;
3281 set_ime_composition_window_fn (context, &form);
3282 release_ime_context_fn (hwnd, context);
3284 break;
3286 case WM_IME_ENDCOMPOSITION:
3287 ignore_ime_char = 0;
3288 goto dflt;
3290 /* Simulate middle mouse button events when left and right buttons
3291 are used together, but only if user has two button mouse. */
3292 case WM_LBUTTONDOWN:
3293 case WM_RBUTTONDOWN:
3294 if (w32_num_mouse_buttons > 2)
3295 goto handle_plain_button;
3298 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3299 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3301 if (button_state & this)
3302 return 0;
3304 if (button_state == 0)
3305 SetCapture (hwnd);
3307 button_state |= this;
3309 if (button_state & other)
3311 if (mouse_button_timer)
3313 KillTimer (hwnd, mouse_button_timer);
3314 mouse_button_timer = 0;
3316 /* Generate middle mouse event instead. */
3317 msg = WM_MBUTTONDOWN;
3318 button_state |= MMOUSE;
3320 else if (button_state & MMOUSE)
3322 /* Ignore button event if we've already generated a
3323 middle mouse down event. This happens if the
3324 user releases and press one of the two buttons
3325 after we've faked a middle mouse event. */
3326 return 0;
3328 else
3330 /* Flush out saved message. */
3331 post_msg (&saved_mouse_button_msg);
3333 wmsg.dwModifiers = w32_get_modifiers ();
3334 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3335 signal_user_input ();
3337 /* Clear message buffer. */
3338 saved_mouse_button_msg.msg.hwnd = 0;
3340 else
3342 /* Hold onto message for now. */
3343 mouse_button_timer =
3344 SetTimer (hwnd, MOUSE_BUTTON_ID,
3345 w32_mouse_button_tolerance, NULL);
3346 saved_mouse_button_msg.msg.hwnd = hwnd;
3347 saved_mouse_button_msg.msg.message = msg;
3348 saved_mouse_button_msg.msg.wParam = wParam;
3349 saved_mouse_button_msg.msg.lParam = lParam;
3350 saved_mouse_button_msg.msg.time = GetMessageTime ();
3351 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3354 return 0;
3356 case WM_LBUTTONUP:
3357 case WM_RBUTTONUP:
3358 if (w32_num_mouse_buttons > 2)
3359 goto handle_plain_button;
3362 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3363 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3365 if ((button_state & this) == 0)
3366 return 0;
3368 button_state &= ~this;
3370 if (button_state & MMOUSE)
3372 /* Only generate event when second button is released. */
3373 if ((button_state & other) == 0)
3375 msg = WM_MBUTTONUP;
3376 button_state &= ~MMOUSE;
3378 if (button_state) emacs_abort ();
3380 else
3381 return 0;
3383 else
3385 /* Flush out saved message if necessary. */
3386 if (saved_mouse_button_msg.msg.hwnd)
3388 post_msg (&saved_mouse_button_msg);
3391 wmsg.dwModifiers = w32_get_modifiers ();
3392 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3393 signal_user_input ();
3395 /* Always clear message buffer and cancel timer. */
3396 saved_mouse_button_msg.msg.hwnd = 0;
3397 KillTimer (hwnd, mouse_button_timer);
3398 mouse_button_timer = 0;
3400 if (button_state == 0)
3401 ReleaseCapture ();
3403 return 0;
3405 case WM_XBUTTONDOWN:
3406 case WM_XBUTTONUP:
3407 if (w32_pass_extra_mouse_buttons_to_system)
3408 goto dflt;
3409 /* else fall through and process them. */
3410 case WM_MBUTTONDOWN:
3411 case WM_MBUTTONUP:
3412 handle_plain_button:
3414 BOOL up;
3415 int button;
3417 /* Ignore middle and extra buttons as long as the menu is active. */
3418 f = x_window_to_frame (dpyinfo, hwnd);
3419 if (f && f->output_data.w32->menubar_active)
3420 return 0;
3422 if (parse_button (msg, HIWORD (wParam), &button, &up))
3424 if (up) ReleaseCapture ();
3425 else SetCapture (hwnd);
3426 button = (button == 0) ? LMOUSE :
3427 ((button == 1) ? MMOUSE : RMOUSE);
3428 if (up)
3429 button_state &= ~button;
3430 else
3431 button_state |= button;
3435 wmsg.dwModifiers = w32_get_modifiers ();
3436 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3437 signal_user_input ();
3439 /* Need to return true for XBUTTON messages, false for others,
3440 to indicate that we processed the message. */
3441 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3443 case WM_MOUSEMOVE:
3444 /* Ignore mouse movements as long as the menu is active. These
3445 movements are processed by the window manager anyway, and
3446 it's wrong to handle them as if they happened on the
3447 underlying frame. */
3448 f = x_window_to_frame (dpyinfo, hwnd);
3449 if (f && f->output_data.w32->menubar_active)
3450 return 0;
3452 /* If the mouse has just moved into the frame, start tracking
3453 it, so we will be notified when it leaves the frame. Mouse
3454 tracking only works under W98 and NT4 and later. On earlier
3455 versions, there is no way of telling when the mouse leaves the
3456 frame, so we just have to put up with help-echo and mouse
3457 highlighting remaining while the frame is not active. */
3458 if (track_mouse_event_fn && !track_mouse_window
3459 /* If the menu bar is active, turning on tracking of mouse
3460 movement events might send these events to the tooltip
3461 frame, if the user happens to move the mouse pointer over
3462 the tooltip. But since we don't process events for
3463 tooltip frames, this causes Windows to present a
3464 hourglass cursor, which is ugly and unexpected. So don't
3465 enable tracking mouse events in this case; they will be
3466 restarted when the menu pops down. (Confusingly, the
3467 menubar_active member of f->output_data.w32, tested
3468 above, is only set when a menu was popped up _not_ from
3469 the frame's menu bar, but via x-popup-menu.) */
3470 && !menubar_in_use)
3472 TRACKMOUSEEVENT tme;
3473 tme.cbSize = sizeof (tme);
3474 tme.dwFlags = TME_LEAVE;
3475 tme.hwndTrack = hwnd;
3476 tme.dwHoverTime = HOVER_DEFAULT;
3478 track_mouse_event_fn (&tme);
3479 track_mouse_window = hwnd;
3481 case WM_VSCROLL:
3482 if (w32_mouse_move_interval <= 0
3483 || (msg == WM_MOUSEMOVE && button_state == 0))
3485 wmsg.dwModifiers = w32_get_modifiers ();
3486 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3487 return 0;
3490 /* Hang onto mouse move and scroll messages for a bit, to avoid
3491 sending such events to Emacs faster than it can process them.
3492 If we get more events before the timer from the first message
3493 expires, we just replace the first message. */
3495 if (saved_mouse_move_msg.msg.hwnd == 0)
3496 mouse_move_timer =
3497 SetTimer (hwnd, MOUSE_MOVE_ID,
3498 w32_mouse_move_interval, NULL);
3500 /* Hold onto message for now. */
3501 saved_mouse_move_msg.msg.hwnd = hwnd;
3502 saved_mouse_move_msg.msg.message = msg;
3503 saved_mouse_move_msg.msg.wParam = wParam;
3504 saved_mouse_move_msg.msg.lParam = lParam;
3505 saved_mouse_move_msg.msg.time = GetMessageTime ();
3506 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3508 return 0;
3510 case WM_MOUSEWHEEL:
3511 case WM_DROPFILES:
3512 wmsg.dwModifiers = w32_get_modifiers ();
3513 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3514 signal_user_input ();
3515 return 0;
3517 case WM_APPCOMMAND:
3518 if (w32_pass_multimedia_buttons_to_system)
3519 goto dflt;
3520 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3521 case WM_MOUSEHWHEEL:
3522 wmsg.dwModifiers = w32_get_modifiers ();
3523 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3524 signal_user_input ();
3525 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3526 handled, to prevent the system trying to handle it by faking
3527 scroll bar events. */
3528 return 1;
3530 case WM_TIMER:
3531 /* Flush out saved messages if necessary. */
3532 if (wParam == mouse_button_timer)
3534 if (saved_mouse_button_msg.msg.hwnd)
3536 post_msg (&saved_mouse_button_msg);
3537 signal_user_input ();
3538 saved_mouse_button_msg.msg.hwnd = 0;
3540 KillTimer (hwnd, mouse_button_timer);
3541 mouse_button_timer = 0;
3543 else if (wParam == mouse_move_timer)
3545 if (saved_mouse_move_msg.msg.hwnd)
3547 post_msg (&saved_mouse_move_msg);
3548 saved_mouse_move_msg.msg.hwnd = 0;
3550 KillTimer (hwnd, mouse_move_timer);
3551 mouse_move_timer = 0;
3553 else if (wParam == menu_free_timer)
3555 KillTimer (hwnd, menu_free_timer);
3556 menu_free_timer = 0;
3557 f = x_window_to_frame (dpyinfo, hwnd);
3558 /* If a popup menu is active, don't wipe its strings. */
3559 if (menubar_in_use
3560 && current_popup_menu == NULL)
3562 /* Free memory used by owner-drawn and help-echo strings. */
3563 w32_free_menu_strings (hwnd);
3564 if (f)
3565 f->output_data.w32->menubar_active = 0;
3566 menubar_in_use = 0;
3569 return 0;
3571 case WM_NCACTIVATE:
3572 /* Windows doesn't send us focus messages when putting up and
3573 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3574 The only indication we get that something happened is receiving
3575 this message afterwards. So this is a good time to reset our
3576 keyboard modifiers' state. */
3577 reset_modifiers ();
3578 goto dflt;
3580 case WM_INITMENU:
3581 button_state = 0;
3582 ReleaseCapture ();
3583 /* We must ensure menu bar is fully constructed and up to date
3584 before allowing user interaction with it. To achieve this
3585 we send this message to the lisp thread and wait for a
3586 reply (whose value is not actually needed) to indicate that
3587 the menu bar is now ready for use, so we can now return.
3589 To remain responsive in the meantime, we enter a nested message
3590 loop that can process all other messages.
3592 However, we skip all this if the message results from calling
3593 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3594 thread a message because it is blocked on us at this point. We
3595 set menubar_active before calling TrackPopupMenu to indicate
3596 this (there is no possibility of confusion with real menubar
3597 being active). */
3599 f = x_window_to_frame (dpyinfo, hwnd);
3600 if (f
3601 && (f->output_data.w32->menubar_active
3602 /* We can receive this message even in the absence of a
3603 menubar (ie. when the system menu is activated) - in this
3604 case we do NOT want to forward the message, otherwise it
3605 will cause the menubar to suddenly appear when the user
3606 had requested it to be turned off! */
3607 || f->output_data.w32->menubar_widget == NULL))
3608 return 0;
3611 deferred_msg msg_buf;
3613 /* Detect if message has already been deferred; in this case
3614 we cannot return any sensible value to ignore this. */
3615 if (find_deferred_msg (hwnd, msg) != NULL)
3616 emacs_abort ();
3618 menubar_in_use = 1;
3620 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3623 case WM_EXITMENULOOP:
3624 f = x_window_to_frame (dpyinfo, hwnd);
3626 /* If a menu is still active, check again after a short delay,
3627 since Windows often (always?) sends the WM_EXITMENULOOP
3628 before the corresponding WM_COMMAND message.
3629 Don't do this if a popup menu is active, since it is only
3630 menubar menus that require cleaning up in this way.
3632 if (f && menubar_in_use && current_popup_menu == NULL)
3633 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3635 /* If hourglass cursor should be displayed, display it now. */
3636 if (f && f->output_data.w32->hourglass_p)
3637 SetCursor (f->output_data.w32->hourglass_cursor);
3639 goto dflt;
3641 case WM_MENUSELECT:
3642 /* Direct handling of help_echo in menus. Should be safe now
3643 that we generate the help_echo by placing a help event in the
3644 keyboard buffer. */
3646 HMENU menu = (HMENU) lParam;
3647 UINT menu_item = (UINT) LOWORD (wParam);
3648 UINT flags = (UINT) HIWORD (wParam);
3650 w32_menu_display_help (hwnd, menu, menu_item, flags);
3652 return 0;
3654 case WM_MEASUREITEM:
3655 f = x_window_to_frame (dpyinfo, hwnd);
3656 if (f)
3658 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3660 if (pMis->CtlType == ODT_MENU)
3662 /* Work out dimensions for popup menu titles. */
3663 char * title = (char *) pMis->itemData;
3664 HDC hdc = GetDC (hwnd);
3665 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3666 LOGFONT menu_logfont;
3667 HFONT old_font;
3668 SIZE size;
3670 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3671 menu_logfont.lfWeight = FW_BOLD;
3672 menu_font = CreateFontIndirect (&menu_logfont);
3673 old_font = SelectObject (hdc, menu_font);
3675 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3676 if (title)
3678 if (unicode_append_menu)
3679 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3680 wcslen ((WCHAR *) title),
3681 &size);
3682 else
3683 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3685 pMis->itemWidth = size.cx;
3686 if (pMis->itemHeight < size.cy)
3687 pMis->itemHeight = size.cy;
3689 else
3690 pMis->itemWidth = 0;
3692 SelectObject (hdc, old_font);
3693 DeleteObject (menu_font);
3694 ReleaseDC (hwnd, hdc);
3695 return TRUE;
3698 return 0;
3700 case WM_DRAWITEM:
3701 f = x_window_to_frame (dpyinfo, hwnd);
3702 if (f)
3704 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3706 if (pDis->CtlType == ODT_MENU)
3708 /* Draw popup menu title. */
3709 char * title = (char *) pDis->itemData;
3710 if (title)
3712 HDC hdc = pDis->hDC;
3713 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3714 LOGFONT menu_logfont;
3715 HFONT old_font;
3717 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3718 menu_logfont.lfWeight = FW_BOLD;
3719 menu_font = CreateFontIndirect (&menu_logfont);
3720 old_font = SelectObject (hdc, menu_font);
3722 /* Always draw title as if not selected. */
3723 if (unicode_append_menu)
3724 ExtTextOutW (hdc,
3725 pDis->rcItem.left
3726 + GetSystemMetrics (SM_CXMENUCHECK),
3727 pDis->rcItem.top,
3728 ETO_OPAQUE, &pDis->rcItem,
3729 (WCHAR *) title,
3730 wcslen ((WCHAR *) title), NULL);
3731 else
3732 ExtTextOut (hdc,
3733 pDis->rcItem.left
3734 + GetSystemMetrics (SM_CXMENUCHECK),
3735 pDis->rcItem.top,
3736 ETO_OPAQUE, &pDis->rcItem,
3737 title, strlen (title), NULL);
3739 SelectObject (hdc, old_font);
3740 DeleteObject (menu_font);
3742 return TRUE;
3745 return 0;
3747 #if 0
3748 /* Still not right - can't distinguish between clicks in the
3749 client area of the frame from clicks forwarded from the scroll
3750 bars - may have to hook WM_NCHITTEST to remember the mouse
3751 position and then check if it is in the client area ourselves. */
3752 case WM_MOUSEACTIVATE:
3753 /* Discard the mouse click that activates a frame, allowing the
3754 user to click anywhere without changing point (or worse!).
3755 Don't eat mouse clicks on scrollbars though!! */
3756 if (LOWORD (lParam) == HTCLIENT )
3757 return MA_ACTIVATEANDEAT;
3758 goto dflt;
3759 #endif
3761 case WM_MOUSELEAVE:
3762 /* No longer tracking mouse. */
3763 track_mouse_window = NULL;
3765 case WM_ACTIVATEAPP:
3766 case WM_ACTIVATE:
3767 case WM_WINDOWPOSCHANGED:
3768 case WM_SHOWWINDOW:
3769 /* Inform lisp thread that a frame might have just been obscured
3770 or exposed, so should recheck visibility of all frames. */
3771 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3772 goto dflt;
3774 case WM_SETFOCUS:
3775 dpyinfo->faked_key = 0;
3776 reset_modifiers ();
3777 register_hot_keys (hwnd);
3778 goto command;
3779 case WM_KILLFOCUS:
3780 unregister_hot_keys (hwnd);
3781 button_state = 0;
3782 ReleaseCapture ();
3783 /* Relinquish the system caret. */
3784 if (w32_system_caret_hwnd)
3786 w32_visible_system_caret_hwnd = NULL;
3787 w32_system_caret_hwnd = NULL;
3788 DestroyCaret ();
3790 goto command;
3791 case WM_COMMAND:
3792 menubar_in_use = 0;
3793 f = x_window_to_frame (dpyinfo, hwnd);
3794 if (f && HIWORD (wParam) == 0)
3796 if (menu_free_timer)
3798 KillTimer (hwnd, menu_free_timer);
3799 menu_free_timer = 0;
3802 case WM_MOVE:
3803 case WM_SIZE:
3804 command:
3805 wmsg.dwModifiers = w32_get_modifiers ();
3806 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3807 goto dflt;
3809 case WM_DESTROY:
3810 CoUninitialize ();
3811 return 0;
3813 case WM_CLOSE:
3814 wmsg.dwModifiers = w32_get_modifiers ();
3815 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3816 return 0;
3818 case WM_WINDOWPOSCHANGING:
3819 /* Don't restrict the sizing of tip frames. */
3820 if (frame_resize_pixelwise || hwnd == tip_window)
3821 return 0;
3823 /* Don't restrict the sizing of fullscreened frames, allowing them to be
3824 flush with the sides of the screen. */
3825 f = x_window_to_frame (dpyinfo, hwnd);
3826 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
3827 return 0;
3830 WINDOWPLACEMENT wp;
3831 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3833 wp.length = sizeof (WINDOWPLACEMENT);
3834 GetWindowPlacement (hwnd, &wp);
3836 if (wp.showCmd != SW_SHOWMAXIMIZED && wp.showCmd != SW_SHOWMINIMIZED
3837 && (lppos->flags & SWP_NOSIZE) == 0)
3839 RECT rect;
3840 int wdiff;
3841 int hdiff;
3842 DWORD font_width;
3843 DWORD line_height;
3844 DWORD internal_border;
3845 DWORD scrollbar_extra;
3846 RECT wr;
3848 wp.length = sizeof (wp);
3849 GetWindowRect (hwnd, &wr);
3851 enter_crit ();
3853 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3854 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3855 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3856 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3858 leave_crit ();
3860 memset (&rect, 0, sizeof (rect));
3861 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3862 GetMenu (hwnd) != NULL);
3864 /* Force width and height of client area to be exact
3865 multiples of the character cell dimensions. */
3866 wdiff = (lppos->cx - (rect.right - rect.left)
3867 - 2 * internal_border - scrollbar_extra)
3868 % font_width;
3869 hdiff = (lppos->cy - (rect.bottom - rect.top)
3870 - 2 * internal_border)
3871 % line_height;
3873 if (wdiff || hdiff)
3875 /* For right/bottom sizing we can just fix the sizes.
3876 However for top/left sizing we will need to fix the X
3877 and Y positions as well. */
3879 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3880 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3882 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3883 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3885 if (wp.showCmd != SW_SHOWMAXIMIZED
3886 && (lppos->flags & SWP_NOMOVE) == 0)
3888 if (lppos->x != wr.left || lppos->y != wr.top)
3890 lppos->x += wdiff;
3891 lppos->y += hdiff;
3893 else
3895 lppos->flags |= SWP_NOMOVE;
3899 return 0;
3904 goto dflt;
3906 case WM_GETMINMAXINFO:
3907 /* Hack to allow resizing the Emacs frame above the screen size.
3908 Note that Windows 9x limits coordinates to 16-bits. */
3909 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3910 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3911 return 0;
3913 case WM_SETCURSOR:
3914 if (LOWORD (lParam) == HTCLIENT)
3916 f = x_window_to_frame (dpyinfo, hwnd);
3917 if (f && f->output_data.w32->hourglass_p
3918 && !menubar_in_use && !current_popup_menu)
3919 SetCursor (f->output_data.w32->hourglass_cursor);
3920 else if (f)
3921 SetCursor (f->output_data.w32->current_cursor);
3922 return 0;
3924 goto dflt;
3926 case WM_EMACS_SETCURSOR:
3928 Cursor cursor = (Cursor) wParam;
3929 f = x_window_to_frame (dpyinfo, hwnd);
3930 if (f && cursor)
3932 f->output_data.w32->current_cursor = cursor;
3933 if (!f->output_data.w32->hourglass_p)
3934 SetCursor (cursor);
3936 return 0;
3939 case WM_EMACS_CREATESCROLLBAR:
3940 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3941 (struct scroll_bar *) lParam);
3943 case WM_EMACS_SHOWWINDOW:
3944 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3946 case WM_EMACS_BRINGTOTOP:
3947 case WM_EMACS_SETFOREGROUND:
3949 HWND foreground_window;
3950 DWORD foreground_thread, retval;
3952 /* On NT 5.0, and apparently Windows 98, it is necessary to
3953 attach to the thread that currently has focus in order to
3954 pull the focus away from it. */
3955 foreground_window = GetForegroundWindow ();
3956 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3957 if (!foreground_window
3958 || foreground_thread == GetCurrentThreadId ()
3959 || !AttachThreadInput (GetCurrentThreadId (),
3960 foreground_thread, TRUE))
3961 foreground_thread = 0;
3963 retval = SetForegroundWindow ((HWND) wParam);
3964 if (msg == WM_EMACS_BRINGTOTOP)
3965 retval = BringWindowToTop ((HWND) wParam);
3967 /* Detach from the previous foreground thread. */
3968 if (foreground_thread)
3969 AttachThreadInput (GetCurrentThreadId (),
3970 foreground_thread, FALSE);
3972 return retval;
3975 case WM_EMACS_SETWINDOWPOS:
3977 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3978 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3979 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3982 case WM_EMACS_DESTROYWINDOW:
3983 DragAcceptFiles ((HWND) wParam, FALSE);
3984 return DestroyWindow ((HWND) wParam);
3986 case WM_EMACS_HIDE_CARET:
3987 return HideCaret (hwnd);
3989 case WM_EMACS_SHOW_CARET:
3990 return ShowCaret (hwnd);
3992 case WM_EMACS_DESTROY_CARET:
3993 w32_system_caret_hwnd = NULL;
3994 w32_visible_system_caret_hwnd = NULL;
3995 return DestroyCaret ();
3997 case WM_EMACS_TRACK_CARET:
3998 /* If there is currently no system caret, create one. */
3999 if (w32_system_caret_hwnd == NULL)
4001 /* Use the default caret width, and avoid changing it
4002 unnecessarily, as it confuses screen reader software. */
4003 w32_system_caret_hwnd = hwnd;
4004 CreateCaret (hwnd, NULL, 0,
4005 w32_system_caret_height);
4008 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
4009 return 0;
4010 /* Ensure visible caret gets turned on when requested. */
4011 else if (w32_use_visible_system_caret
4012 && w32_visible_system_caret_hwnd != hwnd)
4014 w32_visible_system_caret_hwnd = hwnd;
4015 return ShowCaret (hwnd);
4017 /* Ensure visible caret gets turned off when requested. */
4018 else if (!w32_use_visible_system_caret
4019 && w32_visible_system_caret_hwnd)
4021 w32_visible_system_caret_hwnd = NULL;
4022 return HideCaret (hwnd);
4024 else
4025 return 1;
4027 case WM_EMACS_TRACKPOPUPMENU:
4029 UINT flags;
4030 POINT *pos;
4031 int retval;
4032 pos = (POINT *)lParam;
4033 flags = TPM_CENTERALIGN;
4034 if (button_state & LMOUSE)
4035 flags |= TPM_LEFTBUTTON;
4036 else if (button_state & RMOUSE)
4037 flags |= TPM_RIGHTBUTTON;
4039 /* Remember we did a SetCapture on the initial mouse down event,
4040 so for safety, we make sure the capture is canceled now. */
4041 ReleaseCapture ();
4042 button_state = 0;
4044 /* Use menubar_active to indicate that WM_INITMENU is from
4045 TrackPopupMenu below, and should be ignored. */
4046 f = x_window_to_frame (dpyinfo, hwnd);
4047 if (f)
4048 f->output_data.w32->menubar_active = 1;
4050 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4051 0, hwnd, NULL))
4053 MSG amsg;
4054 /* Eat any mouse messages during popupmenu */
4055 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4056 PM_REMOVE));
4057 /* Get the menu selection, if any */
4058 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4060 retval = LOWORD (amsg.wParam);
4062 else
4064 retval = 0;
4067 else
4069 retval = -1;
4072 return retval;
4074 case WM_EMACS_FILENOTIFY:
4075 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4076 return 1;
4078 default:
4079 /* Check for messages registered at runtime. */
4080 if (msg == msh_mousewheel)
4082 wmsg.dwModifiers = w32_get_modifiers ();
4083 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4084 signal_user_input ();
4085 return 0;
4088 dflt:
4089 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4092 /* The most common default return code for handled messages is 0. */
4093 return 0;
4096 static void
4097 my_create_window (struct frame * f)
4099 MSG msg;
4100 static int coords[2];
4101 Lisp_Object left, top;
4102 struct w32_display_info *dpyinfo = &one_w32_display_info;
4104 /* When called with RES_TYPE_NUMBER, x_get_arg will return zero for
4105 anything that is not a number and is not Qunbound. */
4106 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
4107 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
4108 if (EQ (left, Qunbound))
4109 coords[0] = CW_USEDEFAULT;
4110 else
4111 coords[0] = XINT (left);
4112 if (EQ (top, Qunbound))
4113 coords[1] = CW_USEDEFAULT;
4114 else
4115 coords[1] = XINT (top);
4117 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW,
4118 (WPARAM)f, (LPARAM)coords))
4119 emacs_abort ();
4120 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4124 /* Create a tooltip window. Unlike my_create_window, we do not do this
4125 indirectly via the Window thread, as we do not need to process Window
4126 messages for the tooltip. Creating tooltips indirectly also creates
4127 deadlocks when tooltips are created for menu items. */
4128 static void
4129 my_create_tip_window (struct frame *f)
4131 RECT rect;
4133 rect.left = rect.top = 0;
4134 rect.right = FRAME_PIXEL_WIDTH (f);
4135 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4137 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4138 FRAME_EXTERNAL_MENU_BAR (f));
4140 tip_window = FRAME_W32_WINDOW (f)
4141 = CreateWindow (EMACS_CLASS,
4142 f->namebuf,
4143 f->output_data.w32->dwStyle,
4144 f->left_pos,
4145 f->top_pos,
4146 rect.right - rect.left,
4147 rect.bottom - rect.top,
4148 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4149 NULL,
4150 hinst,
4151 NULL);
4153 if (tip_window)
4155 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4156 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4157 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4158 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4160 /* Tip frames have no scrollbars. */
4161 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
4163 /* Do this to discard the default setting specified by our parent. */
4164 ShowWindow (tip_window, SW_HIDE);
4169 /* Create and set up the w32 window for frame F. */
4171 static void
4172 w32_window (struct frame *f, long window_prompting, int minibuffer_only)
4174 block_input ();
4176 /* Use the resource name as the top-level window name
4177 for looking up resources. Make a non-Lisp copy
4178 for the window manager, so GC relocation won't bother it.
4180 Elsewhere we specify the window name for the window manager. */
4181 f->namebuf = xstrdup (SSDATA (Vx_resource_name));
4183 my_create_window (f);
4185 validate_x_resource_name ();
4187 /* x_set_name normally ignores requests to set the name if the
4188 requested name is the same as the current name. This is the one
4189 place where that assumption isn't correct; f->name is set, but
4190 the server hasn't been told. */
4192 Lisp_Object name;
4193 int explicit = f->explicit_name;
4195 f->explicit_name = 0;
4196 name = f->name;
4197 fset_name (f, Qnil);
4198 x_set_name (f, name, explicit);
4201 unblock_input ();
4203 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4204 initialize_frame_menubar (f);
4206 if (FRAME_W32_WINDOW (f) == 0)
4207 error ("Unable to create window");
4210 /* Handle the icon stuff for this window. Perhaps later we might
4211 want an x_set_icon_position which can be called interactively as
4212 well. */
4214 static void
4215 x_icon (struct frame *f, Lisp_Object parms)
4217 Lisp_Object icon_x, icon_y;
4218 struct w32_display_info *dpyinfo = &one_w32_display_info;
4220 /* Set the position of the icon. Note that Windows 95 groups all
4221 icons in the tray. */
4222 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4223 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4224 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4226 CHECK_NUMBER (icon_x);
4227 CHECK_NUMBER (icon_y);
4229 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4230 error ("Both left and top icon corners of icon must be specified");
4232 block_input ();
4234 #if 0 /* TODO */
4235 /* Start up iconic or window? */
4236 x_wm_set_window_state
4237 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4238 ? IconicState
4239 : NormalState));
4241 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4242 ? f->icon_name
4243 : f->name)));
4244 #endif
4246 unblock_input ();
4250 static void
4251 x_make_gc (struct frame *f)
4253 XGCValues gc_values;
4255 block_input ();
4257 /* Create the GC's of this frame.
4258 Note that many default values are used. */
4260 /* Normal video */
4261 gc_values.font = FRAME_FONT (f);
4263 /* Cursor has cursor-color background, background-color foreground. */
4264 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4265 gc_values.background = f->output_data.w32->cursor_pixel;
4266 f->output_data.w32->cursor_gc
4267 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4268 (GCFont | GCForeground | GCBackground),
4269 &gc_values);
4271 /* Reliefs. */
4272 f->output_data.w32->white_relief.gc = 0;
4273 f->output_data.w32->black_relief.gc = 0;
4275 unblock_input ();
4279 /* Handler for signals raised during x_create_frame and
4280 x_create_tip_frame. FRAME is the frame which is partially
4281 constructed. */
4283 static Lisp_Object
4284 unwind_create_frame (Lisp_Object frame)
4286 struct frame *f = XFRAME (frame);
4288 /* If frame is ``official'', nothing to do. */
4289 if (NILP (Fmemq (frame, Vframe_list)))
4291 #ifdef GLYPH_DEBUG
4292 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4294 /* If the frame's image cache refcount is still the same as our
4295 private shadow variable, it means we are unwinding a frame
4296 for which we didn't yet call init_frame_faces, where the
4297 refcount is incremented. Therefore, we increment it here, so
4298 that free_frame_faces, called in x_free_frame_resources
4299 below, will not mistakenly decrement the counter that was not
4300 incremented yet to account for this new frame. */
4301 if (FRAME_IMAGE_CACHE (f) != NULL
4302 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
4303 FRAME_IMAGE_CACHE (f)->refcount++;
4304 #endif
4306 x_free_frame_resources (f);
4307 free_glyphs (f);
4309 #ifdef GLYPH_DEBUG
4310 /* Check that reference counts are indeed correct. */
4311 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4312 eassert ((dpyinfo->terminal->image_cache == NULL
4313 && image_cache_refcount == 0)
4314 || (dpyinfo->terminal->image_cache != NULL
4315 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
4316 #endif
4317 return Qt;
4320 return Qnil;
4323 static void
4324 do_unwind_create_frame (Lisp_Object frame)
4326 unwind_create_frame (frame);
4329 static void
4330 unwind_create_frame_1 (Lisp_Object val)
4332 inhibit_lisp_code = val;
4335 static void
4336 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4338 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4339 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4340 RES_TYPE_STRING);
4341 Lisp_Object font;
4342 if (EQ (font_param, Qunbound))
4343 font_param = Qnil;
4344 font = !NILP (font_param) ? font_param
4345 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4347 if (!STRINGP (font))
4349 int i;
4350 static char *names[]
4351 = { "Courier New-10",
4352 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4353 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4354 "Fixedsys",
4355 NULL };
4357 for (i = 0; names[i]; i++)
4359 font = font_open_by_name (f, build_unibyte_string (names[i]));
4360 if (! NILP (font))
4361 break;
4363 if (NILP (font))
4364 error ("No suitable font was found");
4366 else if (!NILP (font_param))
4368 /* Remember the explicit font parameter, so we can re-apply it after
4369 we've applied the `default' face settings. */
4370 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4372 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4375 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4376 1, 1, 0,
4377 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4378 Return an Emacs frame object.
4379 PARAMETERS is an alist of frame parameters.
4380 If the parameters specify that the frame should not have a minibuffer,
4381 and do not specify a specific minibuffer window to use,
4382 then `default-minibuffer-frame' must be a frame whose minibuffer can
4383 be shared by the new frame.
4385 This function is an internal primitive--use `make-frame' instead. */)
4386 (Lisp_Object parameters)
4388 struct frame *f;
4389 Lisp_Object frame, tem;
4390 Lisp_Object name;
4391 int minibuffer_only = 0;
4392 long window_prompting = 0;
4393 int width, height;
4394 ptrdiff_t count = SPECPDL_INDEX ();
4395 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4396 Lisp_Object display;
4397 struct w32_display_info *dpyinfo = NULL;
4398 Lisp_Object parent;
4399 struct kboard *kb;
4401 if (!FRAME_W32_P (SELECTED_FRAME ())
4402 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4403 error ("Cannot create a GUI frame in a -nw session");
4405 /* Make copy of frame parameters because the original is in pure
4406 storage now. */
4407 parameters = Fcopy_alist (parameters);
4409 /* Use this general default value to start with
4410 until we know if this frame has a specified name. */
4411 Vx_resource_name = Vinvocation_name;
4413 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4414 if (EQ (display, Qunbound))
4415 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4416 if (EQ (display, Qunbound))
4417 display = Qnil;
4418 dpyinfo = check_x_display_info (display);
4419 kb = dpyinfo->terminal->kboard;
4421 if (!dpyinfo->terminal->name)
4422 error ("Terminal is not live, can't create new frames on it");
4424 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4425 if (!STRINGP (name)
4426 && ! EQ (name, Qunbound)
4427 && ! NILP (name))
4428 error ("Invalid frame name--not a string or nil");
4430 if (STRINGP (name))
4431 Vx_resource_name = name;
4433 /* See if parent window is specified. */
4434 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4435 if (EQ (parent, Qunbound))
4436 parent = Qnil;
4437 if (! NILP (parent))
4438 CHECK_NUMBER (parent);
4440 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4441 /* No need to protect DISPLAY because that's not used after passing
4442 it to make_frame_without_minibuffer. */
4443 frame = Qnil;
4444 GCPRO4 (parameters, parent, name, frame);
4445 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
4446 RES_TYPE_SYMBOL);
4447 if (EQ (tem, Qnone) || NILP (tem))
4448 f = make_frame_without_minibuffer (Qnil, kb, display);
4449 else if (EQ (tem, Qonly))
4451 f = make_minibuffer_frame ();
4452 minibuffer_only = 1;
4454 else if (WINDOWP (tem))
4455 f = make_frame_without_minibuffer (tem, kb, display);
4456 else
4457 f = make_frame (1);
4459 XSETFRAME (frame, f);
4461 /* By default, make scrollbars the system standard width. */
4462 x_set_scroll_bar_default_width (f);
4464 f->terminal = dpyinfo->terminal;
4466 f->output_method = output_w32;
4467 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
4468 FRAME_FONTSET (f) = -1;
4470 fset_icon_name
4471 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
4472 RES_TYPE_STRING));
4473 if (! STRINGP (f->icon_name))
4474 fset_icon_name (f, Qnil);
4476 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
4478 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
4479 record_unwind_protect (do_unwind_create_frame, frame);
4481 #ifdef GLYPH_DEBUG
4482 image_cache_refcount =
4483 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
4484 dpyinfo_refcount = dpyinfo->reference_count;
4485 #endif /* GLYPH_DEBUG */
4487 /* Specify the parent under which to make this window. */
4489 if (!NILP (parent))
4491 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4492 f->output_data.w32->explicit_parent = 1;
4494 else
4496 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4497 f->output_data.w32->explicit_parent = 0;
4500 /* Set the name; the functions to which we pass f expect the name to
4501 be set. */
4502 if (EQ (name, Qunbound) || NILP (name))
4504 fset_name (f, build_string (dpyinfo->w32_id_name));
4505 f->explicit_name = 0;
4507 else
4509 fset_name (f, name);
4510 f->explicit_name = 1;
4511 /* use the frame's title when getting resources for this frame. */
4512 specbind (Qx_resource_name, name);
4515 if (uniscribe_available)
4516 register_font_driver (&uniscribe_font_driver, f);
4517 register_font_driver (&w32font_driver, f);
4519 x_default_parameter (f, parameters, Qfont_backend, Qnil,
4520 "fontBackend", "FontBackend", RES_TYPE_STRING);
4521 /* Extract the window parameters from the supplied values
4522 that are needed to determine window geometry. */
4523 x_default_font_parameter (f, parameters);
4524 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4525 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4527 /* We recognize either internalBorderWidth or internalBorder
4528 (which is what xterm calls it). */
4529 if (NILP (Fassq (Qinternal_border_width, parameters)))
4531 Lisp_Object value;
4533 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
4534 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4535 if (! EQ (value, Qunbound))
4536 parameters = Fcons (Fcons (Qinternal_border_width, value),
4537 parameters);
4539 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4540 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4541 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4542 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
4543 NULL, NULL, RES_TYPE_NUMBER);
4544 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
4545 NULL, NULL, RES_TYPE_NUMBER);
4546 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4547 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4549 /* Also do the stuff which must be set before the window exists. */
4550 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4551 "foreground", "Foreground", RES_TYPE_STRING);
4552 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4553 "background", "Background", RES_TYPE_STRING);
4554 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4555 "pointerColor", "Foreground", RES_TYPE_STRING);
4556 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4557 "borderColor", "BorderColor", RES_TYPE_STRING);
4558 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4559 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4560 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4561 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4562 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4563 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4564 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4565 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4566 /* Process alpha here (Bug#16619). */
4567 x_default_parameter (f, parameters, Qalpha, Qnil,
4568 "alpha", "Alpha", RES_TYPE_NUMBER);
4570 /* Init faces before x_default_parameter is called for scroll-bar
4571 parameters because that function calls x_set_scroll_bar_width,
4572 which calls change_frame_size, which calls Fset_window_buffer,
4573 which runs hooks, which call Fvertical_motion. At the end, we
4574 end up in init_iterator with a null face cache, which should not
4575 happen. */
4576 init_frame_faces (f);
4578 /* Avoid calling window-configuration-change-hook; otherwise we
4579 could get an infloop in next_frame since the frame is not yet in
4580 Vframe_list. */
4582 ptrdiff_t count2 = SPECPDL_INDEX ();
4584 record_unwind_protect (unwind_create_frame_1, inhibit_lisp_code);
4585 inhibit_lisp_code = Qt;
4587 /* PXW: This is a duplicate from below. We have to do it here since
4588 otherwise x_set_tool_bar_lines will work with the character sizes
4589 installed by init_frame_faces while the frame's pixel size is still
4590 calculated from a character size of 1 and we subsequently hit the
4591 eassert (height >= 0) assertion in window_box_height. The
4592 non-pixelwise code apparently worked around this because it had one
4593 frame line vs one toolbar line which left us with a zero root
4594 window height which was obviously wrong as well ... */
4595 change_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
4596 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 1, 0, 0, 1);
4598 /* The X resources controlling the menu-bar and tool-bar are
4599 processed specially at startup, and reflected in the mode
4600 variables; ignore them here. */
4601 x_default_parameter (f, parameters, Qmenu_bar_lines,
4602 NILP (Vmenu_bar_mode)
4603 ? make_number (0) : make_number (1),
4604 NULL, NULL, RES_TYPE_NUMBER);
4605 x_default_parameter (f, parameters, Qtool_bar_lines,
4606 NILP (Vtool_bar_mode)
4607 ? make_number (0) : make_number (1),
4608 NULL, NULL, RES_TYPE_NUMBER);
4610 unbind_to (count2, Qnil);
4613 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4614 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4615 x_default_parameter (f, parameters, Qtitle, Qnil,
4616 "title", "Title", RES_TYPE_STRING);
4617 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4618 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4620 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4621 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4623 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4624 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4625 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4626 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4627 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4628 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4629 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
4631 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
4633 window_prompting = x_figure_window_size (f, parameters, 1);
4635 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4636 f->no_split = minibuffer_only || EQ (tem, Qt);
4638 w32_window (f, window_prompting, minibuffer_only);
4639 x_icon (f, parameters);
4641 x_make_gc (f);
4643 /* Now consider the frame official. */
4644 f->terminal->reference_count++;
4645 FRAME_DISPLAY_INFO (f)->reference_count++;
4646 Vframe_list = Fcons (frame, Vframe_list);
4648 /* We need to do this after creating the window, so that the
4649 icon-creation functions can say whose icon they're describing. */
4650 x_default_parameter (f, parameters, Qicon_type, Qnil,
4651 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4653 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4654 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4655 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4656 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4657 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4658 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4659 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4660 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4662 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4663 Change will not be effected unless different from the current
4664 FRAME_LINES (f). */
4665 width = FRAME_TEXT_WIDTH (f);
4666 height = FRAME_TEXT_HEIGHT (f);
4667 FRAME_TEXT_HEIGHT (f) = 0;
4668 SET_FRAME_WIDTH (f, 0);
4669 change_frame_size (f, width, height, 1, 0, 0, 1);
4671 /* Tell the server what size and position, etc, we want, and how
4672 badly we want them. This should be done after we have the menu
4673 bar so that its size can be taken into account. */
4674 block_input ();
4675 x_wm_set_size_hint (f, window_prompting, 0);
4676 unblock_input ();
4678 /* Make the window appear on the frame and enable display, unless
4679 the caller says not to. However, with explicit parent, Emacs
4680 cannot control visibility, so don't try. */
4681 if (! f->output_data.w32->explicit_parent)
4683 Lisp_Object visibility;
4685 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4686 if (EQ (visibility, Qunbound))
4687 visibility = Qt;
4689 if (EQ (visibility, Qicon))
4690 x_iconify_frame (f);
4691 else if (! NILP (visibility))
4692 x_make_frame_visible (f);
4693 else
4694 /* Must have been Qnil. */
4698 /* Initialize `default-minibuffer-frame' in case this is the first
4699 frame on this terminal. */
4700 if (FRAME_HAS_MINIBUF_P (f)
4701 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
4702 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
4703 kset_default_minibuffer_frame (kb, frame);
4705 /* All remaining specified parameters, which have not been "used"
4706 by x_get_arg and friends, now go in the misc. alist of the frame. */
4707 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4708 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4709 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
4711 UNGCPRO;
4713 /* Make sure windows on this frame appear in calls to next-window
4714 and similar functions. */
4715 Vwindow_list = Qnil;
4717 return unbind_to (count, frame);
4720 /* FRAME is used only to get a handle on the X display. We don't pass the
4721 display info directly because we're called from frame.c, which doesn't
4722 know about that structure. */
4723 Lisp_Object
4724 x_get_focus_frame (struct frame *frame)
4726 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
4727 Lisp_Object xfocus;
4728 if (! dpyinfo->w32_focus_frame)
4729 return Qnil;
4731 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4732 return xfocus;
4735 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4736 doc: /* Internal function called by `color-defined-p', which see.
4737 \(Note that the Nextstep version of this function ignores FRAME.) */)
4738 (Lisp_Object color, Lisp_Object frame)
4740 XColor foo;
4741 struct frame *f = decode_window_system_frame (frame);
4743 CHECK_STRING (color);
4745 if (w32_defined_color (f, SDATA (color), &foo, 0))
4746 return Qt;
4747 else
4748 return Qnil;
4751 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
4752 doc: /* Internal function called by `color-values', which see. */)
4753 (Lisp_Object color, Lisp_Object frame)
4755 XColor foo;
4756 struct frame *f = decode_window_system_frame (frame);
4758 CHECK_STRING (color);
4760 if (w32_defined_color (f, SDATA (color), &foo, 0))
4761 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4762 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4763 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
4764 else
4765 return Qnil;
4768 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
4769 doc: /* Internal function called by `display-color-p', which see. */)
4770 (Lisp_Object display)
4772 struct w32_display_info *dpyinfo = check_x_display_info (display);
4774 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4775 return Qnil;
4777 return Qt;
4780 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4781 Sx_display_grayscale_p, 0, 1, 0,
4782 doc: /* Return t if DISPLAY supports shades of gray.
4783 Note that color displays do support shades of gray.
4784 The optional argument DISPLAY specifies which display to ask about.
4785 DISPLAY should be either a frame or a display name (a string).
4786 If omitted or nil, that stands for the selected frame's display. */)
4787 (Lisp_Object display)
4789 struct w32_display_info *dpyinfo = check_x_display_info (display);
4791 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4792 return Qnil;
4794 return Qt;
4797 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4798 Sx_display_pixel_width, 0, 1, 0,
4799 doc: /* Return the width in pixels of DISPLAY.
4800 The optional argument DISPLAY specifies which display to ask about.
4801 DISPLAY should be either a frame or a display name (a string).
4802 If omitted or nil, that stands for the selected frame's display.
4804 On \"multi-monitor\" setups this refers to the pixel width for all
4805 physical monitors associated with DISPLAY. To get information for
4806 each physical monitor, use `display-monitor-attributes-list'. */)
4807 (Lisp_Object display)
4809 struct w32_display_info *dpyinfo = check_x_display_info (display);
4811 return make_number (x_display_pixel_width (dpyinfo));
4814 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
4815 Sx_display_pixel_height, 0, 1, 0,
4816 doc: /* Return the height in pixels of DISPLAY.
4817 The optional argument DISPLAY specifies which display to ask about.
4818 DISPLAY should be either a frame or a display name (a string).
4819 If omitted or nil, that stands for the selected frame's display.
4821 On \"multi-monitor\" setups this refers to the pixel height for all
4822 physical monitors associated with DISPLAY. To get information for
4823 each physical monitor, use `display-monitor-attributes-list'. */)
4824 (Lisp_Object display)
4826 struct w32_display_info *dpyinfo = check_x_display_info (display);
4828 return make_number (x_display_pixel_height (dpyinfo));
4831 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
4832 0, 1, 0,
4833 doc: /* Return the number of bitplanes of DISPLAY.
4834 The optional argument DISPLAY specifies which display to ask about.
4835 DISPLAY should be either a frame or a display name (a string).
4836 If omitted or nil, that stands for the selected frame's display. */)
4837 (Lisp_Object display)
4839 struct w32_display_info *dpyinfo = check_x_display_info (display);
4841 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4844 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
4845 0, 1, 0,
4846 doc: /* Return the number of color cells of DISPLAY.
4847 The optional argument DISPLAY specifies which display to ask about.
4848 DISPLAY should be either a frame or a display name (a string).
4849 If omitted or nil, that stands for the selected frame's display. */)
4850 (Lisp_Object display)
4852 struct w32_display_info *dpyinfo = check_x_display_info (display);
4853 int cap;
4855 /* Don't use NCOLORS: it returns incorrect results under remote
4856 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4857 * overflow and because probably is more meaningful on Windows
4858 * anyway. */
4860 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
4861 return make_number (cap);
4864 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4865 Sx_server_max_request_size,
4866 0, 1, 0,
4867 doc: /* Return the maximum request size of the server of DISPLAY.
4868 The optional argument DISPLAY specifies which display to ask about.
4869 DISPLAY should be either a frame or a display name (a string).
4870 If omitted or nil, that stands for the selected frame's display. */)
4871 (Lisp_Object display)
4873 return make_number (1);
4876 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
4877 doc: /* Return the "vendor ID" string of the GUI software on TERMINAL.
4879 \(Labeling every distributor as a "vendor" embodies the false assumption
4880 that operating systems cannot be developed and distributed noncommercially.)
4882 For GNU and Unix systems, this queries the X server software; for
4883 MS-Windows, this queries the OS.
4885 The optional argument TERMINAL specifies which display to ask about.
4886 TERMINAL should be a terminal object, a frame or a display name (a string).
4887 If omitted or nil, that stands for the selected frame's display. */)
4888 (Lisp_Object terminal)
4890 return build_string ("Microsoft Corp.");
4893 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
4894 doc: /* Return the version numbers of the GUI software on TERMINAL.
4895 The value is a list of three integers specifying the version of the GUI
4896 software in use.
4898 For GNU and Unix system, the first 2 numbers are the version of the X
4899 Protocol used on TERMINAL and the 3rd number is the distributor-specific
4900 release number. For MS-Windows, the 3 numbers report the version and
4901 the build number of the OS.
4903 See also the function `x-server-vendor'.
4905 The optional argument TERMINAL specifies which display to ask about.
4906 TERMINAL should be a terminal object, a frame or a display name (a string).
4907 If omitted or nil, that stands for the selected frame's display. */)
4908 (Lisp_Object terminal)
4910 return list3i (w32_major_version, w32_minor_version, w32_build_number);
4913 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
4914 doc: /* Return the number of screens on the server of DISPLAY.
4915 The optional argument DISPLAY specifies which display to ask about.
4916 DISPLAY should be either a frame or a display name (a string).
4917 If omitted or nil, that stands for the selected frame's display. */)
4918 (Lisp_Object display)
4920 return make_number (1);
4923 DEFUN ("x-display-mm-height", Fx_display_mm_height,
4924 Sx_display_mm_height, 0, 1, 0,
4925 doc: /* Return the height in millimeters of DISPLAY.
4926 The optional argument DISPLAY specifies which display to ask about.
4927 DISPLAY should be either a frame or a display name (a string).
4928 If omitted or nil, that stands for the selected frame's display.
4930 On \"multi-monitor\" setups this refers to the height in millimeters for
4931 all physical monitors associated with DISPLAY. To get information
4932 for each physical monitor, use `display-monitor-attributes-list'. */)
4933 (Lisp_Object display)
4935 struct w32_display_info *dpyinfo = check_x_display_info (display);
4936 HDC hdc;
4937 double mm_per_pixel;
4939 hdc = GetDC (NULL);
4940 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
4941 / GetDeviceCaps (hdc, VERTRES));
4942 ReleaseDC (NULL, hdc);
4944 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
4947 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
4948 doc: /* Return the width in millimeters of DISPLAY.
4949 The optional argument DISPLAY specifies which display to ask about.
4950 DISPLAY should be either a frame or a display name (a string).
4951 If omitted or nil, that stands for the selected frame's display.
4953 On \"multi-monitor\" setups this refers to the width in millimeters for
4954 all physical monitors associated with TERMINAL. To get information
4955 for each physical monitor, use `display-monitor-attributes-list'. */)
4956 (Lisp_Object display)
4958 struct w32_display_info *dpyinfo = check_x_display_info (display);
4959 HDC hdc;
4960 double mm_per_pixel;
4962 hdc = GetDC (NULL);
4963 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
4964 / GetDeviceCaps (hdc, HORZRES));
4965 ReleaseDC (NULL, hdc);
4967 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
4970 DEFUN ("x-display-backing-store", Fx_display_backing_store,
4971 Sx_display_backing_store, 0, 1, 0,
4972 doc: /* Return an indication of whether DISPLAY does backing store.
4973 The value may be `always', `when-mapped', or `not-useful'.
4974 The optional argument DISPLAY specifies which display to ask about.
4975 DISPLAY should be either a frame or a display name (a string).
4976 If omitted or nil, that stands for the selected frame's display. */)
4977 (Lisp_Object display)
4979 return intern ("not-useful");
4982 DEFUN ("x-display-visual-class", Fx_display_visual_class,
4983 Sx_display_visual_class, 0, 1, 0,
4984 doc: /* Return the visual class of DISPLAY.
4985 The value is one of the symbols `static-gray', `gray-scale',
4986 `static-color', `pseudo-color', `true-color', or `direct-color'.
4988 The optional argument DISPLAY specifies which display to ask about.
4989 DISPLAY should be either a frame or a display name (a string).
4990 If omitted or nil, that stands for the selected frame's display. */)
4991 (Lisp_Object display)
4993 struct w32_display_info *dpyinfo = check_x_display_info (display);
4994 Lisp_Object result = Qnil;
4996 if (dpyinfo->has_palette)
4997 result = intern ("pseudo-color");
4998 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
4999 result = intern ("static-grey");
5000 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
5001 result = intern ("static-color");
5002 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
5003 result = intern ("true-color");
5005 return result;
5008 DEFUN ("x-display-save-under", Fx_display_save_under,
5009 Sx_display_save_under, 0, 1, 0,
5010 doc: /* Return t if DISPLAY supports the save-under feature.
5011 The optional argument DISPLAY specifies which display to ask about.
5012 DISPLAY should be either a frame or a display name (a string).
5013 If omitted or nil, that stands for the selected frame's display. */)
5014 (Lisp_Object display)
5016 return Qnil;
5019 static BOOL CALLBACK
5020 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
5022 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
5024 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
5026 return TRUE;
5029 static Lisp_Object
5030 w32_display_monitor_attributes_list (void)
5032 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
5033 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
5034 int i, n_monitors;
5035 HMONITOR *monitors;
5036 struct gcpro gcpro1, gcpro2, gcpro3;
5038 if (!(enum_display_monitors_fn && get_monitor_info_fn
5039 && monitor_from_window_fn))
5040 return Qnil;
5042 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
5043 (LPARAM) &monitor_list)
5044 || NILP (monitor_list))
5045 return Qnil;
5047 n_monitors = 0;
5048 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
5049 n_monitors++;
5051 monitors = xmalloc (n_monitors * sizeof (*monitors));
5052 for (i = 0; i < n_monitors; i++)
5054 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
5055 monitor_list = XCDR (monitor_list);
5058 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
5059 FOR_EACH_FRAME (rest, frame)
5061 struct frame *f = XFRAME (frame);
5063 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5065 HMONITOR monitor =
5066 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5067 MONITOR_DEFAULT_TO_NEAREST);
5069 for (i = 0; i < n_monitors; i++)
5070 if (monitors[i] == monitor)
5071 break;
5073 if (i < n_monitors)
5074 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5078 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5080 for (i = 0; i < n_monitors; i++)
5082 Lisp_Object geometry, workarea, name, attributes = Qnil;
5083 HDC hdc;
5084 int width_mm, height_mm;
5085 struct MONITOR_INFO_EX mi;
5087 mi.cbSize = sizeof (mi);
5088 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5089 continue;
5091 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5092 if (hdc == NULL)
5093 continue;
5094 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5095 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5096 DeleteDC (hdc);
5098 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5099 attributes);
5101 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5103 attributes = Fcons (Fcons (Qname, name), attributes);
5105 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5106 attributes);
5108 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5109 mi.rcWork.right - mi.rcWork.left,
5110 mi.rcWork.bottom - mi.rcWork.top);
5111 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5113 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5114 mi.rcMonitor.right - mi.rcMonitor.left,
5115 mi.rcMonitor.bottom - mi.rcMonitor.top);
5116 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5118 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5119 primary_monitor_attributes = attributes;
5120 else
5121 attributes_list = Fcons (attributes, attributes_list);
5124 if (!NILP (primary_monitor_attributes))
5125 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5127 UNGCPRO;
5129 xfree (monitors);
5131 return attributes_list;
5134 static Lisp_Object
5135 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5137 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5138 HDC hdc;
5139 double mm_per_pixel;
5140 int pixel_width, pixel_height, width_mm, height_mm;
5141 RECT workarea_rect;
5143 /* Fallback: treat (possibly) multiple physical monitors as if they
5144 formed a single monitor as a whole. This should provide a
5145 consistent result at least on single monitor environments. */
5146 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5147 attributes);
5149 frames = Qnil;
5150 FOR_EACH_FRAME (rest, frame)
5152 struct frame *f = XFRAME (frame);
5154 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5155 frames = Fcons (frame, frames);
5157 attributes = Fcons (Fcons (Qframes, frames), attributes);
5159 pixel_width = x_display_pixel_width (dpyinfo);
5160 pixel_height = x_display_pixel_height (dpyinfo);
5162 hdc = GetDC (NULL);
5163 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5164 / GetDeviceCaps (hdc, HORZRES));
5165 width_mm = pixel_width * mm_per_pixel + 0.5;
5166 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5167 / GetDeviceCaps (hdc, VERTRES));
5168 height_mm = pixel_height * mm_per_pixel + 0.5;
5169 ReleaseDC (NULL, hdc);
5170 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5171 attributes);
5173 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5174 we don't care. */
5175 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5176 GetSystemMetrics (SM_YVIRTUALSCREEN),
5177 pixel_width, pixel_height);
5178 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5179 workarea = list4i (workarea_rect.left, workarea_rect.top,
5180 workarea_rect.right - workarea_rect.left,
5181 workarea_rect.bottom - workarea_rect.top);
5182 else
5183 workarea = geometry;
5184 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5186 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5188 return list1 (attributes);
5191 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5192 Sw32_display_monitor_attributes_list,
5193 0, 1, 0,
5194 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5196 The optional argument DISPLAY specifies which display to ask about.
5197 DISPLAY should be either a frame or a display name (a string).
5198 If omitted or nil, that stands for the selected frame's display.
5200 Internal use only, use `display-monitor-attributes-list' instead. */)
5201 (Lisp_Object display)
5203 struct w32_display_info *dpyinfo = check_x_display_info (display);
5204 Lisp_Object attributes_list;
5206 block_input ();
5207 attributes_list = w32_display_monitor_attributes_list ();
5208 if (NILP (attributes_list))
5209 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5210 unblock_input ();
5212 return attributes_list;
5215 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5216 doc: /* Set the sound generated when the bell is rung.
5217 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5218 to use the corresponding system sound for the bell. The 'silent sound
5219 prevents Emacs from making any sound at all.
5220 SOUND is nil to use the normal beep. */)
5221 (Lisp_Object sound)
5223 CHECK_SYMBOL (sound);
5225 if (NILP (sound))
5226 sound_type = 0xFFFFFFFF;
5227 else if (EQ (sound, intern ("asterisk")))
5228 sound_type = MB_ICONASTERISK;
5229 else if (EQ (sound, intern ("exclamation")))
5230 sound_type = MB_ICONEXCLAMATION;
5231 else if (EQ (sound, intern ("hand")))
5232 sound_type = MB_ICONHAND;
5233 else if (EQ (sound, intern ("question")))
5234 sound_type = MB_ICONQUESTION;
5235 else if (EQ (sound, intern ("ok")))
5236 sound_type = MB_OK;
5237 else if (EQ (sound, intern ("silent")))
5238 sound_type = MB_EMACS_SILENT;
5239 else
5240 sound_type = 0xFFFFFFFF;
5242 return sound;
5246 x_screen_planes (register struct frame *f)
5248 return FRAME_DISPLAY_INFO (f)->n_planes;
5251 /* Return the display structure for the display named NAME.
5252 Open a new connection if necessary. */
5254 struct w32_display_info *
5255 x_display_info_for_name (Lisp_Object name)
5257 struct w32_display_info *dpyinfo;
5259 CHECK_STRING (name);
5261 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5262 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5263 return dpyinfo;
5265 /* Use this general default value to start with. */
5266 Vx_resource_name = Vinvocation_name;
5268 validate_x_resource_name ();
5270 dpyinfo = w32_term_init (name, (unsigned char *)0,
5271 SSDATA (Vx_resource_name));
5273 if (dpyinfo == 0)
5274 error ("Cannot connect to server %s", SDATA (name));
5276 XSETFASTINT (Vwindow_system_version, w32_major_version);
5278 return dpyinfo;
5281 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5282 1, 3, 0, doc: /* Open a connection to a display server.
5283 DISPLAY is the name of the display to connect to.
5284 Optional second arg XRM-STRING is a string of resources in xrdb format.
5285 If the optional third arg MUST-SUCCEED is non-nil,
5286 terminate Emacs if we can't open the connection.
5287 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5288 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5290 unsigned char *xrm_option;
5291 struct w32_display_info *dpyinfo;
5293 CHECK_STRING (display);
5295 /* Signal an error in order to encourage correct use from callers.
5296 * If we ever support multiple window systems in the same Emacs,
5297 * we'll need callers to be precise about what window system they
5298 * want. */
5300 if (strcmp (SSDATA (display), "w32") != 0)
5301 error ("The name of the display in this Emacs must be \"w32\"");
5303 /* If initialization has already been done, return now to avoid
5304 overwriting critical parts of one_w32_display_info. */
5305 if (window_system_available (NULL))
5306 return Qnil;
5308 if (! NILP (xrm_string))
5309 CHECK_STRING (xrm_string);
5311 /* Allow color mapping to be defined externally; first look in user's
5312 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5314 Lisp_Object color_file;
5315 struct gcpro gcpro1;
5317 color_file = build_string ("~/rgb.txt");
5319 GCPRO1 (color_file);
5321 if (NILP (Ffile_readable_p (color_file)))
5322 color_file =
5323 Fexpand_file_name (build_string ("rgb.txt"),
5324 Fsymbol_value (intern ("data-directory")));
5326 Vw32_color_map = Fx_load_color_file (color_file);
5328 UNGCPRO;
5330 if (NILP (Vw32_color_map))
5331 Vw32_color_map = w32_default_color_map ();
5333 /* Merge in system logical colors. */
5334 add_system_logical_colors_to_map (&Vw32_color_map);
5336 if (! NILP (xrm_string))
5337 xrm_option = SDATA (xrm_string);
5338 else
5339 xrm_option = (unsigned char *) 0;
5341 /* Use this general default value to start with. */
5342 /* First remove .exe suffix from invocation-name - it looks ugly. */
5344 char basename[ MAX_PATH ], *str;
5346 strcpy (basename, SDATA (Vinvocation_name));
5347 str = strrchr (basename, '.');
5348 if (str) *str = 0;
5349 Vinvocation_name = build_string (basename);
5351 Vx_resource_name = Vinvocation_name;
5353 validate_x_resource_name ();
5355 /* This is what opens the connection and sets x_current_display.
5356 This also initializes many symbols, such as those used for input. */
5357 dpyinfo = w32_term_init (display, xrm_option,
5358 SSDATA (Vx_resource_name));
5360 if (dpyinfo == 0)
5362 if (!NILP (must_succeed))
5363 fatal ("Cannot connect to server %s.\n",
5364 SDATA (display));
5365 else
5366 error ("Cannot connect to server %s", SDATA (display));
5369 XSETFASTINT (Vwindow_system_version, w32_major_version);
5370 return Qnil;
5373 DEFUN ("x-close-connection", Fx_close_connection,
5374 Sx_close_connection, 1, 1, 0,
5375 doc: /* Close the connection to DISPLAY's server.
5376 For DISPLAY, specify either a frame or a display name (a string).
5377 If DISPLAY is nil, that stands for the selected frame's display. */)
5378 (Lisp_Object display)
5380 struct w32_display_info *dpyinfo = check_x_display_info (display);
5382 if (dpyinfo->reference_count > 0)
5383 error ("Display still has frames on it");
5385 block_input ();
5386 x_destroy_all_bitmaps (dpyinfo);
5388 x_delete_display (dpyinfo);
5389 unblock_input ();
5391 return Qnil;
5394 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5395 doc: /* Return the list of display names that Emacs has connections to. */)
5396 (void)
5398 Lisp_Object result = Qnil;
5399 struct w32_display_info *wdi;
5401 for (wdi = x_display_list; wdi; wdi = wdi->next)
5402 result = Fcons (XCAR (wdi->name_list_element), result);
5404 return result;
5407 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5408 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5409 This function only has an effect on X Windows. With MS Windows, it is
5410 defined but does nothing.
5412 If ON is nil, allow buffering of requests.
5413 Turning on synchronization prohibits the Xlib routines from buffering
5414 requests and seriously degrades performance, but makes debugging much
5415 easier.
5416 The optional second argument TERMINAL specifies which display to act on.
5417 TERMINAL should be a terminal object, a frame or a display name (a string).
5418 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5419 (Lisp_Object on, Lisp_Object display)
5421 return Qnil;
5426 /***********************************************************************
5427 Window properties
5428 ***********************************************************************/
5430 #if 0 /* TODO : port window properties to W32 */
5432 DEFUN ("x-change-window-property", Fx_change_window_property,
5433 Sx_change_window_property, 2, 6, 0,
5434 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5435 PROP must be a string. VALUE may be a string or a list of conses,
5436 numbers and/or strings. If an element in the list is a string, it is
5437 converted to an atom and the value of the Atom is used. If an element
5438 is a cons, it is converted to a 32 bit number where the car is the 16
5439 top bits and the cdr is the lower 16 bits.
5441 FRAME nil or omitted means use the selected frame.
5442 If TYPE is given and non-nil, it is the name of the type of VALUE.
5443 If TYPE is not given or nil, the type is STRING.
5444 FORMAT gives the size in bits of each element if VALUE is a list.
5445 It must be one of 8, 16 or 32.
5446 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
5447 If OUTER-P is non-nil, the property is changed for the outer X window of
5448 FRAME. Default is to change on the edit X window. */)
5449 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5450 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
5452 struct frame *f = decode_window_system_frame (frame);
5453 Atom prop_atom;
5455 CHECK_STRING (prop);
5456 CHECK_STRING (value);
5458 block_input ();
5459 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5460 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5461 prop_atom, XA_STRING, 8, PropModeReplace,
5462 SDATA (value), SCHARS (value));
5464 /* Make sure the property is set when we return. */
5465 XFlush (FRAME_W32_DISPLAY (f));
5466 unblock_input ();
5468 return value;
5472 DEFUN ("x-delete-window-property", Fx_delete_window_property,
5473 Sx_delete_window_property, 1, 2, 0,
5474 doc: /* Remove window property PROP from X window of FRAME.
5475 FRAME nil or omitted means use the selected frame. Value is PROP. */)
5476 (Lisp_Object prop, Lisp_Object frame)
5478 struct frame *f = decode_window_system_frame (frame);
5479 Atom prop_atom;
5481 CHECK_STRING (prop);
5482 block_input ();
5483 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5484 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
5486 /* Make sure the property is removed when we return. */
5487 XFlush (FRAME_W32_DISPLAY (f));
5488 unblock_input ();
5490 return prop;
5494 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
5495 1, 6, 0,
5496 doc: /* Value is the value of window property PROP on FRAME.
5497 If FRAME is nil or omitted, use the selected frame.
5499 On X Windows, the following optional arguments are also accepted:
5500 If TYPE is nil or omitted, get the property as a string.
5501 Otherwise TYPE is the name of the atom that denotes the type expected.
5502 If SOURCE is non-nil, get the property on that window instead of from
5503 FRAME. The number 0 denotes the root window.
5504 If DELETE-P is non-nil, delete the property after retrieving it.
5505 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5507 On MS Windows, this function accepts but ignores those optional arguments.
5509 Value is nil if FRAME hasn't a property with name PROP or if PROP has
5510 no value of TYPE (always string in the MS Windows case). */)
5511 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5512 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
5514 struct frame *f = decode_window_system_frame (frame);
5515 Atom prop_atom;
5516 int rc;
5517 Lisp_Object prop_value = Qnil;
5518 char *tmp_data = NULL;
5519 Atom actual_type;
5520 int actual_format;
5521 unsigned long actual_size, bytes_remaining;
5523 CHECK_STRING (prop);
5524 block_input ();
5525 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5526 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5527 prop_atom, 0, 0, False, XA_STRING,
5528 &actual_type, &actual_format, &actual_size,
5529 &bytes_remaining, (unsigned char **) &tmp_data);
5530 if (rc == Success)
5532 int size = bytes_remaining;
5534 XFree (tmp_data);
5535 tmp_data = NULL;
5537 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5538 prop_atom, 0, bytes_remaining,
5539 False, XA_STRING,
5540 &actual_type, &actual_format,
5541 &actual_size, &bytes_remaining,
5542 (unsigned char **) &tmp_data);
5543 if (rc == Success)
5544 prop_value = make_string (tmp_data, size);
5546 XFree (tmp_data);
5549 unblock_input ();
5551 return prop_value;
5553 return Qnil;
5556 #endif /* TODO */
5559 /***********************************************************************
5560 Busy cursor
5561 ***********************************************************************/
5563 void
5564 w32_note_current_window (void)
5566 struct frame * f = SELECTED_FRAME ();
5568 if (!FRAME_W32_P (f))
5569 return;
5571 hourglass_hwnd = FRAME_W32_WINDOW (f);
5574 void
5575 show_hourglass (struct atimer *timer)
5577 struct frame *f;
5579 hourglass_atimer = NULL;
5581 block_input ();
5582 f = x_window_to_frame (&one_w32_display_info,
5583 hourglass_hwnd);
5585 if (f)
5586 f->output_data.w32->hourglass_p = 0;
5587 else
5588 f = SELECTED_FRAME ();
5590 if (!FRAME_W32_P (f))
5592 unblock_input ();
5593 return;
5596 w32_show_hourglass (f);
5597 unblock_input ();
5600 void
5601 hide_hourglass (void)
5603 block_input ();
5604 w32_hide_hourglass ();
5605 unblock_input ();
5609 /* Display an hourglass cursor. Set the hourglass_p flag in display info
5610 to indicate that an hourglass cursor is shown. */
5612 static void
5613 w32_show_hourglass (struct frame *f)
5615 if (!hourglass_shown_p)
5617 f->output_data.w32->hourglass_p = 1;
5618 if (!menubar_in_use && !current_popup_menu)
5619 SetCursor (f->output_data.w32->hourglass_cursor);
5620 hourglass_shown_p = 1;
5625 /* Hide the hourglass cursor on all frames, if it is currently shown. */
5627 static void
5628 w32_hide_hourglass (void)
5630 if (hourglass_shown_p)
5632 struct frame *f = x_window_to_frame (&one_w32_display_info,
5633 hourglass_hwnd);
5634 if (f)
5635 f->output_data.w32->hourglass_p = 0;
5636 else
5637 /* If frame was deleted, restore to selected frame's cursor. */
5638 f = SELECTED_FRAME ();
5640 if (FRAME_W32_P (f))
5641 SetCursor (f->output_data.w32->current_cursor);
5642 else
5643 /* No cursors on non GUI frames - restore to stock arrow cursor. */
5644 SetCursor (w32_load_cursor (IDC_ARROW));
5646 hourglass_shown_p = 0;
5652 /***********************************************************************
5653 Tool tips
5654 ***********************************************************************/
5656 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5657 Lisp_Object, Lisp_Object);
5658 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5659 Lisp_Object, int, int, int *, int *);
5661 /* The frame of a currently visible tooltip. */
5663 Lisp_Object tip_frame;
5665 /* If non-nil, a timer started that hides the last tooltip when it
5666 fires. */
5668 Lisp_Object tip_timer;
5669 Window tip_window;
5671 /* If non-nil, a vector of 3 elements containing the last args
5672 with which x-show-tip was called. See there. */
5674 Lisp_Object last_show_tip_args;
5677 static void
5678 unwind_create_tip_frame (Lisp_Object frame)
5680 Lisp_Object deleted;
5682 deleted = unwind_create_frame (frame);
5683 if (EQ (deleted, Qt))
5685 tip_window = NULL;
5686 tip_frame = Qnil;
5691 /* Create a frame for a tooltip on the display described by DPYINFO.
5692 PARMS is a list of frame parameters. TEXT is the string to
5693 display in the tip frame. Value is the frame.
5695 Note that functions called here, esp. x_default_parameter can
5696 signal errors, for instance when a specified color name is
5697 undefined. We have to make sure that we're in a consistent state
5698 when this happens. */
5700 static Lisp_Object
5701 x_create_tip_frame (struct w32_display_info *dpyinfo,
5702 Lisp_Object parms, Lisp_Object text)
5704 struct frame *f;
5705 Lisp_Object frame;
5706 Lisp_Object name;
5707 long window_prompting = 0;
5708 int width, height;
5709 ptrdiff_t count = SPECPDL_INDEX ();
5710 struct gcpro gcpro1, gcpro2, gcpro3;
5711 struct kboard *kb;
5712 int face_change_count_before = face_change_count;
5713 Lisp_Object buffer;
5714 struct buffer *old_buffer;
5716 /* Use this general default value to start with until we know if
5717 this frame has a specified name. */
5718 Vx_resource_name = Vinvocation_name;
5720 kb = dpyinfo->terminal->kboard;
5722 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5723 avoid destructive changes behind our caller's back. */
5724 parms = Fcopy_alist (parms);
5726 /* Get the name of the frame to use for resource lookup. */
5727 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
5728 if (!STRINGP (name)
5729 && !EQ (name, Qunbound)
5730 && !NILP (name))
5731 error ("Invalid frame name--not a string or nil");
5732 Vx_resource_name = name;
5734 frame = Qnil;
5735 GCPRO3 (parms, name, frame);
5736 /* Make a frame without minibuffer nor mode-line. */
5737 f = make_frame (0);
5738 f->wants_modeline = 0;
5739 XSETFRAME (frame, f);
5741 buffer = Fget_buffer_create (build_string (" *tip*"));
5742 /* Use set_window_buffer instead of Fset_window_buffer (see
5743 discussion of bug#11984, bug#12025, bug#12026). */
5744 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, 0, 0);
5745 old_buffer = current_buffer;
5746 set_buffer_internal_1 (XBUFFER (buffer));
5747 bset_truncate_lines (current_buffer, Qnil);
5748 specbind (Qinhibit_read_only, Qt);
5749 specbind (Qinhibit_modification_hooks, Qt);
5750 Ferase_buffer ();
5751 Finsert (1, &text);
5752 set_buffer_internal_1 (old_buffer);
5754 record_unwind_protect (unwind_create_tip_frame, frame);
5756 /* By setting the output method, we're essentially saying that
5757 the frame is live, as per FRAME_LIVE_P. If we get a signal
5758 from this point on, x_destroy_window might screw up reference
5759 counts etc. */
5760 f->terminal = dpyinfo->terminal;
5761 f->output_method = output_w32;
5762 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5764 FRAME_FONTSET (f) = -1;
5765 fset_icon_name (f, Qnil);
5767 #ifdef GLYPH_DEBUG
5768 image_cache_refcount =
5769 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5770 dpyinfo_refcount = dpyinfo->reference_count;
5771 #endif /* GLYPH_DEBUG */
5772 FRAME_KBOARD (f) = kb;
5773 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5774 f->output_data.w32->explicit_parent = 0;
5776 /* Set the name; the functions to which we pass f expect the name to
5777 be set. */
5778 if (EQ (name, Qunbound) || NILP (name))
5780 fset_name (f, build_string (dpyinfo->w32_id_name));
5781 f->explicit_name = 0;
5783 else
5785 fset_name (f, name);
5786 f->explicit_name = 1;
5787 /* use the frame's title when getting resources for this frame. */
5788 specbind (Qx_resource_name, name);
5791 if (uniscribe_available)
5792 register_font_driver (&uniscribe_font_driver, f);
5793 register_font_driver (&w32font_driver, f);
5795 x_default_parameter (f, parms, Qfont_backend, Qnil,
5796 "fontBackend", "FontBackend", RES_TYPE_STRING);
5798 /* Extract the window parameters from the supplied values
5799 that are needed to determine window geometry. */
5800 x_default_font_parameter (f, parms);
5802 x_default_parameter (f, parms, Qborder_width, make_number (2),
5803 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5804 /* This defaults to 2 in order to match xterm. We recognize either
5805 internalBorderWidth or internalBorder (which is what xterm calls
5806 it). */
5807 if (NILP (Fassq (Qinternal_border_width, parms)))
5809 Lisp_Object value;
5811 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
5812 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5813 if (! EQ (value, Qunbound))
5814 parms = Fcons (Fcons (Qinternal_border_width, value),
5815 parms);
5817 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
5818 "internalBorderWidth", "internalBorderWidth",
5819 RES_TYPE_NUMBER);
5820 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5821 NULL, NULL, RES_TYPE_NUMBER);
5822 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5823 NULL, NULL, RES_TYPE_NUMBER);
5825 /* Also do the stuff which must be set before the window exists. */
5826 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5827 "foreground", "Foreground", RES_TYPE_STRING);
5828 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5829 "background", "Background", RES_TYPE_STRING);
5830 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5831 "pointerColor", "Foreground", RES_TYPE_STRING);
5832 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5833 "cursorColor", "Foreground", RES_TYPE_STRING);
5834 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5835 "borderColor", "BorderColor", RES_TYPE_STRING);
5837 /* Init faces before x_default_parameter is called for scroll-bar
5838 parameters because that function calls x_set_scroll_bar_width,
5839 which calls change_frame_size, which calls Fset_window_buffer,
5840 which runs hooks, which call Fvertical_motion. At the end, we
5841 end up in init_iterator with a null face cache, which should not
5842 happen. */
5843 init_frame_faces (f);
5845 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
5846 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5848 window_prompting = x_figure_window_size (f, parms, 0);
5850 /* No fringes on tip frame. */
5851 f->fringe_cols = 0;
5852 f->left_fringe_width = 0;
5853 f->right_fringe_width = 0;
5855 block_input ();
5856 my_create_tip_window (f);
5857 unblock_input ();
5859 x_make_gc (f);
5861 x_default_parameter (f, parms, Qauto_raise, Qnil,
5862 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5863 x_default_parameter (f, parms, Qauto_lower, Qnil,
5864 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5865 x_default_parameter (f, parms, Qcursor_type, Qbox,
5866 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5868 /* Dimensions, especially FRAME_LINES (f), must be done via
5869 change_frame_size. Change will not be effected unless different
5870 from the current FRAME_LINES (f). */
5871 width = FRAME_COLS (f);
5872 height = FRAME_LINES (f);
5873 FRAME_LINES (f) = 0;
5874 SET_FRAME_COLS (f, 0);
5875 change_frame_size (f, width, height, 1, 0, 0, 0);
5877 /* Add `tooltip' frame parameter's default value. */
5878 if (NILP (Fframe_parameter (frame, Qtooltip)))
5879 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
5881 /* Set up faces after all frame parameters are known. This call
5882 also merges in face attributes specified for new frames.
5884 Frame parameters may be changed if .Xdefaults contains
5885 specifications for the default font. For example, if there is an
5886 `Emacs.default.attributeBackground: pink', the `background-color'
5887 attribute of the frame get's set, which let's the internal border
5888 of the tooltip frame appear in pink. Prevent this. */
5890 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
5891 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5892 Lisp_Object colors = Qnil;
5894 /* Set tip_frame here, so that */
5895 tip_frame = frame;
5896 call2 (Qface_set_after_frame_default, frame, Qnil);
5898 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
5899 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5900 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5901 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5903 if (!NILP (colors))
5904 Fmodify_frame_parameters (frame, colors);
5907 f->no_split = 1;
5909 UNGCPRO;
5911 /* Now that the frame is official, it counts as a reference to
5912 its display. */
5913 FRAME_DISPLAY_INFO (f)->reference_count++;
5914 f->terminal->reference_count++;
5916 /* It is now ok to make the frame official even if we get an error
5917 below. And the frame needs to be on Vframe_list or making it
5918 visible won't work. */
5919 Vframe_list = Fcons (frame, Vframe_list);
5921 /* Setting attributes of faces of the tooltip frame from resources
5922 and similar will increment face_change_count, which leads to the
5923 clearing of all current matrices. Since this isn't necessary
5924 here, avoid it by resetting face_change_count to the value it
5925 had before we created the tip frame. */
5926 face_change_count = face_change_count_before;
5928 /* Discard the unwind_protect. */
5929 return unbind_to (count, frame);
5933 /* Compute where to display tip frame F. PARMS is the list of frame
5934 parameters for F. DX and DY are specified offsets from the current
5935 location of the mouse. WIDTH and HEIGHT are the width and height
5936 of the tooltip. Return coordinates relative to the root window of
5937 the display in *ROOT_X, and *ROOT_Y. */
5939 static void
5940 compute_tip_xy (struct frame *f,
5941 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5942 int width, int height, int *root_x, int *root_y)
5944 Lisp_Object left, top;
5945 int min_x, min_y, max_x, max_y;
5947 /* User-specified position? */
5948 left = Fcdr (Fassq (Qleft, parms));
5949 top = Fcdr (Fassq (Qtop, parms));
5951 /* Move the tooltip window where the mouse pointer is. Resize and
5952 show it. */
5953 if (!INTEGERP (left) || !INTEGERP (top))
5955 POINT pt;
5957 /* Default min and max values. */
5958 min_x = 0;
5959 min_y = 0;
5960 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5961 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
5963 block_input ();
5964 GetCursorPos (&pt);
5965 *root_x = pt.x;
5966 *root_y = pt.y;
5967 unblock_input ();
5969 /* If multiple monitor support is available, constrain the tip onto
5970 the current monitor. This improves the above by allowing negative
5971 co-ordinates if monitor positions are such that they are valid, and
5972 snaps a tooltip onto a single monitor if we are close to the edge
5973 where it would otherwise flow onto the other monitor (or into
5974 nothingness if there is a gap in the overlap). */
5975 if (monitor_from_point_fn && get_monitor_info_fn)
5977 struct MONITOR_INFO info;
5978 HMONITOR monitor
5979 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5980 info.cbSize = sizeof (info);
5982 if (get_monitor_info_fn (monitor, &info))
5984 min_x = info.rcWork.left;
5985 min_y = info.rcWork.top;
5986 max_x = info.rcWork.right;
5987 max_y = info.rcWork.bottom;
5992 if (INTEGERP (top))
5993 *root_y = XINT (top);
5994 else if (*root_y + XINT (dy) <= min_y)
5995 *root_y = min_y; /* Can happen for negative dy */
5996 else if (*root_y + XINT (dy) + height <= max_y)
5997 /* It fits below the pointer */
5998 *root_y += XINT (dy);
5999 else if (height + XINT (dy) + min_y <= *root_y)
6000 /* It fits above the pointer. */
6001 *root_y -= height + XINT (dy);
6002 else
6003 /* Put it on the top. */
6004 *root_y = min_y;
6006 if (INTEGERP (left))
6007 *root_x = XINT (left);
6008 else if (*root_x + XINT (dx) <= min_x)
6009 *root_x = 0; /* Can happen for negative dx */
6010 else if (*root_x + XINT (dx) + width <= max_x)
6011 /* It fits to the right of the pointer. */
6012 *root_x += XINT (dx);
6013 else if (width + XINT (dx) + min_x <= *root_x)
6014 /* It fits to the left of the pointer. */
6015 *root_x -= width + XINT (dx);
6016 else
6017 /* Put it left justified on the screen -- it ought to fit that way. */
6018 *root_x = min_x;
6022 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
6023 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
6024 A tooltip window is a small window displaying a string.
6026 This is an internal function; Lisp code should call `tooltip-show'.
6028 FRAME nil or omitted means use the selected frame.
6030 PARMS is an optional list of frame parameters which can be
6031 used to change the tooltip's appearance.
6033 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
6034 means use the default timeout of 5 seconds.
6036 If the list of frame parameters PARMS contains a `left' parameter,
6037 the tooltip is displayed at that x-position. Otherwise it is
6038 displayed at the mouse position, with offset DX added (default is 5 if
6039 DX isn't specified). Likewise for the y-position; if a `top' frame
6040 parameter is specified, it determines the y-position of the tooltip
6041 window, otherwise it is displayed at the mouse position, with offset
6042 DY added (default is -10).
6044 A tooltip's maximum size is specified by `x-max-tooltip-size'.
6045 Text larger than the specified size is clipped. */)
6046 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
6048 struct frame *f;
6049 struct window *w;
6050 int root_x, root_y;
6051 struct buffer *old_buffer;
6052 struct text_pos pos;
6053 int i, width, height, seen_reversed_p;
6054 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
6055 int old_windows_or_buffers_changed = windows_or_buffers_changed;
6056 ptrdiff_t count = SPECPDL_INDEX ();
6058 specbind (Qinhibit_redisplay, Qt);
6060 GCPRO4 (string, parms, frame, timeout);
6062 CHECK_STRING (string);
6063 f = decode_window_system_frame (frame);
6064 if (NILP (timeout))
6065 timeout = make_number (5);
6066 else
6067 CHECK_NATNUM (timeout);
6069 if (NILP (dx))
6070 dx = make_number (5);
6071 else
6072 CHECK_NUMBER (dx);
6074 if (NILP (dy))
6075 dy = make_number (-10);
6076 else
6077 CHECK_NUMBER (dy);
6079 if (NILP (last_show_tip_args))
6080 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
6082 if (!NILP (tip_frame))
6084 Lisp_Object last_string = AREF (last_show_tip_args, 0);
6085 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
6086 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
6088 if (EQ (frame, last_frame)
6089 && !NILP (Fequal (last_string, string))
6090 && !NILP (Fequal (last_parms, parms)))
6092 struct frame *f = XFRAME (tip_frame);
6094 /* Only DX and DY have changed. */
6095 if (!NILP (tip_timer))
6097 Lisp_Object timer = tip_timer;
6098 tip_timer = Qnil;
6099 call1 (Qcancel_timer, timer);
6102 block_input ();
6103 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6104 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6106 /* Put tooltip in topmost group and in position. */
6107 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6108 root_x, root_y, 0, 0,
6109 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6111 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6112 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6113 0, 0, 0, 0,
6114 SWP_NOMOVE | SWP_NOSIZE
6115 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6117 unblock_input ();
6118 goto start_timer;
6122 /* Hide a previous tip, if any. */
6123 Fx_hide_tip ();
6125 ASET (last_show_tip_args, 0, string);
6126 ASET (last_show_tip_args, 1, frame);
6127 ASET (last_show_tip_args, 2, parms);
6129 /* Add default values to frame parameters. */
6130 if (NILP (Fassq (Qname, parms)))
6131 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6132 if (NILP (Fassq (Qinternal_border_width, parms)))
6133 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6134 if (NILP (Fassq (Qright_divider_width, parms)))
6135 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6136 if (NILP (Fassq (Qbottom_divider_width, parms)))
6137 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6138 if (NILP (Fassq (Qborder_width, parms)))
6139 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6140 if (NILP (Fassq (Qborder_color, parms)))
6141 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6142 if (NILP (Fassq (Qbackground_color, parms)))
6143 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6144 parms);
6146 /* Block input until the tip has been fully drawn, to avoid crashes
6147 when drawing tips in menus. */
6148 block_input ();
6150 /* Create a frame for the tooltip, and record it in the global
6151 variable tip_frame. */
6152 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6153 f = XFRAME (frame);
6155 /* Set up the frame's root window. */
6156 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6157 w->left_col = 0;
6158 w->top_line = 0;
6159 w->pixel_left = 0;
6160 w->pixel_top = 0;
6162 if (CONSP (Vx_max_tooltip_size)
6163 && INTEGERP (XCAR (Vx_max_tooltip_size))
6164 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6165 && INTEGERP (XCDR (Vx_max_tooltip_size))
6166 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6168 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6169 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6171 else
6173 w->total_cols = 80;
6174 w->total_lines = 40;
6177 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6178 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6180 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6181 adjust_frame_glyphs (f);
6182 w->pseudo_window_p = 1;
6184 /* Display the tooltip text in a temporary buffer. */
6185 old_buffer = current_buffer;
6186 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6187 bset_truncate_lines (current_buffer, Qnil);
6188 clear_glyph_matrix (w->desired_matrix);
6189 clear_glyph_matrix (w->current_matrix);
6190 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6191 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6193 /* Compute width and height of the tooltip. */
6194 width = height = seen_reversed_p = 0;
6195 for (i = 0; i < w->desired_matrix->nrows; ++i)
6197 struct glyph_row *row = &w->desired_matrix->rows[i];
6198 struct glyph *last;
6199 int row_width;
6201 /* Stop at the first empty row at the end. */
6202 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6203 break;
6205 /* Let the row go over the full width of the frame. */
6206 row->full_width_p = 1;
6208 row_width = row->pixel_width;
6209 if (row->used[TEXT_AREA])
6211 if (!row->reversed_p)
6213 /* There's a glyph at the end of rows that is used to
6214 place the cursor there. Don't include the width of
6215 this glyph. */
6216 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6217 if (INTEGERP (last->object))
6218 row_width -= last->pixel_width;
6220 else
6222 /* There could be a stretch glyph at the beginning of R2L
6223 rows that is produced by extend_face_to_end_of_line.
6224 Don't count that glyph. */
6225 struct glyph *g = row->glyphs[TEXT_AREA];
6227 if (g->type == STRETCH_GLYPH && INTEGERP (g->object))
6229 row_width -= g->pixel_width;
6230 seen_reversed_p = 1;
6235 height += row->height;
6236 width = max (width, row_width);
6239 /* If we've seen partial-length R2L rows, we need to re-adjust the
6240 tool-tip frame width and redisplay it again, to avoid over-wide
6241 tips due to the stretch glyph that extends R2L lines to full
6242 width of the frame. */
6243 if (seen_reversed_p)
6245 /* PXW: Why do we do the pixel-to-cols conversion only if
6246 seen_reversed_p holds? Don't we have to set other fields of
6247 the window/frame structure?
6249 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6250 not in pixels. */
6251 w->pixel_width = width;
6252 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6253 w->total_cols = width;
6254 FRAME_TOTAL_COLS (f) = width;
6255 SET_FRAME_WIDTH (f, width);
6256 adjust_frame_glyphs (f);
6257 w->pseudo_window_p = 1;
6258 clear_glyph_matrix (w->desired_matrix);
6259 clear_glyph_matrix (w->current_matrix);
6260 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6261 width = height = 0;
6262 /* Recompute width and height of the tooltip. */
6263 for (i = 0; i < w->desired_matrix->nrows; ++i)
6265 struct glyph_row *row = &w->desired_matrix->rows[i];
6266 struct glyph *last;
6267 int row_width;
6269 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6270 break;
6271 row->full_width_p = 1;
6272 row_width = row->pixel_width;
6273 if (row->used[TEXT_AREA] && !row->reversed_p)
6275 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6276 if (INTEGERP (last->object))
6277 row_width -= last->pixel_width;
6280 height += row->height;
6281 width = max (width, row_width);
6285 /* Add the frame's internal border to the width and height the w32
6286 window should have. */
6287 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6288 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6290 /* Move the tooltip window where the mouse pointer is. Resize and
6291 show it.
6293 PXW: This should use the frame's pixel coordinates. */
6294 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6297 /* Adjust Window size to take border into account. */
6298 RECT rect;
6299 rect.left = rect.top = 0;
6300 rect.right = width;
6301 rect.bottom = height;
6302 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6303 FRAME_EXTERNAL_MENU_BAR (f));
6305 /* Position and size tooltip, and put it in the topmost group.
6306 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6307 peculiarity of w32 display: without it, some fonts cause the
6308 last character of the tip to be truncated or wrapped around to
6309 the next line. */
6310 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6311 root_x, root_y,
6312 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6313 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6315 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6316 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6317 0, 0, 0, 0,
6318 SWP_NOMOVE | SWP_NOSIZE
6319 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6321 /* Let redisplay know that we have made the frame visible already. */
6322 SET_FRAME_VISIBLE (f, 1);
6324 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6327 /* Draw into the window. */
6328 w->must_be_updated_p = 1;
6329 update_single_window (w, 1);
6331 unblock_input ();
6333 /* Restore original current buffer. */
6334 set_buffer_internal_1 (old_buffer);
6335 windows_or_buffers_changed = old_windows_or_buffers_changed;
6337 start_timer:
6338 /* Let the tip disappear after timeout seconds. */
6339 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6340 intern ("x-hide-tip"));
6342 UNGCPRO;
6343 return unbind_to (count, Qnil);
6347 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6348 doc: /* Hide the current tooltip window, if there is any.
6349 Value is t if tooltip was open, nil otherwise. */)
6350 (void)
6352 ptrdiff_t count;
6353 Lisp_Object deleted, frame, timer;
6354 struct gcpro gcpro1, gcpro2;
6356 /* Return quickly if nothing to do. */
6357 if (NILP (tip_timer) && NILP (tip_frame))
6358 return Qnil;
6360 frame = tip_frame;
6361 timer = tip_timer;
6362 GCPRO2 (frame, timer);
6363 tip_frame = tip_timer = deleted = Qnil;
6365 count = SPECPDL_INDEX ();
6366 specbind (Qinhibit_redisplay, Qt);
6367 specbind (Qinhibit_quit, Qt);
6369 if (!NILP (timer))
6370 call1 (Qcancel_timer, timer);
6372 if (FRAMEP (frame))
6374 delete_frame (frame, Qnil);
6375 deleted = Qt;
6378 UNGCPRO;
6379 return unbind_to (count, deleted);
6382 /***********************************************************************
6383 File selection dialog
6384 ***********************************************************************/
6386 #define FILE_NAME_TEXT_FIELD edt1
6387 #define FILE_NAME_COMBO_BOX cmb13
6388 #define FILE_NAME_LIST lst1
6390 /* Callback for altering the behavior of the Open File dialog.
6391 Makes the Filename text field contain "Current Directory" and be
6392 read-only when "Directories" is selected in the filter. This
6393 allows us to work around the fact that the standard Open File
6394 dialog does not support directories. */
6395 static UINT_PTR CALLBACK
6396 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6398 if (msg == WM_NOTIFY)
6400 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6401 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6402 int dropdown_changed;
6403 int dir_index;
6404 #ifdef NTGUI_UNICODE
6405 const int use_unicode = 1;
6406 #else /* !NTGUI_UNICODE */
6407 int use_unicode = w32_unicode_filenames;
6408 #endif /* NTGUI_UNICODE */
6410 /* Detect when the Filter dropdown is changed. */
6411 if (use_unicode)
6412 dropdown_changed =
6413 notify_w->hdr.code == CDN_TYPECHANGE
6414 || notify_w->hdr.code == CDN_INITDONE;
6415 else
6416 dropdown_changed =
6417 notify_a->hdr.code == CDN_TYPECHANGE
6418 || notify_a->hdr.code == CDN_INITDONE;
6419 if (dropdown_changed)
6421 HWND dialog = GetParent (hwnd);
6422 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6423 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6424 int hdr_code;
6426 /* At least on Windows 7, the above attempt to get the window handle
6427 to the File Name Text Field fails. The following code does the
6428 job though. Note that this code is based on my examination of the
6429 window hierarchy using Microsoft Spy++. bk */
6430 if (edit_control == NULL)
6432 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6433 if (tmp)
6435 tmp = GetWindow (tmp, GW_CHILD);
6436 if (tmp)
6437 edit_control = GetWindow (tmp, GW_CHILD);
6441 /* Directories is in index 2. */
6442 if (use_unicode)
6444 dir_index = notify_w->lpOFN->nFilterIndex;
6445 hdr_code = notify_w->hdr.code;
6447 else
6449 dir_index = notify_a->lpOFN->nFilterIndex;
6450 hdr_code = notify_a->hdr.code;
6452 if (dir_index == 2)
6454 if (use_unicode)
6455 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6456 (LPARAM)L"Current Directory");
6457 else
6458 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6459 (LPARAM)"Current Directory");
6460 EnableWindow (edit_control, FALSE);
6461 /* Note that at least on Windows 7, the above call to EnableWindow
6462 disables the window that would ordinarily have focus. If we
6463 do not set focus to some other window here, focus will land in
6464 no man's land and the user will be unable to tab through the
6465 dialog box (pressing tab will only result in a beep).
6466 Avoid that problem by setting focus to the list here. */
6467 if (hdr_code == CDN_INITDONE)
6468 SetFocus (list);
6470 else
6472 /* Don't override default filename on init done. */
6473 if (hdr_code == CDN_TYPECHANGE)
6475 if (use_unicode)
6476 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6477 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6478 else
6479 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6480 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6482 EnableWindow (edit_control, TRUE);
6486 return 0;
6489 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6490 doc: /* Read file name, prompting with PROMPT in directory DIR.
6491 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6492 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6493 or directory must exist.
6495 This function is only defined on NS, MS Windows, and X Windows with the
6496 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6497 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6498 On Windows 7 and later, the file selection dialog "remembers" the last
6499 directory where the user selected a file, and will open that directory
6500 instead of DIR on subsequent invocations of this function with the same
6501 value of DIR as in previous invocations; this is standard Windows behavior. */)
6502 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6504 /* Filter index: 1: All Files, 2: Directories only */
6505 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6506 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6508 Lisp_Object filename = default_filename;
6509 struct frame *f = SELECTED_FRAME ();
6510 BOOL file_opened = FALSE;
6511 Lisp_Object orig_dir = dir;
6512 Lisp_Object orig_prompt = prompt;
6514 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6515 compatibility) we end up with the old file dialogs. Define a big
6516 enough struct for the new dialog to trick GetOpenFileName into
6517 giving us the new dialogs on newer versions of Windows. */
6518 struct {
6519 OPENFILENAMEW details;
6520 #if _WIN32_WINNT < 0x500 /* < win2k */
6521 PVOID pvReserved;
6522 DWORD dwReserved;
6523 DWORD FlagsEx;
6524 #endif /* < win2k */
6525 } new_file_details_w;
6527 #ifdef NTGUI_UNICODE
6528 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6529 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6530 const int use_unicode = 1;
6531 #else /* not NTGUI_UNICODE */
6532 struct {
6533 OPENFILENAMEA details;
6534 #if _WIN32_WINNT < 0x500 /* < win2k */
6535 PVOID pvReserved;
6536 DWORD dwReserved;
6537 DWORD FlagsEx;
6538 #endif /* < win2k */
6539 } new_file_details_a;
6540 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6541 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6542 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6543 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6544 int use_unicode = w32_unicode_filenames;
6545 wchar_t *prompt_w;
6546 char *prompt_a;
6547 int len;
6548 char fname_ret[MAX_UTF8_PATH];
6549 #endif /* NTGUI_UNICODE */
6551 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
6552 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
6555 struct gcpro gcpro1, gcpro2;
6556 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
6558 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6559 system file encoding expected by the platform APIs (e.g. Cygwin's
6560 POSIX implementation) may not be the same as the encoding expected
6561 by the Windows "ANSI" APIs! */
6563 CHECK_STRING (prompt);
6564 CHECK_STRING (dir);
6566 dir = Fexpand_file_name (dir, Qnil);
6568 if (STRINGP (filename))
6569 filename = Ffile_name_nondirectory (filename);
6570 else
6571 filename = empty_unibyte_string;
6573 #ifdef CYGWIN
6574 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
6575 if (SCHARS (filename) > 0)
6576 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
6577 #endif
6579 CHECK_STRING (dir);
6580 CHECK_STRING (filename);
6582 /* The code in file_dialog_callback that attempts to set the text
6583 of the file name edit window when handling the CDN_INITDONE
6584 WM_NOTIFY message does not work. Setting filename to "Current
6585 Directory" in the only_dir_p case here does work however. */
6586 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6587 filename = build_string ("Current Directory");
6589 /* Convert the values we've computed so far to system form. */
6590 #ifdef NTGUI_UNICODE
6591 to_unicode (prompt, &prompt);
6592 to_unicode (dir, &dir);
6593 to_unicode (filename, &filename);
6594 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6595 report_file_error ("filename too long", default_filename);
6597 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
6598 #else /* !NTGUI_UNICODE */
6599 prompt = ENCODE_FILE (prompt);
6600 dir = ENCODE_FILE (dir);
6601 filename = ENCODE_FILE (filename);
6603 /* We modify these in-place, so make copies for safety. */
6604 dir = Fcopy_sequence (dir);
6605 unixtodos_filename (SDATA (dir));
6606 filename = Fcopy_sequence (filename);
6607 unixtodos_filename (SDATA (filename));
6608 if (SBYTES (filename) >= MAX_UTF8_PATH)
6609 report_file_error ("filename too long", default_filename);
6610 if (w32_unicode_filenames)
6612 filename_to_utf16 (SSDATA (dir), dir_w);
6613 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6615 /* filename_to_utf16 sets errno to ENOENT when the file
6616 name is too long or cannot be converted to UTF-16. */
6617 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6618 report_file_error ("filename too long", default_filename);
6620 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6621 SSDATA (prompt), -1, NULL, 0);
6622 if (len > 32768)
6623 len = 32768;
6624 prompt_w = alloca (len * sizeof (wchar_t));
6625 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6626 SSDATA (prompt), -1, prompt_w, len);
6628 else
6630 filename_to_ansi (SSDATA (dir), dir_a);
6631 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6633 /* filename_to_ansi sets errno to ENOENT when the file
6634 name is too long or cannot be converted to UTF-16. */
6635 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6636 report_file_error ("filename too long", default_filename);
6638 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6639 SSDATA (prompt), -1, NULL, 0);
6640 if (len > 32768)
6641 len = 32768;
6642 prompt_w = alloca (len * sizeof (wchar_t));
6643 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6644 SSDATA (prompt), -1, prompt_w, len);
6645 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
6646 if (len > 32768)
6647 len = 32768;
6648 prompt_a = alloca (len);
6649 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
6651 #endif /* NTGUI_UNICODE */
6653 /* Fill in the structure for the call to GetOpenFileName below.
6654 For NTGUI_UNICODE builds (which run only on NT), we just use
6655 the actual size of the structure. For non-NTGUI_UNICODE
6656 builds, we tell the OS we're using an old version of the
6657 structure if the OS isn't new enough to support the newer
6658 version. */
6659 if (use_unicode)
6661 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6662 if (w32_major_version > 4 && w32_major_version < 95)
6663 file_details_w->lStructSize = sizeof (new_file_details_w);
6664 else
6665 file_details_w->lStructSize = sizeof (*file_details_w);
6666 /* Set up the inout parameter for the selected file name. */
6667 file_details_w->lpstrFile = filename_buf_w;
6668 file_details_w->nMaxFile =
6669 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6670 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6671 /* Undocumented Bug in Common File Dialog:
6672 If a filter is not specified, shell links are not resolved. */
6673 file_details_w->lpstrFilter = filter_w;
6674 #ifdef NTGUI_UNICODE
6675 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
6676 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
6677 #else
6678 file_details_w->lpstrInitialDir = dir_w;
6679 file_details_w->lpstrTitle = prompt_w;
6680 #endif
6681 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6682 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6683 | OFN_EXPLORER | OFN_ENABLEHOOK);
6684 if (!NILP (mustmatch))
6686 /* Require that the path to the parent directory exists. */
6687 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6688 /* If we are looking for a file, require that it exists. */
6689 if (NILP (only_dir_p))
6690 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6693 #ifndef NTGUI_UNICODE
6694 else
6696 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6697 if (w32_major_version > 4 && w32_major_version < 95)
6698 file_details_a->lStructSize = sizeof (new_file_details_a);
6699 else
6700 file_details_a->lStructSize = sizeof (*file_details_a);
6701 file_details_a->lpstrFile = filename_buf_a;
6702 file_details_a->nMaxFile =
6703 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6704 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6705 file_details_a->lpstrFilter = filter_a;
6706 file_details_a->lpstrInitialDir = dir_a;
6707 file_details_a->lpstrTitle = prompt_a;
6708 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6709 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6710 | OFN_EXPLORER | OFN_ENABLEHOOK);
6711 if (!NILP (mustmatch))
6713 /* Require that the path to the parent directory exists. */
6714 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6715 /* If we are looking for a file, require that it exists. */
6716 if (NILP (only_dir_p))
6717 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6720 #endif /* !NTGUI_UNICODE */
6723 int count = SPECPDL_INDEX ();
6724 /* Prevent redisplay. */
6725 specbind (Qinhibit_redisplay, Qt);
6726 block_input ();
6727 if (use_unicode)
6729 file_details_w->lpfnHook = file_dialog_callback;
6731 file_opened = GetOpenFileNameW (file_details_w);
6733 #ifndef NTGUI_UNICODE
6734 else
6736 file_details_a->lpfnHook = file_dialog_callback;
6738 file_opened = GetOpenFileNameA (file_details_a);
6740 #endif /* !NTGUI_UNICODE */
6741 unblock_input ();
6742 unbind_to (count, Qnil);
6745 if (file_opened)
6747 /* Get an Emacs string from the value Windows gave us. */
6748 #ifdef NTGUI_UNICODE
6749 filename = from_unicode_buffer (filename_buf_w);
6750 #else /* !NTGUI_UNICODE */
6751 if (use_unicode)
6752 filename_from_utf16 (filename_buf_w, fname_ret);
6753 else
6754 filename_from_ansi (filename_buf_a, fname_ret);
6755 dostounix_filename (fname_ret);
6756 filename = DECODE_FILE (build_unibyte_string (fname_ret));
6757 #endif /* NTGUI_UNICODE */
6759 #ifdef CYGWIN
6760 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
6761 #endif /* CYGWIN */
6763 /* Strip the dummy filename off the end of the string if we
6764 added it to select a directory. */
6765 if ((use_unicode && file_details_w->nFilterIndex == 2)
6766 #ifndef NTGUI_UNICODE
6767 || (!use_unicode && file_details_a->nFilterIndex == 2)
6768 #endif
6770 filename = Ffile_name_directory (filename);
6772 /* User canceled the dialog without making a selection. */
6773 else if (!CommDlgExtendedError ())
6774 filename = Qnil;
6775 /* An error occurred, fallback on reading from the mini-buffer. */
6776 else
6777 filename = Fcompleting_read (
6778 orig_prompt,
6779 intern ("read-file-name-internal"),
6780 orig_dir,
6781 mustmatch,
6782 orig_dir,
6783 Qfile_name_history,
6784 default_filename,
6785 Qnil);
6787 UNGCPRO;
6790 /* Make "Cancel" equivalent to C-g. */
6791 if (NILP (filename))
6792 Fsignal (Qquit, Qnil);
6794 RETURN_UNGCPRO (filename);
6798 #ifdef WINDOWSNT
6799 /* Moving files to the system recycle bin.
6800 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6801 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6802 Ssystem_move_file_to_trash, 1, 1, 0,
6803 doc: /* Move file or directory named FILENAME to the recycle bin. */)
6804 (Lisp_Object filename)
6806 Lisp_Object handler;
6807 Lisp_Object encoded_file;
6808 Lisp_Object operation;
6810 operation = Qdelete_file;
6811 if (!NILP (Ffile_directory_p (filename))
6812 && NILP (Ffile_symlink_p (filename)))
6814 operation = intern ("delete-directory");
6815 filename = Fdirectory_file_name (filename);
6818 /* Must have fully qualified file names for moving files to Recycle
6819 Bin. */
6820 filename = Fexpand_file_name (filename, Qnil);
6822 handler = Ffind_file_name_handler (filename, operation);
6823 if (!NILP (handler))
6824 return call2 (handler, operation, filename);
6825 else
6827 const char * path;
6828 int result;
6830 encoded_file = ENCODE_FILE (filename);
6832 path = map_w32_filename (SDATA (encoded_file), NULL);
6834 /* The Unicode version of SHFileOperation is not supported on
6835 Windows 9X. */
6836 if (w32_unicode_filenames && os_subtype != OS_9X)
6838 SHFILEOPSTRUCTW file_op_w;
6839 /* We need one more element beyond MAX_PATH because this is
6840 a list of file names, with the last element double-null
6841 terminated. */
6842 wchar_t tmp_path_w[MAX_PATH + 1];
6844 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6845 filename_to_utf16 (path, tmp_path_w);
6847 /* On Windows, write permission is required to delete/move files. */
6848 _wchmod (tmp_path_w, 0666);
6850 memset (&file_op_w, 0, sizeof (file_op_w));
6851 file_op_w.hwnd = HWND_DESKTOP;
6852 file_op_w.wFunc = FO_DELETE;
6853 file_op_w.pFrom = tmp_path_w;
6854 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6855 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6856 file_op_w.fAnyOperationsAborted = FALSE;
6858 result = SHFileOperationW (&file_op_w);
6860 else
6862 SHFILEOPSTRUCTA file_op_a;
6863 char tmp_path_a[MAX_PATH + 1];
6865 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6866 filename_to_ansi (path, tmp_path_a);
6868 /* If a file cannot be represented in ANSI codepage, don't
6869 let them inadvertently delete other files because some
6870 characters are interpreted as a wildcards. */
6871 if (_mbspbrk (tmp_path_a, "?*"))
6872 result = ERROR_FILE_NOT_FOUND;
6873 else
6875 _chmod (tmp_path_a, 0666);
6877 memset (&file_op_a, 0, sizeof (file_op_a));
6878 file_op_a.hwnd = HWND_DESKTOP;
6879 file_op_a.wFunc = FO_DELETE;
6880 file_op_a.pFrom = tmp_path_a;
6881 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6882 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6883 file_op_a.fAnyOperationsAborted = FALSE;
6885 result = SHFileOperationA (&file_op_a);
6888 if (result != 0)
6889 report_file_error ("Removing old name", list1 (filename));
6891 return Qnil;
6894 #endif /* WINDOWSNT */
6897 /***********************************************************************
6898 w32 specialized functions
6899 ***********************************************************************/
6901 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6902 Sw32_send_sys_command, 1, 2, 0,
6903 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
6904 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
6905 to minimize), #xf120 to restore frame to original size, and #xf100
6906 to activate the menubar for keyboard access. #xf140 activates the
6907 screen saver if defined.
6909 If optional parameter FRAME is not specified, use selected frame. */)
6910 (Lisp_Object command, Lisp_Object frame)
6912 struct frame *f = decode_window_system_frame (frame);
6914 CHECK_NUMBER (command);
6916 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
6918 return Qnil;
6921 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
6922 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6923 This is a wrapper around the ShellExecute system function, which
6924 invokes the application registered to handle OPERATION for DOCUMENT.
6926 OPERATION is either nil or a string that names a supported operation.
6927 What operations can be used depends on the particular DOCUMENT and its
6928 handler application, but typically it is one of the following common
6929 operations:
6931 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6932 executable program (application). If it is an application,
6933 that application is launched in the current buffer's default
6934 directory. Otherwise, the application associated with
6935 DOCUMENT is launched in the buffer's default directory.
6936 \"opennew\" - like \"open\", but instruct the application to open
6937 DOCUMENT in a new window.
6938 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
6939 \"print\" - print DOCUMENT, which must be a file.
6940 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
6941 The printer should be provided in PARAMETERS, see below.
6942 \"explore\" - start the Windows Explorer on DOCUMENT.
6943 \"edit\" - launch an editor and open DOCUMENT for editing; which
6944 editor is launched depends on the association for the
6945 specified DOCUMENT.
6946 \"find\" - initiate search starting from DOCUMENT, which must specify
6947 a directory.
6948 \"runas\" - run DOCUMENT, which must be an excutable file, with
6949 elevated privileges (a.k.a. \"as Administrator\").
6950 \"properties\"
6951 - open the the property sheet dialog for DOCUMENT; works
6952 for *.lnk desktop shortcuts, and little or nothing else.
6953 nil - invoke the default OPERATION, or \"open\" if default is
6954 not defined or unavailable.
6956 DOCUMENT is typically the name of a document file or a URL, but can
6957 also be an executable program to run, or a directory to open in the
6958 Windows Explorer. If it is a file, it must be a local one; this
6959 function does not support remote file names.
6961 If DOCUMENT is an executable program, the optional third arg PARAMETERS
6962 can be a string containing command line parameters that will be passed
6963 to the program. Some values of OPERATION also require parameters (e.g.,
6964 \"printto\" requires the printer address). Otherwise, PARAMETERS should
6965 be nil or unspecified.
6967 Optional fourth argument SHOW-FLAG can be used to control how the
6968 application will be displayed when it is invoked. If SHOW-FLAG is nil
6969 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
6970 specified, otherwise it is an integer between 0 and 11 representing
6971 a ShowWindow flag:
6973 0 - start hidden
6974 1 - start as normal-size window
6975 3 - start in a maximized window
6976 6 - start in a minimized window
6977 10 - start as the application itself specifies; this is the default. */)
6978 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
6980 char *errstr;
6981 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6982 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
6983 intptr_t result;
6984 #ifndef CYGWIN
6985 int use_unicode = w32_unicode_filenames;
6986 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
6987 Lisp_Object absdoc, handler;
6988 struct gcpro gcpro1;
6989 #endif
6991 CHECK_STRING (document);
6993 #ifdef CYGWIN
6994 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
6995 document = Fcygwin_convert_file_name_to_windows (document, Qt);
6997 /* Encode filename, current directory and parameters. */
6998 current_dir = GUI_ENCODE_FILE (current_dir);
6999 document = GUI_ENCODE_FILE (document);
7000 doc_w = GUI_SDATA (document);
7001 if (STRINGP (parameters))
7003 parameters = GUI_ENCODE_SYSTEM (parameters);
7004 params_w = GUI_SDATA (parameters);
7006 if (STRINGP (operation))
7008 operation = GUI_ENCODE_SYSTEM (operation);
7009 ops_w = GUI_SDATA (operation);
7011 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7012 GUI_SDATA (current_dir),
7013 (INTEGERP (show_flag)
7014 ? XINT (show_flag) : SW_SHOWDEFAULT));
7015 #else /* !CYGWIN */
7016 current_dir = ENCODE_FILE (current_dir);
7017 /* We have a situation here. If DOCUMENT is a relative file name,
7018 but its name includes leading directories, i.e. it lives not in
7019 CURRENT_DIR, but in its subdirectory, then ShellExecute below
7020 will fail to find it. So we need to make the file name is
7021 absolute. But DOCUMENT does not have to be a file, it can be a
7022 URL, for example. So we make it absolute only if it is an
7023 existing file; if it is a file that does not exist, tough. */
7024 GCPRO1 (absdoc);
7025 absdoc = Fexpand_file_name (document, Qnil);
7026 /* Don't call file handlers for file-exists-p, since they might
7027 attempt to access the file, which could fail or produce undesired
7028 consequences, see bug#16558 for an example. */
7029 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
7030 if (NILP (handler))
7032 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
7034 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
7036 /* ShellExecute fails if DOCUMENT is a UNC with forward
7037 slashes (expand-file-name above converts all backslashes
7038 to forward slashes). Now that we know DOCUMENT is a
7039 file, we can mirror all forward slashes into backslashes. */
7040 unixtodos_filename (SSDATA (absdoc_encoded));
7041 document = absdoc_encoded;
7043 else
7044 document = ENCODE_FILE (document);
7046 else
7047 document = ENCODE_FILE (document);
7048 UNGCPRO;
7049 if (use_unicode)
7051 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
7053 /* Encode filename, current directory and parameters, and
7054 convert operation to UTF-16. */
7055 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7056 filename_to_utf16 (SSDATA (document), document_w);
7057 doc_w = document_w;
7058 if (STRINGP (parameters))
7060 int len;
7062 parameters = ENCODE_SYSTEM (parameters);
7063 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7064 SSDATA (parameters), -1, NULL, 0);
7065 if (len > 32768)
7066 len = 32768;
7067 params_w = alloca (len * sizeof (wchar_t));
7068 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7069 SSDATA (parameters), -1, params_w, len);
7071 if (STRINGP (operation))
7073 /* Assume OPERATION is pure ASCII. */
7074 const char *s = SSDATA (operation);
7075 wchar_t *d;
7076 int len = SBYTES (operation) + 1;
7078 if (len > 32768)
7079 len = 32768;
7080 d = ops_w = alloca (len * sizeof (wchar_t));
7081 while (d < ops_w + len - 1)
7082 *d++ = *s++;
7083 *d = 0;
7085 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
7086 current_dir_w,
7087 (INTEGERP (show_flag)
7088 ? XINT (show_flag) : SW_SHOWDEFAULT));
7090 else
7092 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7094 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7095 filename_to_ansi (SSDATA (document), document_a);
7096 doc_a = document_a;
7097 if (STRINGP (parameters))
7099 parameters = ENCODE_SYSTEM (parameters);
7100 params_a = SSDATA (parameters);
7102 if (STRINGP (operation))
7104 /* Assume OPERATION is pure ASCII. */
7105 ops_a = SSDATA (operation);
7107 result = (intptr_t) ShellExecuteA (NULL, ops_a, doc_a, params_a,
7108 current_dir_a,
7109 (INTEGERP (show_flag)
7110 ? XINT (show_flag) : SW_SHOWDEFAULT));
7112 #endif /* !CYGWIN */
7114 if (result > 32)
7115 return Qt;
7117 switch (result)
7119 case SE_ERR_ACCESSDENIED:
7120 errstr = w32_strerror (ERROR_ACCESS_DENIED);
7121 break;
7122 case SE_ERR_ASSOCINCOMPLETE:
7123 case SE_ERR_NOASSOC:
7124 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
7125 break;
7126 case SE_ERR_DDEBUSY:
7127 case SE_ERR_DDEFAIL:
7128 errstr = w32_strerror (ERROR_DDE_FAIL);
7129 break;
7130 case SE_ERR_DDETIMEOUT:
7131 errstr = w32_strerror (ERROR_TIMEOUT);
7132 break;
7133 case SE_ERR_DLLNOTFOUND:
7134 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
7135 break;
7136 case SE_ERR_FNF:
7137 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
7138 break;
7139 case SE_ERR_OOM:
7140 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
7141 break;
7142 case SE_ERR_PNF:
7143 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
7144 break;
7145 case SE_ERR_SHARE:
7146 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
7147 break;
7148 default:
7149 errstr = w32_strerror (0);
7150 break;
7152 /* The error string might be encoded in the locale's encoding. */
7153 if (!NILP (Vlocale_coding_system))
7155 Lisp_Object decoded =
7156 code_convert_string_norecord (build_unibyte_string (errstr),
7157 Vlocale_coding_system, 0);
7158 errstr = SSDATA (decoded);
7160 error ("ShellExecute failed: %s", errstr);
7163 /* Lookup virtual keycode from string representing the name of a
7164 non-ascii keystroke into the corresponding virtual key, using
7165 lispy_function_keys. */
7166 static int
7167 lookup_vk_code (char *key)
7169 int i;
7171 for (i = 0; i < 256; i++)
7172 if (lispy_function_keys[i]
7173 && strcmp (lispy_function_keys[i], key) == 0)
7174 return i;
7176 return -1;
7179 /* Convert a one-element vector style key sequence to a hot key
7180 definition. */
7181 static Lisp_Object
7182 w32_parse_hot_key (Lisp_Object key)
7184 /* Copied from Fdefine_key and store_in_keymap. */
7185 register Lisp_Object c;
7186 int vk_code;
7187 int lisp_modifiers;
7188 int w32_modifiers;
7189 struct gcpro gcpro1;
7191 CHECK_VECTOR (key);
7193 if (ASIZE (key) != 1)
7194 return Qnil;
7196 GCPRO1 (key);
7198 c = AREF (key, 0);
7200 if (CONSP (c) && lucid_event_type_list_p (c))
7201 c = Fevent_convert_list (c);
7203 UNGCPRO;
7205 if (! INTEGERP (c) && ! SYMBOLP (c))
7206 error ("Key definition is invalid");
7208 /* Work out the base key and the modifiers. */
7209 if (SYMBOLP (c))
7211 c = parse_modifiers (c);
7212 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7213 c = Fcar (c);
7214 if (!SYMBOLP (c))
7215 emacs_abort ();
7216 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7218 else if (INTEGERP (c))
7220 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7221 /* Many ascii characters are their own virtual key code. */
7222 vk_code = XINT (c) & CHARACTERBITS;
7225 if (vk_code < 0 || vk_code > 255)
7226 return Qnil;
7228 if ((lisp_modifiers & meta_modifier) != 0
7229 && !NILP (Vw32_alt_is_meta))
7230 lisp_modifiers |= alt_modifier;
7232 /* Supply defs missing from mingw32. */
7233 #ifndef MOD_ALT
7234 #define MOD_ALT 0x0001
7235 #define MOD_CONTROL 0x0002
7236 #define MOD_SHIFT 0x0004
7237 #define MOD_WIN 0x0008
7238 #endif
7240 /* Convert lisp modifiers to Windows hot-key form. */
7241 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7242 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7243 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7244 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7246 return HOTKEY (vk_code, w32_modifiers);
7249 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7250 Sw32_register_hot_key, 1, 1, 0,
7251 doc: /* Register KEY as a hot-key combination.
7252 Certain key combinations like Alt-Tab are reserved for system use on
7253 Windows, and therefore are normally intercepted by the system. However,
7254 most of these key combinations can be received by registering them as
7255 hot-keys, overriding their special meaning.
7257 KEY must be a one element key definition in vector form that would be
7258 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7259 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7260 is always interpreted as the Windows modifier keys.
7262 The return value is the hotkey-id if registered, otherwise nil. */)
7263 (Lisp_Object key)
7265 key = w32_parse_hot_key (key);
7267 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7269 /* Reuse an empty slot if possible. */
7270 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7272 /* Safe to add new key to list, even if we have focus. */
7273 if (NILP (item))
7274 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7275 else
7276 XSETCAR (item, key);
7278 /* Notify input thread about new hot-key definition, so that it
7279 takes effect without needing to switch focus. */
7280 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7281 (WPARAM) XLI (key), 0);
7284 return key;
7287 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7288 Sw32_unregister_hot_key, 1, 1, 0,
7289 doc: /* Unregister KEY as a hot-key combination. */)
7290 (Lisp_Object key)
7292 Lisp_Object item;
7294 if (!INTEGERP (key))
7295 key = w32_parse_hot_key (key);
7297 item = Fmemq (key, w32_grabbed_keys);
7299 if (!NILP (item))
7301 /* Notify input thread about hot-key definition being removed, so
7302 that it takes effect without needing focus switch. */
7303 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7304 (WPARAM) XINT (XCAR (item)), (LPARAM) XLI (item)))
7306 MSG msg;
7307 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7309 return Qt;
7311 return Qnil;
7314 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7315 Sw32_registered_hot_keys, 0, 0, 0,
7316 doc: /* Return list of registered hot-key IDs. */)
7317 (void)
7319 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7322 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7323 Sw32_reconstruct_hot_key, 1, 1, 0,
7324 doc: /* Convert hot-key ID to a lisp key combination.
7325 usage: (w32-reconstruct-hot-key ID) */)
7326 (Lisp_Object hotkeyid)
7328 int vk_code, w32_modifiers;
7329 Lisp_Object key;
7331 CHECK_NUMBER (hotkeyid);
7333 vk_code = HOTKEY_VK_CODE (hotkeyid);
7334 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7336 if (vk_code < 256 && lispy_function_keys[vk_code])
7337 key = intern (lispy_function_keys[vk_code]);
7338 else
7339 key = make_number (vk_code);
7341 key = Fcons (key, Qnil);
7342 if (w32_modifiers & MOD_SHIFT)
7343 key = Fcons (Qshift, key);
7344 if (w32_modifiers & MOD_CONTROL)
7345 key = Fcons (Qctrl, key);
7346 if (w32_modifiers & MOD_ALT)
7347 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7348 if (w32_modifiers & MOD_WIN)
7349 key = Fcons (Qhyper, key);
7351 return key;
7354 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7355 Sw32_toggle_lock_key, 1, 2, 0,
7356 doc: /* Toggle the state of the lock key KEY.
7357 KEY can be `capslock', `kp-numlock', or `scroll'.
7358 If the optional parameter NEW-STATE is a number, then the state of KEY
7359 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
7360 (Lisp_Object key, Lisp_Object new_state)
7362 int vk_code;
7364 if (EQ (key, intern ("capslock")))
7365 vk_code = VK_CAPITAL;
7366 else if (EQ (key, intern ("kp-numlock")))
7367 vk_code = VK_NUMLOCK;
7368 else if (EQ (key, intern ("scroll")))
7369 vk_code = VK_SCROLL;
7370 else
7371 return Qnil;
7373 if (!dwWindowsThreadId)
7374 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7376 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7377 (WPARAM) vk_code, (LPARAM) XLI (new_state)))
7379 MSG msg;
7380 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7381 return make_number (msg.wParam);
7383 return Qnil;
7386 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7387 2, 2, 0,
7388 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7390 This is a direct interface to the Windows API FindWindow function. */)
7391 (Lisp_Object class, Lisp_Object name)
7393 HWND hnd;
7395 if (!NILP (class))
7396 CHECK_STRING (class);
7397 if (!NILP (name))
7398 CHECK_STRING (name);
7400 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7401 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7402 if (!hnd)
7403 return Qnil;
7404 return Qt;
7407 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7408 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7409 FRAME must be a live frame and defaults to the selected one.
7411 The boundary rectangle is a list of four elements, specifying the left,
7412 top, right and bottom screen coordinates of FRAME including menu and
7413 title bar and decorations. Optional argument CLIENT non-nil means to
7414 return the boundaries of the client rectangle which excludes menu and
7415 title bar and decorations. */)
7416 (Lisp_Object frame, Lisp_Object client)
7418 struct frame *f = decode_live_frame (frame);
7419 RECT rect;
7421 if (!NILP (client))
7422 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7423 else
7424 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7426 return list4 (make_number (rect.left), make_number (rect.top),
7427 make_number (rect.right), make_number (rect.bottom));
7430 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7431 doc: /* Get power status information from Windows system.
7433 The following %-sequences are provided:
7434 %L AC line status (verbose)
7435 %B Battery status (verbose)
7436 %b Battery status, empty means high, `-' means low,
7437 `!' means critical, and `+' means charging
7438 %p Battery load percentage
7439 %s Remaining time (to charge or discharge) in seconds
7440 %m Remaining time (to charge or discharge) in minutes
7441 %h Remaining time (to charge or discharge) in hours
7442 %t Remaining time (to charge or discharge) in the form `h:min' */)
7443 (void)
7445 Lisp_Object status = Qnil;
7447 SYSTEM_POWER_STATUS system_status;
7448 if (GetSystemPowerStatus (&system_status))
7450 Lisp_Object line_status, battery_status, battery_status_symbol;
7451 Lisp_Object load_percentage, seconds, minutes, hours, remain;
7453 long seconds_left = (long) system_status.BatteryLifeTime;
7455 if (system_status.ACLineStatus == 0)
7456 line_status = build_string ("off-line");
7457 else if (system_status.ACLineStatus == 1)
7458 line_status = build_string ("on-line");
7459 else
7460 line_status = build_string ("N/A");
7462 if (system_status.BatteryFlag & 128)
7464 battery_status = build_string ("N/A");
7465 battery_status_symbol = empty_unibyte_string;
7467 else if (system_status.BatteryFlag & 8)
7469 battery_status = build_string ("charging");
7470 battery_status_symbol = build_string ("+");
7471 if (system_status.BatteryFullLifeTime != -1L)
7472 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7474 else if (system_status.BatteryFlag & 4)
7476 battery_status = build_string ("critical");
7477 battery_status_symbol = build_string ("!");
7479 else if (system_status.BatteryFlag & 2)
7481 battery_status = build_string ("low");
7482 battery_status_symbol = build_string ("-");
7484 else if (system_status.BatteryFlag & 1)
7486 battery_status = build_string ("high");
7487 battery_status_symbol = empty_unibyte_string;
7489 else
7491 battery_status = build_string ("medium");
7492 battery_status_symbol = empty_unibyte_string;
7495 if (system_status.BatteryLifePercent > 100)
7496 load_percentage = build_string ("N/A");
7497 else
7499 char buffer[16];
7500 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
7501 load_percentage = build_string (buffer);
7504 if (seconds_left < 0)
7505 seconds = minutes = hours = remain = build_string ("N/A");
7506 else
7508 long m;
7509 float h;
7510 char buffer[16];
7511 snprintf (buffer, 16, "%ld", seconds_left);
7512 seconds = build_string (buffer);
7514 m = seconds_left / 60;
7515 snprintf (buffer, 16, "%ld", m);
7516 minutes = build_string (buffer);
7518 h = seconds_left / 3600.0;
7519 snprintf (buffer, 16, "%3.1f", h);
7520 hours = build_string (buffer);
7522 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
7523 remain = build_string (buffer);
7526 status = listn (CONSTYPE_HEAP, 8,
7527 Fcons (make_number ('L'), line_status),
7528 Fcons (make_number ('B'), battery_status),
7529 Fcons (make_number ('b'), battery_status_symbol),
7530 Fcons (make_number ('p'), load_percentage),
7531 Fcons (make_number ('s'), seconds),
7532 Fcons (make_number ('m'), minutes),
7533 Fcons (make_number ('h'), hours),
7534 Fcons (make_number ('t'), remain));
7536 return status;
7540 #ifdef WINDOWSNT
7541 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
7542 doc: /* Return storage information about the file system FILENAME is on.
7543 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7544 storage of the file system, FREE is the free storage, and AVAIL is the
7545 storage available to a non-superuser. All 3 numbers are in bytes.
7546 If the underlying system call fails, value is nil. */)
7547 (Lisp_Object filename)
7549 Lisp_Object encoded, value;
7551 CHECK_STRING (filename);
7552 filename = Fexpand_file_name (filename, Qnil);
7553 encoded = ENCODE_FILE (filename);
7555 value = Qnil;
7557 /* Determining the required information on Windows turns out, sadly,
7558 to be more involved than one would hope. The original Windows API
7559 call for this will return bogus information on some systems, but we
7560 must dynamically probe for the replacement api, since that was
7561 added rather late on. */
7563 HMODULE hKernel = GetModuleHandle ("kernel32");
7564 BOOL (WINAPI *pfn_GetDiskFreeSpaceExW)
7565 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7566 = GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7567 BOOL (WINAPI *pfn_GetDiskFreeSpaceExA)
7568 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7569 = GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
7570 bool have_pfn_GetDiskFreeSpaceEx =
7571 (w32_unicode_filenames && pfn_GetDiskFreeSpaceExW
7572 || !w32_unicode_filenames && pfn_GetDiskFreeSpaceExA);
7574 /* On Windows, we may need to specify the root directory of the
7575 volume holding FILENAME. */
7576 char rootname[MAX_UTF8_PATH];
7577 wchar_t rootname_w[MAX_PATH];
7578 char rootname_a[MAX_PATH];
7579 char *name = SDATA (encoded);
7580 BOOL result;
7582 /* find the root name of the volume if given */
7583 if (isalpha (name[0]) && name[1] == ':')
7585 rootname[0] = name[0];
7586 rootname[1] = name[1];
7587 rootname[2] = '\\';
7588 rootname[3] = 0;
7590 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7592 char *str = rootname;
7593 int slashes = 4;
7596 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7597 break;
7598 *str++ = *name++;
7600 while ( *name );
7602 *str++ = '\\';
7603 *str = 0;
7606 if (w32_unicode_filenames)
7607 filename_to_utf16 (rootname, rootname_w);
7608 else
7609 filename_to_ansi (rootname, rootname_a);
7611 if (have_pfn_GetDiskFreeSpaceEx)
7613 /* Unsigned large integers cannot be cast to double, so
7614 use signed ones instead. */
7615 LARGE_INTEGER availbytes;
7616 LARGE_INTEGER freebytes;
7617 LARGE_INTEGER totalbytes;
7619 if (w32_unicode_filenames)
7620 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7621 (ULARGE_INTEGER *)&availbytes,
7622 (ULARGE_INTEGER *)&totalbytes,
7623 (ULARGE_INTEGER *)&freebytes);
7624 else
7625 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7626 (ULARGE_INTEGER *)&availbytes,
7627 (ULARGE_INTEGER *)&totalbytes,
7628 (ULARGE_INTEGER *)&freebytes);
7629 if (result)
7630 value = list3 (make_float ((double) totalbytes.QuadPart),
7631 make_float ((double) freebytes.QuadPart),
7632 make_float ((double) availbytes.QuadPart));
7634 else
7636 DWORD sectors_per_cluster;
7637 DWORD bytes_per_sector;
7638 DWORD free_clusters;
7639 DWORD total_clusters;
7641 if (w32_unicode_filenames)
7642 result = GetDiskFreeSpaceW (rootname_w,
7643 &sectors_per_cluster,
7644 &bytes_per_sector,
7645 &free_clusters,
7646 &total_clusters);
7647 else
7648 result = GetDiskFreeSpaceA (rootname_a,
7649 &sectors_per_cluster,
7650 &bytes_per_sector,
7651 &free_clusters,
7652 &total_clusters);
7653 if (result)
7654 value = list3 (make_float ((double) total_clusters
7655 * sectors_per_cluster * bytes_per_sector),
7656 make_float ((double) free_clusters
7657 * sectors_per_cluster * bytes_per_sector),
7658 make_float ((double) free_clusters
7659 * sectors_per_cluster * bytes_per_sector));
7663 return value;
7665 #endif /* WINDOWSNT */
7668 #ifdef WINDOWSNT
7669 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7670 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
7671 (void)
7673 static char pname_buf[256];
7674 int err;
7675 HANDLE hPrn;
7676 PRINTER_INFO_2W *ppi2w = NULL;
7677 PRINTER_INFO_2A *ppi2a = NULL;
7678 DWORD dwNeeded = 0, dwReturned = 0;
7679 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7680 char port_name[MAX_UTF8_PATH];
7682 /* Retrieve the default string from Win.ini (the registry).
7683 * String will be in form "printername,drivername,portname".
7684 * This is the most portable way to get the default printer. */
7685 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7686 return Qnil;
7687 /* printername precedes first "," character */
7688 strtok (pname_buf, ",");
7689 /* We want to know more than the printer name */
7690 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7691 return Qnil;
7692 /* GetPrinterW is not supported by unicows.dll. */
7693 if (w32_unicode_filenames && os_subtype != OS_9X)
7694 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7695 else
7696 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
7697 if (dwNeeded == 0)
7699 ClosePrinter (hPrn);
7700 return Qnil;
7702 /* Call GetPrinter again with big enough memory block. */
7703 if (w32_unicode_filenames && os_subtype != OS_9X)
7705 /* Allocate memory for the PRINTER_INFO_2 struct. */
7706 ppi2w = xmalloc (dwNeeded);
7707 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
7708 ClosePrinter (hPrn);
7709 if (!err)
7711 xfree (ppi2w);
7712 return Qnil;
7715 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7716 && ppi2w->pServerName)
7718 filename_from_utf16 (ppi2w->pServerName, server_name);
7719 filename_from_utf16 (ppi2w->pShareName, share_name);
7721 else
7723 server_name[0] = '\0';
7724 filename_from_utf16 (ppi2w->pPortName, port_name);
7727 else
7729 ppi2a = xmalloc (dwNeeded);
7730 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7731 ClosePrinter (hPrn);
7732 if (!err)
7734 xfree (ppi2a);
7735 return Qnil;
7738 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7739 && ppi2a->pServerName)
7741 filename_from_ansi (ppi2a->pServerName, server_name);
7742 filename_from_ansi (ppi2a->pShareName, share_name);
7744 else
7746 server_name[0] = '\0';
7747 filename_from_ansi (ppi2a->pPortName, port_name);
7751 if (server_name[0])
7753 /* a remote printer */
7754 if (server_name[0] == '\\')
7755 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7756 share_name);
7757 else
7758 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7759 share_name);
7760 pname_buf[sizeof (pname_buf) - 1] = '\0';
7762 else
7764 /* a local printer */
7765 strncpy (pname_buf, port_name, sizeof (pname_buf));
7766 pname_buf[sizeof (pname_buf) - 1] = '\0';
7767 /* `pPortName' can include several ports, delimited by ','.
7768 * we only use the first one. */
7769 strtok (pname_buf, ",");
7772 return DECODE_FILE (build_unibyte_string (pname_buf));
7774 #endif /* WINDOWSNT */
7777 /* Equivalent of strerror for W32 error codes. */
7778 char *
7779 w32_strerror (int error_no)
7781 static char buf[500];
7782 DWORD ret;
7784 if (error_no == 0)
7785 error_no = GetLastError ();
7787 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7788 FORMAT_MESSAGE_IGNORE_INSERTS,
7789 NULL,
7790 error_no,
7791 0, /* choose most suitable language */
7792 buf, sizeof (buf), NULL);
7794 while (ret > 0 && (buf[ret - 1] == '\n' ||
7795 buf[ret - 1] == '\r' ))
7796 --ret;
7797 buf[ret] = '\0';
7798 if (!ret)
7799 sprintf (buf, "w32 error %u", error_no);
7801 return buf;
7804 /* For convenience when debugging. (You cannot call GetLastError
7805 directly from GDB: it will crash, because it uses the __stdcall
7806 calling convention, not the _cdecl convention assumed by GDB.) */
7807 DWORD
7808 w32_last_error (void)
7810 return GetLastError ();
7813 /* Cache information describing the NT system for later use. */
7814 void
7815 cache_system_info (void)
7817 union
7819 struct info
7821 char major;
7822 char minor;
7823 short platform;
7824 } info;
7825 DWORD data;
7826 } version;
7828 /* Cache the module handle of Emacs itself. */
7829 hinst = GetModuleHandle (NULL);
7831 /* Cache the version of the operating system. */
7832 version.data = GetVersion ();
7833 w32_major_version = version.info.major;
7834 w32_minor_version = version.info.minor;
7836 if (version.info.platform & 0x8000)
7837 os_subtype = OS_9X;
7838 else
7839 os_subtype = OS_NT;
7841 /* Cache page size, allocation unit, processor type, etc. */
7842 GetSystemInfo (&sysinfo_cache);
7843 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
7845 /* Cache os info. */
7846 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7847 GetVersionEx (&osinfo_cache);
7849 w32_build_number = osinfo_cache.dwBuildNumber;
7850 if (os_subtype == OS_9X)
7851 w32_build_number &= 0xffff;
7853 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
7856 #ifdef EMACSDEBUG
7857 void
7858 _DebPrint (const char *fmt, ...)
7860 char buf[1024];
7861 va_list args;
7863 va_start (args, fmt);
7864 vsprintf (buf, fmt, args);
7865 va_end (args);
7866 #if CYGWIN
7867 fprintf (stderr, "%s", buf);
7868 #endif
7869 OutputDebugString (buf);
7871 #endif
7874 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
7876 int cur_state = (GetKeyState (vk_code) & 1);
7878 if (NILP (new_state)
7879 || (NUMBERP (new_state)
7880 && ((XUINT (new_state)) & 1) != cur_state))
7882 #ifdef WINDOWSNT
7883 faked_key = vk_code;
7884 #endif /* WINDOWSNT */
7886 keybd_event ((BYTE) vk_code,
7887 (BYTE) MapVirtualKey (vk_code, 0),
7888 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7889 keybd_event ((BYTE) vk_code,
7890 (BYTE) MapVirtualKey (vk_code, 0),
7891 KEYEVENTF_EXTENDEDKEY | 0, 0);
7892 keybd_event ((BYTE) vk_code,
7893 (BYTE) MapVirtualKey (vk_code, 0),
7894 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7895 cur_state = !cur_state;
7898 return cur_state;
7901 /* Translate console modifiers to emacs modifiers.
7902 German keyboard support (Kai Morgan Zeise 2/18/95). */
7904 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
7906 int retval = 0;
7908 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
7909 pressed, first remove those modifiers. */
7910 if (!NILP (Vw32_recognize_altgr)
7911 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7912 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7913 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
7915 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
7916 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
7918 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7920 retval |= ctrl_modifier;
7921 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7922 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7923 retval |= meta_modifier;
7926 if (mods & LEFT_WIN_PRESSED)
7927 retval |= w32_key_to_modifier (VK_LWIN);
7928 if (mods & RIGHT_WIN_PRESSED)
7929 retval |= w32_key_to_modifier (VK_RWIN);
7930 if (mods & APPS_PRESSED)
7931 retval |= w32_key_to_modifier (VK_APPS);
7932 if (mods & SCROLLLOCK_ON)
7933 retval |= w32_key_to_modifier (VK_SCROLL);
7935 /* Just in case someone wanted the original behavior, make it
7936 optional by setting w32-capslock-is-shiftlock to t. */
7937 if (NILP (Vw32_capslock_is_shiftlock)
7938 /* Keys that should _not_ be affected by CapsLock. */
7939 && ( (key == VK_BACK)
7940 || (key == VK_TAB)
7941 || (key == VK_CLEAR)
7942 || (key == VK_RETURN)
7943 || (key == VK_ESCAPE)
7944 || ((key >= VK_SPACE) && (key <= VK_HELP))
7945 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
7946 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
7949 /* Only consider shift state. */
7950 if ((mods & SHIFT_PRESSED) != 0)
7951 retval |= shift_modifier;
7953 else
7955 /* Ignore CapsLock state if not enabled. */
7956 if (NILP (Vw32_enable_caps_lock))
7957 mods &= ~CAPSLOCK_ON;
7958 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
7959 retval |= shift_modifier;
7962 return retval;
7965 /* The return code indicates key code size. cpID is the codepage to
7966 use for translation to Unicode; -1 means use the current console
7967 input codepage. */
7969 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
7971 unsigned int key_code = event->wVirtualKeyCode;
7972 unsigned int mods = event->dwControlKeyState;
7973 BYTE keystate[256];
7974 static BYTE ansi_code[4];
7975 static int isdead = 0;
7977 if (isdead == 2)
7979 event->uChar.AsciiChar = ansi_code[2];
7980 isdead = 0;
7981 return 1;
7983 if (event->uChar.AsciiChar != 0)
7984 return 1;
7986 memset (keystate, 0, sizeof (keystate));
7987 keystate[key_code] = 0x80;
7988 if (mods & SHIFT_PRESSED)
7989 keystate[VK_SHIFT] = 0x80;
7990 if (mods & CAPSLOCK_ON)
7991 keystate[VK_CAPITAL] = 1;
7992 /* If we recognize right-alt and left-ctrl as AltGr, set the key
7993 states accordingly before invoking ToAscii. */
7994 if (!NILP (Vw32_recognize_altgr)
7995 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
7997 keystate[VK_CONTROL] = 0x80;
7998 keystate[VK_LCONTROL] = 0x80;
7999 keystate[VK_MENU] = 0x80;
8000 keystate[VK_RMENU] = 0x80;
8003 #if 0
8004 /* Because of an OS bug, ToAscii corrupts the stack when called to
8005 convert a dead key in console mode on NT4. Unfortunately, trying
8006 to check for dead keys using MapVirtualKey doesn't work either -
8007 these functions apparently use internal information about keyboard
8008 layout which doesn't get properly updated in console programs when
8009 changing layout (though apparently it gets partly updated,
8010 otherwise ToAscii wouldn't crash). */
8011 if (is_dead_key (event->wVirtualKeyCode))
8012 return 0;
8013 #endif
8015 /* On NT, call ToUnicode instead and then convert to the current
8016 console input codepage. */
8017 if (os_subtype == OS_NT)
8019 WCHAR buf[128];
8021 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
8022 keystate, buf, 128, 0);
8023 if (isdead > 0)
8025 /* When we are called from the GUI message processing code,
8026 we are passed the current keyboard codepage, a positive
8027 number, to use below. */
8028 if (cpId == -1)
8029 cpId = GetConsoleCP ();
8031 event->uChar.UnicodeChar = buf[isdead - 1];
8032 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
8033 ansi_code, 4, NULL, NULL);
8035 else
8036 isdead = 0;
8038 else
8040 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
8041 keystate, (LPWORD) ansi_code, 0);
8044 if (isdead == 0)
8045 return 0;
8046 event->uChar.AsciiChar = ansi_code[0];
8047 return isdead;
8051 void
8052 w32_sys_ring_bell (struct frame *f)
8054 if (sound_type == 0xFFFFFFFF)
8056 Beep (666, 100);
8058 else if (sound_type == MB_EMACS_SILENT)
8060 /* Do nothing. */
8062 else
8063 MessageBeep (sound_type);
8066 DEFUN ("w32--menu-bar-in-use", Fw32__menu_bar_in_use, Sw32__menu_bar_in_use,
8067 0, 0, 0,
8068 doc: /* Return non-nil when a menu-bar menu is being used.
8069 Internal use only. */)
8070 (void)
8072 return menubar_in_use ? Qt : Qnil;
8076 /***********************************************************************
8077 Initialization
8078 ***********************************************************************/
8080 /* Keep this list in the same order as frame_parms in frame.c.
8081 Use 0 for unsupported frame parameters. */
8083 frame_parm_handler w32_frame_parm_handlers[] =
8085 x_set_autoraise,
8086 x_set_autolower,
8087 x_set_background_color,
8088 x_set_border_color,
8089 x_set_border_width,
8090 x_set_cursor_color,
8091 x_set_cursor_type,
8092 x_set_font,
8093 x_set_foreground_color,
8094 x_set_icon_name,
8095 x_set_icon_type,
8096 x_set_internal_border_width,
8097 x_set_right_divider_width,
8098 x_set_bottom_divider_width,
8099 x_set_menu_bar_lines,
8100 x_set_mouse_color,
8101 x_explicitly_set_name,
8102 x_set_scroll_bar_width,
8103 x_set_title,
8104 x_set_unsplittable,
8105 x_set_vertical_scroll_bars,
8106 x_set_visibility,
8107 x_set_tool_bar_lines,
8108 0, /* x_set_scroll_bar_foreground, */
8109 0, /* x_set_scroll_bar_background, */
8110 x_set_screen_gamma,
8111 x_set_line_spacing,
8112 x_set_fringe_width,
8113 x_set_fringe_width,
8114 0, /* x_set_wait_for_wm, */
8115 x_set_fullscreen,
8116 x_set_font_backend,
8117 x_set_alpha,
8118 0, /* x_set_sticky */
8119 0, /* x_set_tool_bar_position */
8122 void
8123 syms_of_w32fns (void)
8125 globals_of_w32fns ();
8126 track_mouse_window = NULL;
8128 w32_visible_system_caret_hwnd = NULL;
8130 DEFSYM (Qsuppress_icon, "suppress-icon");
8131 DEFSYM (Qundefined_color, "undefined-color");
8132 DEFSYM (Qcancel_timer, "cancel-timer");
8133 DEFSYM (Qhyper, "hyper");
8134 DEFSYM (Qsuper, "super");
8135 DEFSYM (Qmeta, "meta");
8136 DEFSYM (Qalt, "alt");
8137 DEFSYM (Qctrl, "ctrl");
8138 DEFSYM (Qcontrol, "control");
8139 DEFSYM (Qshift, "shift");
8140 DEFSYM (Qfont_param, "font-parameter");
8141 DEFSYM (Qgeometry, "geometry");
8142 DEFSYM (Qworkarea, "workarea");
8143 DEFSYM (Qmm_size, "mm-size");
8144 DEFSYM (Qframes, "frames");
8145 /* This is the end of symbol initialization. */
8148 Fput (Qundefined_color, Qerror_conditions,
8149 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8150 Fput (Qundefined_color, Qerror_message,
8151 build_pure_c_string ("Undefined color"));
8153 staticpro (&w32_grabbed_keys);
8154 w32_grabbed_keys = Qnil;
8156 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8157 doc: /* An array of color name mappings for Windows. */);
8158 Vw32_color_map = Qnil;
8160 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8161 doc: /* Non-nil if Alt key presses are passed on to Windows.
8162 When non-nil, for example, Alt pressed and released and then space will
8163 open the System menu. When nil, Emacs processes the Alt key events, and
8164 then silently swallows them. */);
8165 Vw32_pass_alt_to_system = Qnil;
8167 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8168 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8169 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8170 Vw32_alt_is_meta = Qt;
8172 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8173 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8174 w32_quit_key = 0;
8176 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8177 Vw32_pass_lwindow_to_system,
8178 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8180 When non-nil, the Start menu is opened by tapping the key.
8181 If you set this to nil, the left \"Windows\" key is processed by Emacs
8182 according to the value of `w32-lwindow-modifier', which see.
8184 Note that some combinations of the left \"Windows\" key with other keys are
8185 caught by Windows at low level, and so binding them in Emacs will have no
8186 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8187 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8188 the doc string of `w32-phantom-key-code'. */);
8189 Vw32_pass_lwindow_to_system = Qt;
8191 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8192 Vw32_pass_rwindow_to_system,
8193 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8195 When non-nil, the Start menu is opened by tapping the key.
8196 If you set this to nil, the right \"Windows\" key is processed by Emacs
8197 according to the value of `w32-rwindow-modifier', which see.
8199 Note that some combinations of the right \"Windows\" key with other keys are
8200 caught by Windows at low level, and so binding them in Emacs will have no
8201 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8202 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8203 the doc string of `w32-phantom-key-code'. */);
8204 Vw32_pass_rwindow_to_system = Qt;
8206 DEFVAR_LISP ("w32-phantom-key-code",
8207 Vw32_phantom_key_code,
8208 doc: /* Virtual key code used to generate \"phantom\" key presses.
8209 Value is a number between 0 and 255.
8211 Phantom key presses are generated in order to stop the system from
8212 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8213 `w32-pass-rwindow-to-system' is nil. */);
8214 /* Although 255 is technically not a valid key code, it works and
8215 means that this hack won't interfere with any real key code. */
8216 XSETINT (Vw32_phantom_key_code, 255);
8218 DEFVAR_LISP ("w32-enable-num-lock",
8219 Vw32_enable_num_lock,
8220 doc: /* If non-nil, the Num Lock key acts normally.
8221 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8222 Vw32_enable_num_lock = Qt;
8224 DEFVAR_LISP ("w32-enable-caps-lock",
8225 Vw32_enable_caps_lock,
8226 doc: /* If non-nil, the Caps Lock key acts normally.
8227 Set to nil to handle Caps Lock as the `capslock' key. */);
8228 Vw32_enable_caps_lock = Qt;
8230 DEFVAR_LISP ("w32-scroll-lock-modifier",
8231 Vw32_scroll_lock_modifier,
8232 doc: /* Modifier to use for the Scroll Lock ON state.
8233 The value can be hyper, super, meta, alt, control or shift for the
8234 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8235 Any other value will cause the Scroll Lock key to be ignored. */);
8236 Vw32_scroll_lock_modifier = Qnil;
8238 DEFVAR_LISP ("w32-lwindow-modifier",
8239 Vw32_lwindow_modifier,
8240 doc: /* Modifier to use for the left \"Windows\" key.
8241 The value can be hyper, super, meta, alt, control or shift for the
8242 respective modifier, or nil to appear as the `lwindow' key.
8243 Any other value will cause the key to be ignored. */);
8244 Vw32_lwindow_modifier = Qnil;
8246 DEFVAR_LISP ("w32-rwindow-modifier",
8247 Vw32_rwindow_modifier,
8248 doc: /* Modifier to use for the right \"Windows\" key.
8249 The value can be hyper, super, meta, alt, control or shift for the
8250 respective modifier, or nil to appear as the `rwindow' key.
8251 Any other value will cause the key to be ignored. */);
8252 Vw32_rwindow_modifier = Qnil;
8254 DEFVAR_LISP ("w32-apps-modifier",
8255 Vw32_apps_modifier,
8256 doc: /* Modifier to use for the \"Apps\" key.
8257 The value can be hyper, super, meta, alt, control or shift for the
8258 respective modifier, or nil to appear as the `apps' key.
8259 Any other value will cause the key to be ignored. */);
8260 Vw32_apps_modifier = Qnil;
8262 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
8263 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8264 w32_enable_synthesized_fonts = 0;
8266 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
8267 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8268 Vw32_enable_palette = Qt;
8270 DEFVAR_INT ("w32-mouse-button-tolerance",
8271 w32_mouse_button_tolerance,
8272 doc: /* Analogue of double click interval for faking middle mouse events.
8273 The value is the minimum time in milliseconds that must elapse between
8274 left and right button down events before they are considered distinct events.
8275 If both mouse buttons are depressed within this interval, a middle mouse
8276 button down event is generated instead. */);
8277 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8279 DEFVAR_INT ("w32-mouse-move-interval",
8280 w32_mouse_move_interval,
8281 doc: /* Minimum interval between mouse move events.
8282 The value is the minimum time in milliseconds that must elapse between
8283 successive mouse move (or scroll bar drag) events before they are
8284 reported as lisp events. */);
8285 w32_mouse_move_interval = 0;
8287 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8288 w32_pass_extra_mouse_buttons_to_system,
8289 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8290 Recent versions of Windows support mice with up to five buttons.
8291 Since most applications don't support these extra buttons, most mouse
8292 drivers will allow you to map them to functions at the system level.
8293 If this variable is non-nil, Emacs will pass them on, allowing the
8294 system to handle them. */);
8295 w32_pass_extra_mouse_buttons_to_system = 0;
8297 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8298 w32_pass_multimedia_buttons_to_system,
8299 doc: /* If non-nil, media buttons are passed to Windows.
8300 Some modern keyboards contain buttons for controlling media players, web
8301 browsers and other applications. Generally these buttons are handled on a
8302 system wide basis, but by setting this to nil they are made available
8303 to Emacs for binding. Depending on your keyboard, additional keys that
8304 may be available are:
8306 browser-back, browser-forward, browser-refresh, browser-stop,
8307 browser-search, browser-favorites, browser-home,
8308 mail, mail-reply, mail-forward, mail-send,
8309 app-1, app-2,
8310 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8311 spell-check, correction-list, toggle-dictate-command,
8312 media-next, media-previous, media-stop, media-play-pause, media-select,
8313 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8314 media-channel-up, media-channel-down,
8315 volume-mute, volume-up, volume-down,
8316 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8317 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8318 w32_pass_multimedia_buttons_to_system = 1;
8320 #if 0 /* TODO: Mouse cursor customization. */
8321 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
8322 doc: /* The shape of the pointer when over text.
8323 Changing the value does not affect existing frames
8324 unless you set the mouse color. */);
8325 Vx_pointer_shape = Qnil;
8327 Vx_nontext_pointer_shape = Qnil;
8329 Vx_mode_pointer_shape = Qnil;
8331 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
8332 doc: /* The shape of the pointer when Emacs is busy.
8333 This variable takes effect when you create a new frame
8334 or when you set the mouse color. */);
8335 Vx_hourglass_pointer_shape = Qnil;
8337 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8338 Vx_sensitive_text_pointer_shape,
8339 doc: /* The shape of the pointer when over mouse-sensitive text.
8340 This variable takes effect when you create a new frame
8341 or when you set the mouse color. */);
8342 Vx_sensitive_text_pointer_shape = Qnil;
8344 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8345 Vx_window_horizontal_drag_shape,
8346 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8347 This variable takes effect when you create a new frame
8348 or when you set the mouse color. */);
8349 Vx_window_horizontal_drag_shape = Qnil;
8351 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8352 Vx_window_vertical_drag_shape,
8353 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8354 This variable takes effect when you create a new frame
8355 or when you set the mouse color. */);
8356 Vx_window_vertical_drag_shape = Qnil;
8357 #endif
8359 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
8360 doc: /* A string indicating the foreground color of the cursor box. */);
8361 Vx_cursor_fore_pixel = Qnil;
8363 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
8364 doc: /* Maximum size for tooltips.
8365 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8366 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8368 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
8369 doc: /* Non-nil if no window manager is in use.
8370 Emacs doesn't try to figure this out; this is always nil
8371 unless you set it to something else. */);
8372 /* We don't have any way to find this out, so set it to nil
8373 and maybe the user would like to set it to t. */
8374 Vx_no_window_manager = Qnil;
8376 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8377 Vx_pixel_size_width_font_regexp,
8378 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8380 Since Emacs gets width of a font matching with this regexp from
8381 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8382 such a font. This is especially effective for such large fonts as
8383 Chinese, Japanese, and Korean. */);
8384 Vx_pixel_size_width_font_regexp = Qnil;
8386 DEFVAR_LISP ("w32-bdf-filename-alist",
8387 Vw32_bdf_filename_alist,
8388 doc: /* List of bdf fonts and their corresponding filenames. */);
8389 Vw32_bdf_filename_alist = Qnil;
8391 DEFVAR_BOOL ("w32-strict-fontnames",
8392 w32_strict_fontnames,
8393 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8394 Default is nil, which allows old fontnames that are not XLFD compliant,
8395 and allows third-party CJK display to work by specifying false charset
8396 fields to trick Emacs into translating to Big5, SJIS etc.
8397 Setting this to t will prevent wrong fonts being selected when
8398 fontsets are automatically created. */);
8399 w32_strict_fontnames = 0;
8401 DEFVAR_BOOL ("w32-strict-painting",
8402 w32_strict_painting,
8403 doc: /* Non-nil means use strict rules for repainting frames.
8404 Set this to nil to get the old behavior for repainting; this should
8405 only be necessary if the default setting causes problems. */);
8406 w32_strict_painting = 1;
8408 #if 0 /* TODO: Port to W32 */
8409 defsubr (&Sx_change_window_property);
8410 defsubr (&Sx_delete_window_property);
8411 defsubr (&Sx_window_property);
8412 #endif
8413 defsubr (&Sxw_display_color_p);
8414 defsubr (&Sx_display_grayscale_p);
8415 defsubr (&Sxw_color_defined_p);
8416 defsubr (&Sxw_color_values);
8417 defsubr (&Sx_server_max_request_size);
8418 defsubr (&Sx_server_vendor);
8419 defsubr (&Sx_server_version);
8420 defsubr (&Sx_display_pixel_width);
8421 defsubr (&Sx_display_pixel_height);
8422 defsubr (&Sx_display_mm_width);
8423 defsubr (&Sx_display_mm_height);
8424 defsubr (&Sx_display_screens);
8425 defsubr (&Sx_display_planes);
8426 defsubr (&Sx_display_color_cells);
8427 defsubr (&Sx_display_visual_class);
8428 defsubr (&Sx_display_backing_store);
8429 defsubr (&Sx_display_save_under);
8430 defsubr (&Sx_create_frame);
8431 defsubr (&Sx_open_connection);
8432 defsubr (&Sx_close_connection);
8433 defsubr (&Sx_display_list);
8434 defsubr (&Sx_synchronize);
8436 /* W32 specific functions */
8438 defsubr (&Sw32_define_rgb_color);
8439 defsubr (&Sw32_default_color_map);
8440 defsubr (&Sw32_display_monitor_attributes_list);
8441 defsubr (&Sw32_send_sys_command);
8442 defsubr (&Sw32_shell_execute);
8443 defsubr (&Sw32_register_hot_key);
8444 defsubr (&Sw32_unregister_hot_key);
8445 defsubr (&Sw32_registered_hot_keys);
8446 defsubr (&Sw32_reconstruct_hot_key);
8447 defsubr (&Sw32_toggle_lock_key);
8448 defsubr (&Sw32_window_exists_p);
8449 defsubr (&Sw32_frame_rect);
8450 defsubr (&Sw32_battery_status);
8451 defsubr (&Sw32__menu_bar_in_use);
8453 #ifdef WINDOWSNT
8454 defsubr (&Sfile_system_info);
8455 defsubr (&Sdefault_printer_name);
8456 #endif
8458 defsubr (&Sset_message_beep);
8460 hourglass_hwnd = NULL;
8462 defsubr (&Sx_show_tip);
8463 defsubr (&Sx_hide_tip);
8464 tip_timer = Qnil;
8465 staticpro (&tip_timer);
8466 tip_frame = Qnil;
8467 staticpro (&tip_frame);
8469 last_show_tip_args = Qnil;
8470 staticpro (&last_show_tip_args);
8472 defsubr (&Sx_file_dialog);
8473 #ifdef WINDOWSNT
8474 defsubr (&Ssystem_move_file_to_trash);
8475 #endif
8480 /* Crashing and reporting backtrace. */
8482 #ifndef CYGWIN
8483 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8484 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8485 #endif
8486 static DWORD except_code;
8487 static PVOID except_addr;
8489 #ifndef CYGWIN
8490 /* This handler records the exception code and the address where it
8491 was triggered so that this info could be included in the backtrace.
8492 Without that, the backtrace in some cases has no information
8493 whatsoever about the offending code, and looks as if the top-level
8494 exception handler in the MinGW startup code di the one that
8495 crashed. */
8496 static LONG CALLBACK
8497 my_exception_handler (EXCEPTION_POINTERS * exception_data)
8499 except_code = exception_data->ExceptionRecord->ExceptionCode;
8500 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8502 if (prev_exception_handler)
8503 return prev_exception_handler (exception_data);
8504 return EXCEPTION_EXECUTE_HANDLER;
8506 #endif
8508 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8509 PULONG);
8511 #define BACKTRACE_LIMIT_MAX 62
8514 w32_backtrace (void **buffer, int limit)
8516 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8517 HMODULE hm_kernel32 = NULL;
8519 if (!s_pfn_CaptureStackBackTrace)
8521 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8522 s_pfn_CaptureStackBackTrace =
8523 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8524 "RtlCaptureStackBackTrace");
8526 if (s_pfn_CaptureStackBackTrace)
8527 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8528 buffer, NULL);
8529 return 0;
8532 void
8533 emacs_abort (void)
8535 int button;
8536 button = MessageBox (NULL,
8537 "A fatal error has occurred!\n\n"
8538 "Would you like to attach a debugger?\n\n"
8539 "Select:\n"
8540 "YES -- to debug Emacs, or\n"
8541 "NO -- to abort Emacs and produce a backtrace\n"
8542 " (emacs_backtrace.txt in current directory)."
8543 #if __GNUC__
8544 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8545 "\"continue\" inside GDB before clicking YES.)"
8546 #endif
8547 , "Emacs Abort Dialog",
8548 MB_ICONEXCLAMATION | MB_TASKMODAL
8549 | MB_SETFOREGROUND | MB_YESNO);
8550 switch (button)
8552 case IDYES:
8553 DebugBreak ();
8554 exit (2); /* tell the compiler we will never return */
8555 case IDNO:
8556 default:
8558 void *stack[BACKTRACE_LIMIT_MAX + 1];
8559 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8561 if (i)
8563 int errfile_fd = -1;
8564 int j;
8565 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
8566 /* The type below should really be 'void *', but
8567 INT_BUFSIZE_BOUND cannot handle that without
8568 triggering compiler warnings (under certain
8569 pedantic warning switches), it wants an
8570 integer type. */
8571 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
8572 #ifdef CYGWIN
8573 int stderr_fd = 2;
8574 #else
8575 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
8576 int stderr_fd = -1;
8578 if (errout && errout != INVALID_HANDLE_VALUE)
8579 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
8580 #endif
8582 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8583 but not on Windows 7. addr2line doesn't mind a missing
8584 "0x", but will be confused by an extra one. */
8585 if (except_addr)
8586 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8587 except_code, except_addr);
8588 if (stderr_fd >= 0)
8590 if (except_addr)
8591 write (stderr_fd, buf, strlen (buf));
8592 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8594 #ifdef CYGWIN
8595 #define _open open
8596 #endif
8597 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8598 if (errfile_fd >= 0)
8600 lseek (errfile_fd, 0L, SEEK_END);
8601 if (except_addr)
8602 write (errfile_fd, buf, strlen (buf));
8603 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8606 for (j = 0; j < i; j++)
8608 /* stack[] gives the return addresses, whereas we want
8609 the address of the call, so decrease each address
8610 by approximate size of 1 CALL instruction. */
8611 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
8612 if (stderr_fd >= 0)
8613 write (stderr_fd, buf, strlen (buf));
8614 if (errfile_fd >= 0)
8615 write (errfile_fd, buf, strlen (buf));
8617 if (i == BACKTRACE_LIMIT_MAX)
8619 if (stderr_fd >= 0)
8620 write (stderr_fd, "...\r\n", 5);
8621 if (errfile_fd >= 0)
8622 write (errfile_fd, "...\r\n", 5);
8624 if (errfile_fd >= 0)
8625 close (errfile_fd);
8627 abort ();
8628 break;
8635 /* Initialization. */
8638 globals_of_w32fns is used to initialize those global variables that
8639 must always be initialized on startup even when the global variable
8640 initialized is non zero (see the function main in emacs.c).
8641 globals_of_w32fns is called from syms_of_w32fns when the global
8642 variable initialized is 0 and directly from main when initialized
8643 is non zero.
8645 void
8646 globals_of_w32fns (void)
8648 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8650 TrackMouseEvent not available in all versions of Windows, so must load
8651 it dynamically. Do it once, here, instead of every time it is used.
8653 track_mouse_event_fn = (TrackMouseEvent_Proc)
8654 GetProcAddress (user32_lib, "TrackMouseEvent");
8656 monitor_from_point_fn = (MonitorFromPoint_Proc)
8657 GetProcAddress (user32_lib, "MonitorFromPoint");
8658 get_monitor_info_fn = (GetMonitorInfo_Proc)
8659 GetProcAddress (user32_lib, "GetMonitorInfoA");
8660 monitor_from_window_fn = (MonitorFromWindow_Proc)
8661 GetProcAddress (user32_lib, "MonitorFromWindow");
8662 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8663 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8666 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8667 get_composition_string_fn = (ImmGetCompositionString_Proc)
8668 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8669 get_ime_context_fn = (ImmGetContext_Proc)
8670 GetProcAddress (imm32_lib, "ImmGetContext");
8671 release_ime_context_fn = (ImmReleaseContext_Proc)
8672 GetProcAddress (imm32_lib, "ImmReleaseContext");
8673 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8674 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8677 except_code = 0;
8678 except_addr = 0;
8679 #ifndef CYGWIN
8680 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8681 #endif
8683 DEFVAR_INT ("w32-ansi-code-page",
8684 w32_ansi_code_page,
8685 doc: /* The ANSI code page used by the system. */);
8686 w32_ansi_code_page = GetACP ();
8688 if (os_subtype == OS_NT)
8689 w32_unicode_gui = 1;
8690 else
8691 w32_unicode_gui = 0;
8693 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8694 InitCommonControls ();
8696 syms_of_w32uniscribe ();
8699 #ifdef NTGUI_UNICODE
8701 Lisp_Object
8702 ntgui_encode_system (Lisp_Object str)
8704 Lisp_Object encoded;
8705 to_unicode (str, &encoded);
8706 return encoded;
8709 #endif /* NTGUI_UNICODE */