* make-docfile.c: Simplify a bit, to simplify further refactoring.
[emacs.git] / src / w32fns.c
blobb76c81fdf1fb92c856b37d5e72491f06012c422b
1 /* Graphical user interface functions for the Microsoft Windows API.
3 Copyright (C) 1989, 1992-2014 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20 /* Added by Kevin Gallo */
22 #include <config.h>
24 #include <signal.h>
25 #include <stdio.h>
26 #include <limits.h>
27 #include <errno.h>
28 #include <math.h>
29 #include <fcntl.h>
30 #include <unistd.h>
32 #include "lisp.h"
33 #include "w32term.h"
34 #include "frame.h"
35 #include "window.h"
36 #include "character.h"
37 #include "buffer.h"
38 #include "intervals.h"
39 #include "dispextern.h"
40 #include "keyboard.h"
41 #include "blockinput.h"
42 #include "epaths.h"
43 #include "charset.h"
44 #include "coding.h"
45 #include "ccl.h"
46 #include "fontset.h"
47 #include "systime.h"
48 #include "termhooks.h"
50 #include "w32common.h"
52 #ifdef WINDOWSNT
53 #include "w32heap.h"
54 #include <mbstring.h>
55 #endif /* WINDOWSNT */
57 #if CYGWIN
58 #include "cygw32.h"
59 #else
60 #include "w32.h"
61 #endif
63 #include "bitmaps/gray.xbm"
65 #include <commctrl.h>
66 #include <commdlg.h>
67 #include <shellapi.h>
68 #include <ctype.h>
69 #include <winspool.h>
70 #include <objbase.h>
72 #include <dlgs.h>
73 #include <imm.h>
75 #include "font.h"
76 #include "w32font.h"
78 #ifndef FOF_NO_CONNECTED_ELEMENTS
79 #define FOF_NO_CONNECTED_ELEMENTS 0x2000
80 #endif
82 void syms_of_w32fns (void);
83 void globals_of_w32fns (void);
85 extern void free_frame_menubar (struct frame *);
86 extern int w32_console_toggle_lock_key (int, Lisp_Object);
87 extern void w32_menu_display_help (HWND, HMENU, UINT, UINT);
88 extern void w32_free_menu_strings (HWND);
89 extern const char *map_w32_filename (const char *, const char **);
90 extern char * w32_strerror (int error_no);
92 #ifndef IDC_HAND
93 #define IDC_HAND MAKEINTRESOURCE(32649)
94 #endif
96 Lisp_Object Qundefined_color;
97 Lisp_Object Qcancel_timer;
98 Lisp_Object Qfont_param;
99 Lisp_Object Qhyper;
100 Lisp_Object Qsuper;
101 Lisp_Object Qmeta;
102 Lisp_Object Qalt;
103 Lisp_Object Qctrl;
104 Lisp_Object Qcontrol;
105 Lisp_Object Qshift;
106 static Lisp_Object Qgeometry, Qworkarea, Qmm_size, Qframes;
109 /* Prefix for system colors. */
110 #define SYSTEM_COLOR_PREFIX "System"
111 #define SYSTEM_COLOR_PREFIX_LEN (sizeof (SYSTEM_COLOR_PREFIX) - 1)
113 /* State variables for emulating a three button mouse. */
114 #define LMOUSE 1
115 #define MMOUSE 2
116 #define RMOUSE 4
118 static int button_state = 0;
119 static W32Msg saved_mouse_button_msg;
120 static unsigned mouse_button_timer = 0; /* non-zero when timer is active */
121 static W32Msg saved_mouse_move_msg;
122 static unsigned mouse_move_timer = 0;
124 /* Window that is tracking the mouse. */
125 static HWND track_mouse_window;
127 /* Multi-monitor API definitions that are not pulled from the headers
128 since we are compiling for NT 4. */
129 #ifndef MONITOR_DEFAULT_TO_NEAREST
130 #define MONITOR_DEFAULT_TO_NEAREST 2
131 #endif
132 #ifndef MONITORINFOF_PRIMARY
133 #define MONITORINFOF_PRIMARY 1
134 #endif
135 #ifndef SM_XVIRTUALSCREEN
136 #define SM_XVIRTUALSCREEN 76
137 #endif
138 #ifndef SM_YVIRTUALSCREEN
139 #define SM_YVIRTUALSCREEN 77
140 #endif
141 /* MinGW headers define MONITORINFO unconditionally, but MSVC ones don't.
142 To avoid a compile error on one or the other, redefine with a new name. */
143 struct MONITOR_INFO
145 DWORD cbSize;
146 RECT rcMonitor;
147 RECT rcWork;
148 DWORD dwFlags;
151 #ifndef CCHDEVICENAME
152 #define CCHDEVICENAME 32
153 #endif
154 struct MONITOR_INFO_EX
156 DWORD cbSize;
157 RECT rcMonitor;
158 RECT rcWork;
159 DWORD dwFlags;
160 char szDevice[CCHDEVICENAME];
163 /* Reportedly, MSVC does not have this in its headers. */
164 #if defined (_MSC_VER) && _WIN32_WINNT < 0x0500
165 DECLARE_HANDLE(HMONITOR);
166 #endif
168 typedef BOOL (WINAPI * TrackMouseEvent_Proc)
169 (IN OUT LPTRACKMOUSEEVENT lpEventTrack);
170 typedef LONG (WINAPI * ImmGetCompositionString_Proc)
171 (IN HIMC context, IN DWORD index, OUT LPVOID buffer, IN DWORD bufLen);
172 typedef HIMC (WINAPI * ImmGetContext_Proc) (IN HWND window);
173 typedef HWND (WINAPI * ImmReleaseContext_Proc) (IN HWND wnd, IN HIMC context);
174 typedef HWND (WINAPI * ImmSetCompositionWindow_Proc) (IN HIMC context,
175 IN COMPOSITIONFORM *form);
176 typedef HMONITOR (WINAPI * MonitorFromPoint_Proc) (IN POINT pt, IN DWORD flags);
177 typedef BOOL (WINAPI * GetMonitorInfo_Proc)
178 (IN HMONITOR monitor, OUT struct MONITOR_INFO* info);
179 typedef HMONITOR (WINAPI * MonitorFromWindow_Proc)
180 (IN HWND hwnd, IN DWORD dwFlags);
181 typedef BOOL CALLBACK (* MonitorEnum_Proc)
182 (IN HMONITOR monitor, IN HDC hdc, IN RECT *rcMonitor, IN LPARAM dwData);
183 typedef BOOL (WINAPI * EnumDisplayMonitors_Proc)
184 (IN HDC hdc, IN RECT *rcClip, IN MonitorEnum_Proc fnEnum, IN LPARAM dwData);
186 TrackMouseEvent_Proc track_mouse_event_fn = NULL;
187 ImmGetCompositionString_Proc get_composition_string_fn = NULL;
188 ImmGetContext_Proc get_ime_context_fn = NULL;
189 ImmReleaseContext_Proc release_ime_context_fn = NULL;
190 ImmSetCompositionWindow_Proc set_ime_composition_window_fn = NULL;
191 MonitorFromPoint_Proc monitor_from_point_fn = NULL;
192 GetMonitorInfo_Proc get_monitor_info_fn = NULL;
193 MonitorFromWindow_Proc monitor_from_window_fn = NULL;
194 EnumDisplayMonitors_Proc enum_display_monitors_fn = NULL;
196 #ifdef NTGUI_UNICODE
197 #define unicode_append_menu AppendMenuW
198 #else /* !NTGUI_UNICODE */
199 extern AppendMenuW_Proc unicode_append_menu;
200 #endif /* NTGUI_UNICODE */
202 /* Flag to selectively ignore WM_IME_CHAR messages. */
203 static int ignore_ime_char = 0;
205 /* W95 mousewheel handler */
206 unsigned int msh_mousewheel = 0;
208 /* Timers */
209 #define MOUSE_BUTTON_ID 1
210 #define MOUSE_MOVE_ID 2
211 #define MENU_FREE_ID 3
212 /* The delay (milliseconds) before a menu is freed after WM_EXITMENULOOP
213 is received. */
214 #define MENU_FREE_DELAY 1000
215 static unsigned menu_free_timer = 0;
217 #ifdef GLYPH_DEBUG
218 static int image_cache_refcount, dpyinfo_refcount;
219 #endif
221 static HWND w32_visible_system_caret_hwnd;
223 static int w32_unicode_gui;
225 /* From w32menu.c */
226 extern HMENU current_popup_menu;
227 static int menubar_in_use = 0;
229 /* From w32uniscribe.c */
230 extern void syms_of_w32uniscribe (void);
231 extern int uniscribe_available;
233 #ifdef WINDOWSNT
234 /* From w32inevt.c */
235 extern int faked_key;
236 #endif /* WINDOWSNT */
238 /* This gives us the page size and the size of the allocation unit on NT. */
239 SYSTEM_INFO sysinfo_cache;
241 /* This gives us version, build, and platform identification. */
242 OSVERSIONINFO osinfo_cache;
244 DWORD_PTR syspage_mask = 0;
246 /* The major and minor versions of NT. */
247 int w32_major_version;
248 int w32_minor_version;
249 int w32_build_number;
251 /* Distinguish between Windows NT and Windows 95. */
252 int os_subtype;
254 #ifdef HAVE_NTGUI
255 HINSTANCE hinst = NULL;
256 #endif
258 static unsigned int sound_type = 0xFFFFFFFF;
259 #define MB_EMACS_SILENT (0xFFFFFFFF - 1)
261 /* Let the user specify a display with a frame.
262 nil stands for the selected frame--or, if that is not a w32 frame,
263 the first display on the list. */
265 struct w32_display_info *
266 check_x_display_info (Lisp_Object frame)
268 if (NILP (frame))
270 struct frame *sf = XFRAME (selected_frame);
272 if (FRAME_W32_P (sf) && FRAME_LIVE_P (sf))
273 return FRAME_DISPLAY_INFO (sf);
274 else
275 return &one_w32_display_info;
277 else if (STRINGP (frame))
278 return x_display_info_for_name (frame);
279 else
281 struct frame *f;
283 CHECK_LIVE_FRAME (frame);
284 f = XFRAME (frame);
285 if (! FRAME_W32_P (f))
286 error ("Non-W32 frame used");
287 return FRAME_DISPLAY_INFO (f);
291 /* Return the Emacs frame-object corresponding to an w32 window.
292 It could be the frame's main window or an icon window. */
294 struct frame *
295 x_window_to_frame (struct w32_display_info *dpyinfo, HWND wdesc)
297 Lisp_Object tail, frame;
298 struct frame *f;
300 FOR_EACH_FRAME (tail, frame)
302 f = XFRAME (frame);
303 if (!FRAME_W32_P (f) || FRAME_DISPLAY_INFO (f) != dpyinfo)
304 continue;
306 if (FRAME_W32_WINDOW (f) == wdesc)
307 return f;
309 return 0;
313 static Lisp_Object unwind_create_frame (Lisp_Object);
314 static void unwind_create_tip_frame (Lisp_Object);
315 static void my_create_window (struct frame *);
316 static void my_create_tip_window (struct frame *);
318 /* TODO: Native Input Method support; see x_create_im. */
319 void x_set_foreground_color (struct frame *, Lisp_Object, Lisp_Object);
320 void x_set_background_color (struct frame *, Lisp_Object, Lisp_Object);
321 void x_set_mouse_color (struct frame *, Lisp_Object, Lisp_Object);
322 void x_set_cursor_color (struct frame *, Lisp_Object, Lisp_Object);
323 void x_set_border_color (struct frame *, Lisp_Object, Lisp_Object);
324 void x_set_cursor_type (struct frame *, Lisp_Object, Lisp_Object);
325 void x_set_icon_type (struct frame *, Lisp_Object, Lisp_Object);
326 void x_set_icon_name (struct frame *, Lisp_Object, Lisp_Object);
327 void x_explicitly_set_name (struct frame *, Lisp_Object, Lisp_Object);
328 void x_set_menu_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
329 void x_set_title (struct frame *, Lisp_Object, Lisp_Object);
330 void x_set_tool_bar_lines (struct frame *, Lisp_Object, Lisp_Object);
335 /* Store the screen positions of frame F into XPTR and YPTR.
336 These are the positions of the containing window manager window,
337 not Emacs's own window. */
339 void
340 x_real_positions (struct frame *f, int *xptr, int *yptr)
342 POINT pt;
343 RECT rect;
345 /* Get the bounds of the WM window. */
346 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
348 pt.x = 0;
349 pt.y = 0;
351 /* Convert (0, 0) in the client area to screen co-ordinates. */
352 ClientToScreen (FRAME_W32_WINDOW (f), &pt);
354 /* Remember x_pixels_diff and y_pixels_diff. */
355 f->x_pixels_diff = pt.x - rect.left;
356 f->y_pixels_diff = pt.y - rect.top;
358 *xptr = rect.left;
359 *yptr = rect.top;
362 /* Returns the window rectangle appropriate for the given fullscreen mode.
363 The normal rect parameter was the window's rectangle prior to entering
364 fullscreen mode. If multiple monitor support is available, the nearest
365 monitor to the window is chosen. */
367 void
368 w32_fullscreen_rect (HWND hwnd, int fsmode, RECT normal, RECT *rect)
370 struct MONITOR_INFO mi = { sizeof(mi) };
371 if (monitor_from_window_fn && get_monitor_info_fn)
373 HMONITOR monitor =
374 monitor_from_window_fn (hwnd, MONITOR_DEFAULT_TO_NEAREST);
375 get_monitor_info_fn (monitor, &mi);
377 else
379 mi.rcMonitor.left = 0;
380 mi.rcMonitor.top = 0;
381 mi.rcMonitor.right = GetSystemMetrics (SM_CXSCREEN);
382 mi.rcMonitor.bottom = GetSystemMetrics (SM_CYSCREEN);
383 mi.rcWork.left = 0;
384 mi.rcWork.top = 0;
385 mi.rcWork.right = GetSystemMetrics (SM_CXMAXIMIZED);
386 mi.rcWork.bottom = GetSystemMetrics (SM_CYMAXIMIZED);
389 switch (fsmode)
391 case FULLSCREEN_BOTH:
392 rect->left = mi.rcMonitor.left;
393 rect->top = mi.rcMonitor.top;
394 rect->right = mi.rcMonitor.right;
395 rect->bottom = mi.rcMonitor.bottom;
396 break;
397 case FULLSCREEN_WIDTH:
398 rect->left = mi.rcWork.left;
399 rect->top = normal.top;
400 rect->right = mi.rcWork.right;
401 rect->bottom = normal.bottom;
402 break;
403 case FULLSCREEN_HEIGHT:
404 rect->left = normal.left;
405 rect->top = mi.rcWork.top;
406 rect->right = normal.right;
407 rect->bottom = mi.rcWork.bottom;
408 break;
409 default:
410 *rect = normal;
411 break;
417 DEFUN ("w32-define-rgb-color", Fw32_define_rgb_color,
418 Sw32_define_rgb_color, 4, 4, 0,
419 doc: /* Convert RGB numbers to a Windows color reference and associate with NAME.
420 This adds or updates a named color to `w32-color-map', making it
421 available for use. The original entry's RGB ref is returned, or nil
422 if the entry is new. */)
423 (Lisp_Object red, Lisp_Object green, Lisp_Object blue, Lisp_Object name)
425 Lisp_Object rgb;
426 Lisp_Object oldrgb = Qnil;
427 Lisp_Object entry;
429 CHECK_NUMBER (red);
430 CHECK_NUMBER (green);
431 CHECK_NUMBER (blue);
432 CHECK_STRING (name);
434 XSETINT (rgb, RGB (XUINT (red), XUINT (green), XUINT (blue)));
436 block_input ();
438 /* replace existing entry in w32-color-map or add new entry. */
439 entry = Fassoc (name, Vw32_color_map);
440 if (NILP (entry))
442 entry = Fcons (name, rgb);
443 Vw32_color_map = Fcons (entry, Vw32_color_map);
445 else
447 oldrgb = Fcdr (entry);
448 Fsetcdr (entry, rgb);
451 unblock_input ();
453 return (oldrgb);
456 /* The default colors for the w32 color map */
457 typedef struct colormap_t
459 char *name;
460 COLORREF colorref;
461 } colormap_t;
463 colormap_t w32_color_map[] =
465 {"snow" , PALETTERGB (255,250,250)},
466 {"ghost white" , PALETTERGB (248,248,255)},
467 {"GhostWhite" , PALETTERGB (248,248,255)},
468 {"white smoke" , PALETTERGB (245,245,245)},
469 {"WhiteSmoke" , PALETTERGB (245,245,245)},
470 {"gainsboro" , PALETTERGB (220,220,220)},
471 {"floral white" , PALETTERGB (255,250,240)},
472 {"FloralWhite" , PALETTERGB (255,250,240)},
473 {"old lace" , PALETTERGB (253,245,230)},
474 {"OldLace" , PALETTERGB (253,245,230)},
475 {"linen" , PALETTERGB (250,240,230)},
476 {"antique white" , PALETTERGB (250,235,215)},
477 {"AntiqueWhite" , PALETTERGB (250,235,215)},
478 {"papaya whip" , PALETTERGB (255,239,213)},
479 {"PapayaWhip" , PALETTERGB (255,239,213)},
480 {"blanched almond" , PALETTERGB (255,235,205)},
481 {"BlanchedAlmond" , PALETTERGB (255,235,205)},
482 {"bisque" , PALETTERGB (255,228,196)},
483 {"peach puff" , PALETTERGB (255,218,185)},
484 {"PeachPuff" , PALETTERGB (255,218,185)},
485 {"navajo white" , PALETTERGB (255,222,173)},
486 {"NavajoWhite" , PALETTERGB (255,222,173)},
487 {"moccasin" , PALETTERGB (255,228,181)},
488 {"cornsilk" , PALETTERGB (255,248,220)},
489 {"ivory" , PALETTERGB (255,255,240)},
490 {"lemon chiffon" , PALETTERGB (255,250,205)},
491 {"LemonChiffon" , PALETTERGB (255,250,205)},
492 {"seashell" , PALETTERGB (255,245,238)},
493 {"honeydew" , PALETTERGB (240,255,240)},
494 {"mint cream" , PALETTERGB (245,255,250)},
495 {"MintCream" , PALETTERGB (245,255,250)},
496 {"azure" , PALETTERGB (240,255,255)},
497 {"alice blue" , PALETTERGB (240,248,255)},
498 {"AliceBlue" , PALETTERGB (240,248,255)},
499 {"lavender" , PALETTERGB (230,230,250)},
500 {"lavender blush" , PALETTERGB (255,240,245)},
501 {"LavenderBlush" , PALETTERGB (255,240,245)},
502 {"misty rose" , PALETTERGB (255,228,225)},
503 {"MistyRose" , PALETTERGB (255,228,225)},
504 {"white" , PALETTERGB (255,255,255)},
505 {"black" , PALETTERGB ( 0, 0, 0)},
506 {"dark slate gray" , PALETTERGB ( 47, 79, 79)},
507 {"DarkSlateGray" , PALETTERGB ( 47, 79, 79)},
508 {"dark slate grey" , PALETTERGB ( 47, 79, 79)},
509 {"DarkSlateGrey" , PALETTERGB ( 47, 79, 79)},
510 {"dim gray" , PALETTERGB (105,105,105)},
511 {"DimGray" , PALETTERGB (105,105,105)},
512 {"dim grey" , PALETTERGB (105,105,105)},
513 {"DimGrey" , PALETTERGB (105,105,105)},
514 {"slate gray" , PALETTERGB (112,128,144)},
515 {"SlateGray" , PALETTERGB (112,128,144)},
516 {"slate grey" , PALETTERGB (112,128,144)},
517 {"SlateGrey" , PALETTERGB (112,128,144)},
518 {"light slate gray" , PALETTERGB (119,136,153)},
519 {"LightSlateGray" , PALETTERGB (119,136,153)},
520 {"light slate grey" , PALETTERGB (119,136,153)},
521 {"LightSlateGrey" , PALETTERGB (119,136,153)},
522 {"gray" , PALETTERGB (190,190,190)},
523 {"grey" , PALETTERGB (190,190,190)},
524 {"light grey" , PALETTERGB (211,211,211)},
525 {"LightGrey" , PALETTERGB (211,211,211)},
526 {"light gray" , PALETTERGB (211,211,211)},
527 {"LightGray" , PALETTERGB (211,211,211)},
528 {"midnight blue" , PALETTERGB ( 25, 25,112)},
529 {"MidnightBlue" , PALETTERGB ( 25, 25,112)},
530 {"navy" , PALETTERGB ( 0, 0,128)},
531 {"navy blue" , PALETTERGB ( 0, 0,128)},
532 {"NavyBlue" , PALETTERGB ( 0, 0,128)},
533 {"cornflower blue" , PALETTERGB (100,149,237)},
534 {"CornflowerBlue" , PALETTERGB (100,149,237)},
535 {"dark slate blue" , PALETTERGB ( 72, 61,139)},
536 {"DarkSlateBlue" , PALETTERGB ( 72, 61,139)},
537 {"slate blue" , PALETTERGB (106, 90,205)},
538 {"SlateBlue" , PALETTERGB (106, 90,205)},
539 {"medium slate blue" , PALETTERGB (123,104,238)},
540 {"MediumSlateBlue" , PALETTERGB (123,104,238)},
541 {"light slate blue" , PALETTERGB (132,112,255)},
542 {"LightSlateBlue" , PALETTERGB (132,112,255)},
543 {"medium blue" , PALETTERGB ( 0, 0,205)},
544 {"MediumBlue" , PALETTERGB ( 0, 0,205)},
545 {"royal blue" , PALETTERGB ( 65,105,225)},
546 {"RoyalBlue" , PALETTERGB ( 65,105,225)},
547 {"blue" , PALETTERGB ( 0, 0,255)},
548 {"dodger blue" , PALETTERGB ( 30,144,255)},
549 {"DodgerBlue" , PALETTERGB ( 30,144,255)},
550 {"deep sky blue" , PALETTERGB ( 0,191,255)},
551 {"DeepSkyBlue" , PALETTERGB ( 0,191,255)},
552 {"sky blue" , PALETTERGB (135,206,235)},
553 {"SkyBlue" , PALETTERGB (135,206,235)},
554 {"light sky blue" , PALETTERGB (135,206,250)},
555 {"LightSkyBlue" , PALETTERGB (135,206,250)},
556 {"steel blue" , PALETTERGB ( 70,130,180)},
557 {"SteelBlue" , PALETTERGB ( 70,130,180)},
558 {"light steel blue" , PALETTERGB (176,196,222)},
559 {"LightSteelBlue" , PALETTERGB (176,196,222)},
560 {"light blue" , PALETTERGB (173,216,230)},
561 {"LightBlue" , PALETTERGB (173,216,230)},
562 {"powder blue" , PALETTERGB (176,224,230)},
563 {"PowderBlue" , PALETTERGB (176,224,230)},
564 {"pale turquoise" , PALETTERGB (175,238,238)},
565 {"PaleTurquoise" , PALETTERGB (175,238,238)},
566 {"dark turquoise" , PALETTERGB ( 0,206,209)},
567 {"DarkTurquoise" , PALETTERGB ( 0,206,209)},
568 {"medium turquoise" , PALETTERGB ( 72,209,204)},
569 {"MediumTurquoise" , PALETTERGB ( 72,209,204)},
570 {"turquoise" , PALETTERGB ( 64,224,208)},
571 {"cyan" , PALETTERGB ( 0,255,255)},
572 {"light cyan" , PALETTERGB (224,255,255)},
573 {"LightCyan" , PALETTERGB (224,255,255)},
574 {"cadet blue" , PALETTERGB ( 95,158,160)},
575 {"CadetBlue" , PALETTERGB ( 95,158,160)},
576 {"medium aquamarine" , PALETTERGB (102,205,170)},
577 {"MediumAquamarine" , PALETTERGB (102,205,170)},
578 {"aquamarine" , PALETTERGB (127,255,212)},
579 {"dark green" , PALETTERGB ( 0,100, 0)},
580 {"DarkGreen" , PALETTERGB ( 0,100, 0)},
581 {"dark olive green" , PALETTERGB ( 85,107, 47)},
582 {"DarkOliveGreen" , PALETTERGB ( 85,107, 47)},
583 {"dark sea green" , PALETTERGB (143,188,143)},
584 {"DarkSeaGreen" , PALETTERGB (143,188,143)},
585 {"sea green" , PALETTERGB ( 46,139, 87)},
586 {"SeaGreen" , PALETTERGB ( 46,139, 87)},
587 {"medium sea green" , PALETTERGB ( 60,179,113)},
588 {"MediumSeaGreen" , PALETTERGB ( 60,179,113)},
589 {"light sea green" , PALETTERGB ( 32,178,170)},
590 {"LightSeaGreen" , PALETTERGB ( 32,178,170)},
591 {"pale green" , PALETTERGB (152,251,152)},
592 {"PaleGreen" , PALETTERGB (152,251,152)},
593 {"spring green" , PALETTERGB ( 0,255,127)},
594 {"SpringGreen" , PALETTERGB ( 0,255,127)},
595 {"lawn green" , PALETTERGB (124,252, 0)},
596 {"LawnGreen" , PALETTERGB (124,252, 0)},
597 {"green" , PALETTERGB ( 0,255, 0)},
598 {"chartreuse" , PALETTERGB (127,255, 0)},
599 {"medium spring green" , PALETTERGB ( 0,250,154)},
600 {"MediumSpringGreen" , PALETTERGB ( 0,250,154)},
601 {"green yellow" , PALETTERGB (173,255, 47)},
602 {"GreenYellow" , PALETTERGB (173,255, 47)},
603 {"lime green" , PALETTERGB ( 50,205, 50)},
604 {"LimeGreen" , PALETTERGB ( 50,205, 50)},
605 {"yellow green" , PALETTERGB (154,205, 50)},
606 {"YellowGreen" , PALETTERGB (154,205, 50)},
607 {"forest green" , PALETTERGB ( 34,139, 34)},
608 {"ForestGreen" , PALETTERGB ( 34,139, 34)},
609 {"olive drab" , PALETTERGB (107,142, 35)},
610 {"OliveDrab" , PALETTERGB (107,142, 35)},
611 {"dark khaki" , PALETTERGB (189,183,107)},
612 {"DarkKhaki" , PALETTERGB (189,183,107)},
613 {"khaki" , PALETTERGB (240,230,140)},
614 {"pale goldenrod" , PALETTERGB (238,232,170)},
615 {"PaleGoldenrod" , PALETTERGB (238,232,170)},
616 {"light goldenrod yellow" , PALETTERGB (250,250,210)},
617 {"LightGoldenrodYellow" , PALETTERGB (250,250,210)},
618 {"light yellow" , PALETTERGB (255,255,224)},
619 {"LightYellow" , PALETTERGB (255,255,224)},
620 {"yellow" , PALETTERGB (255,255, 0)},
621 {"gold" , PALETTERGB (255,215, 0)},
622 {"light goldenrod" , PALETTERGB (238,221,130)},
623 {"LightGoldenrod" , PALETTERGB (238,221,130)},
624 {"goldenrod" , PALETTERGB (218,165, 32)},
625 {"dark goldenrod" , PALETTERGB (184,134, 11)},
626 {"DarkGoldenrod" , PALETTERGB (184,134, 11)},
627 {"rosy brown" , PALETTERGB (188,143,143)},
628 {"RosyBrown" , PALETTERGB (188,143,143)},
629 {"indian red" , PALETTERGB (205, 92, 92)},
630 {"IndianRed" , PALETTERGB (205, 92, 92)},
631 {"saddle brown" , PALETTERGB (139, 69, 19)},
632 {"SaddleBrown" , PALETTERGB (139, 69, 19)},
633 {"sienna" , PALETTERGB (160, 82, 45)},
634 {"peru" , PALETTERGB (205,133, 63)},
635 {"burlywood" , PALETTERGB (222,184,135)},
636 {"beige" , PALETTERGB (245,245,220)},
637 {"wheat" , PALETTERGB (245,222,179)},
638 {"sandy brown" , PALETTERGB (244,164, 96)},
639 {"SandyBrown" , PALETTERGB (244,164, 96)},
640 {"tan" , PALETTERGB (210,180,140)},
641 {"chocolate" , PALETTERGB (210,105, 30)},
642 {"firebrick" , PALETTERGB (178,34, 34)},
643 {"brown" , PALETTERGB (165,42, 42)},
644 {"dark salmon" , PALETTERGB (233,150,122)},
645 {"DarkSalmon" , PALETTERGB (233,150,122)},
646 {"salmon" , PALETTERGB (250,128,114)},
647 {"light salmon" , PALETTERGB (255,160,122)},
648 {"LightSalmon" , PALETTERGB (255,160,122)},
649 {"orange" , PALETTERGB (255,165, 0)},
650 {"dark orange" , PALETTERGB (255,140, 0)},
651 {"DarkOrange" , PALETTERGB (255,140, 0)},
652 {"coral" , PALETTERGB (255,127, 80)},
653 {"light coral" , PALETTERGB (240,128,128)},
654 {"LightCoral" , PALETTERGB (240,128,128)},
655 {"tomato" , PALETTERGB (255, 99, 71)},
656 {"orange red" , PALETTERGB (255, 69, 0)},
657 {"OrangeRed" , PALETTERGB (255, 69, 0)},
658 {"red" , PALETTERGB (255, 0, 0)},
659 {"hot pink" , PALETTERGB (255,105,180)},
660 {"HotPink" , PALETTERGB (255,105,180)},
661 {"deep pink" , PALETTERGB (255, 20,147)},
662 {"DeepPink" , PALETTERGB (255, 20,147)},
663 {"pink" , PALETTERGB (255,192,203)},
664 {"light pink" , PALETTERGB (255,182,193)},
665 {"LightPink" , PALETTERGB (255,182,193)},
666 {"pale violet red" , PALETTERGB (219,112,147)},
667 {"PaleVioletRed" , PALETTERGB (219,112,147)},
668 {"maroon" , PALETTERGB (176, 48, 96)},
669 {"medium violet red" , PALETTERGB (199, 21,133)},
670 {"MediumVioletRed" , PALETTERGB (199, 21,133)},
671 {"violet red" , PALETTERGB (208, 32,144)},
672 {"VioletRed" , PALETTERGB (208, 32,144)},
673 {"magenta" , PALETTERGB (255, 0,255)},
674 {"violet" , PALETTERGB (238,130,238)},
675 {"plum" , PALETTERGB (221,160,221)},
676 {"orchid" , PALETTERGB (218,112,214)},
677 {"medium orchid" , PALETTERGB (186, 85,211)},
678 {"MediumOrchid" , PALETTERGB (186, 85,211)},
679 {"dark orchid" , PALETTERGB (153, 50,204)},
680 {"DarkOrchid" , PALETTERGB (153, 50,204)},
681 {"dark violet" , PALETTERGB (148, 0,211)},
682 {"DarkViolet" , PALETTERGB (148, 0,211)},
683 {"blue violet" , PALETTERGB (138, 43,226)},
684 {"BlueViolet" , PALETTERGB (138, 43,226)},
685 {"purple" , PALETTERGB (160, 32,240)},
686 {"medium purple" , PALETTERGB (147,112,219)},
687 {"MediumPurple" , PALETTERGB (147,112,219)},
688 {"thistle" , PALETTERGB (216,191,216)},
689 {"gray0" , PALETTERGB ( 0, 0, 0)},
690 {"grey0" , PALETTERGB ( 0, 0, 0)},
691 {"dark grey" , PALETTERGB (169,169,169)},
692 {"DarkGrey" , PALETTERGB (169,169,169)},
693 {"dark gray" , PALETTERGB (169,169,169)},
694 {"DarkGray" , PALETTERGB (169,169,169)},
695 {"dark blue" , PALETTERGB ( 0, 0,139)},
696 {"DarkBlue" , PALETTERGB ( 0, 0,139)},
697 {"dark cyan" , PALETTERGB ( 0,139,139)},
698 {"DarkCyan" , PALETTERGB ( 0,139,139)},
699 {"dark magenta" , PALETTERGB (139, 0,139)},
700 {"DarkMagenta" , PALETTERGB (139, 0,139)},
701 {"dark red" , PALETTERGB (139, 0, 0)},
702 {"DarkRed" , PALETTERGB (139, 0, 0)},
703 {"light green" , PALETTERGB (144,238,144)},
704 {"LightGreen" , PALETTERGB (144,238,144)},
707 static Lisp_Object
708 w32_default_color_map (void)
710 int i;
711 colormap_t *pc = w32_color_map;
712 Lisp_Object cmap;
714 block_input ();
716 cmap = Qnil;
718 for (i = 0; i < ARRAYELTS (w32_color_map); pc++, i++)
719 cmap = Fcons (Fcons (build_string (pc->name),
720 make_number (pc->colorref)),
721 cmap);
723 unblock_input ();
725 return (cmap);
728 DEFUN ("w32-default-color-map", Fw32_default_color_map, Sw32_default_color_map,
729 0, 0, 0, doc: /* Return the default color map. */)
730 (void)
732 return w32_default_color_map ();
735 static Lisp_Object
736 w32_color_map_lookup (const char *colorname)
738 Lisp_Object tail, ret = Qnil;
740 block_input ();
742 for (tail = Vw32_color_map; CONSP (tail); tail = XCDR (tail))
744 register Lisp_Object elt, tem;
746 elt = XCAR (tail);
747 if (!CONSP (elt)) continue;
749 tem = XCAR (elt);
751 if (lstrcmpi (SDATA (tem), colorname) == 0)
753 ret = Fcdr (elt);
754 break;
757 QUIT;
760 unblock_input ();
762 return ret;
766 static void
767 add_system_logical_colors_to_map (Lisp_Object *system_colors)
769 HKEY colors_key;
771 /* Other registry operations are done with input blocked. */
772 block_input ();
774 /* Look for "Control Panel/Colors" under User and Machine registry
775 settings. */
776 if (RegOpenKeyEx (HKEY_CURRENT_USER, "Control Panel\\Colors", 0,
777 KEY_READ, &colors_key) == ERROR_SUCCESS
778 || RegOpenKeyEx (HKEY_LOCAL_MACHINE, "Control Panel\\Colors", 0,
779 KEY_READ, &colors_key) == ERROR_SUCCESS)
781 /* List all keys. */
782 char color_buffer[64];
783 char full_name_buffer[MAX_PATH + SYSTEM_COLOR_PREFIX_LEN];
784 int index = 0;
785 DWORD name_size, color_size;
786 char *name_buffer = full_name_buffer + SYSTEM_COLOR_PREFIX_LEN;
788 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
789 color_size = sizeof (color_buffer);
791 strcpy (full_name_buffer, SYSTEM_COLOR_PREFIX);
793 while (RegEnumValueA (colors_key, index, name_buffer, &name_size,
794 NULL, NULL, color_buffer, &color_size)
795 == ERROR_SUCCESS)
797 int r, g, b;
798 if (sscanf (color_buffer, " %u %u %u", &r, &g, &b) == 3)
799 *system_colors = Fcons (Fcons (build_string (full_name_buffer),
800 make_number (RGB (r, g, b))),
801 *system_colors);
803 name_size = sizeof (full_name_buffer) - SYSTEM_COLOR_PREFIX_LEN;
804 color_size = sizeof (color_buffer);
805 index++;
807 RegCloseKey (colors_key);
810 unblock_input ();
814 static Lisp_Object
815 x_to_w32_color (const char * colorname)
817 register Lisp_Object ret = Qnil;
819 block_input ();
821 if (colorname[0] == '#')
823 /* Could be an old-style RGB Device specification. */
824 int size = strlen (colorname + 1);
825 char *color = alloca (size + 1);
827 strcpy (color, colorname + 1);
828 if (size == 3 || size == 6 || size == 9 || size == 12)
830 UINT colorval;
831 int i, pos;
832 pos = 0;
833 size /= 3;
834 colorval = 0;
836 for (i = 0; i < 3; i++)
838 char *end;
839 char t;
840 unsigned long value;
842 /* The check for 'x' in the following conditional takes into
843 account the fact that strtol allows a "0x" in front of
844 our numbers, and we don't. */
845 if (!isxdigit (color[0]) || color[1] == 'x')
846 break;
847 t = color[size];
848 color[size] = '\0';
849 value = strtoul (color, &end, 16);
850 color[size] = t;
851 if (errno == ERANGE || end - color != size)
852 break;
853 switch (size)
855 case 1:
856 value = value * 0x10;
857 break;
858 case 2:
859 break;
860 case 3:
861 value /= 0x10;
862 break;
863 case 4:
864 value /= 0x100;
865 break;
867 colorval |= (value << pos);
868 pos += 0x8;
869 if (i == 2)
871 unblock_input ();
872 XSETINT (ret, colorval);
873 return ret;
875 color = end;
879 else if (strnicmp (colorname, "rgb:", 4) == 0)
881 const char *color;
882 UINT colorval;
883 int i, pos;
884 pos = 0;
886 colorval = 0;
887 color = colorname + 4;
888 for (i = 0; i < 3; i++)
890 char *end;
891 unsigned long value;
893 /* The check for 'x' in the following conditional takes into
894 account the fact that strtol allows a "0x" in front of
895 our numbers, and we don't. */
896 if (!isxdigit (color[0]) || color[1] == 'x')
897 break;
898 value = strtoul (color, &end, 16);
899 if (errno == ERANGE)
900 break;
901 switch (end - color)
903 case 1:
904 value = value * 0x10 + value;
905 break;
906 case 2:
907 break;
908 case 3:
909 value /= 0x10;
910 break;
911 case 4:
912 value /= 0x100;
913 break;
914 default:
915 value = ULONG_MAX;
917 if (value == ULONG_MAX)
918 break;
919 colorval |= (value << pos);
920 pos += 0x8;
921 if (i == 2)
923 if (*end != '\0')
924 break;
925 unblock_input ();
926 XSETINT (ret, colorval);
927 return ret;
929 if (*end != '/')
930 break;
931 color = end + 1;
934 else if (strnicmp (colorname, "rgbi:", 5) == 0)
936 /* This is an RGB Intensity specification. */
937 const char *color;
938 UINT colorval;
939 int i, pos;
940 pos = 0;
942 colorval = 0;
943 color = colorname + 5;
944 for (i = 0; i < 3; i++)
946 char *end;
947 double value;
948 UINT val;
950 value = strtod (color, &end);
951 if (errno == ERANGE)
952 break;
953 if (value < 0.0 || value > 1.0)
954 break;
955 val = (UINT)(0x100 * value);
956 /* We used 0x100 instead of 0xFF to give a continuous
957 range between 0.0 and 1.0 inclusive. The next statement
958 fixes the 1.0 case. */
959 if (val == 0x100)
960 val = 0xFF;
961 colorval |= (val << pos);
962 pos += 0x8;
963 if (i == 2)
965 if (*end != '\0')
966 break;
967 unblock_input ();
968 XSETINT (ret, colorval);
969 return ret;
971 if (*end != '/')
972 break;
973 color = end + 1;
976 /* I am not going to attempt to handle any of the CIE color schemes
977 or TekHVC, since I don't know the algorithms for conversion to
978 RGB. */
980 /* If we fail to lookup the color name in w32_color_map, then check the
981 colorname to see if it can be crudely approximated: If the X color
982 ends in a number (e.g., "darkseagreen2"), strip the number and
983 return the result of looking up the base color name. */
984 ret = w32_color_map_lookup (colorname);
985 if (NILP (ret))
987 int len = strlen (colorname);
989 if (isdigit (colorname[len - 1]))
991 char *ptr, *approx = alloca (len + 1);
993 strcpy (approx, colorname);
994 ptr = &approx[len - 1];
995 while (ptr > approx && isdigit (*ptr))
996 *ptr-- = '\0';
998 ret = w32_color_map_lookup (approx);
1002 unblock_input ();
1003 return ret;
1006 void
1007 w32_regenerate_palette (struct frame *f)
1009 struct w32_palette_entry * list;
1010 LOGPALETTE * log_palette;
1011 HPALETTE new_palette;
1012 int i;
1014 /* don't bother trying to create palette if not supported */
1015 if (! FRAME_DISPLAY_INFO (f)->has_palette)
1016 return;
1018 log_palette = (LOGPALETTE *)
1019 alloca (sizeof (LOGPALETTE) +
1020 FRAME_DISPLAY_INFO (f)->num_colors * sizeof (PALETTEENTRY));
1021 log_palette->palVersion = 0x300;
1022 log_palette->palNumEntries = FRAME_DISPLAY_INFO (f)->num_colors;
1024 list = FRAME_DISPLAY_INFO (f)->color_list;
1025 for (i = 0;
1026 i < FRAME_DISPLAY_INFO (f)->num_colors;
1027 i++, list = list->next)
1028 log_palette->palPalEntry[i] = list->entry;
1030 new_palette = CreatePalette (log_palette);
1032 enter_crit ();
1034 if (FRAME_DISPLAY_INFO (f)->palette)
1035 DeleteObject (FRAME_DISPLAY_INFO (f)->palette);
1036 FRAME_DISPLAY_INFO (f)->palette = new_palette;
1038 /* Realize display palette and garbage all frames. */
1039 release_frame_dc (f, get_frame_dc (f));
1041 leave_crit ();
1044 #define W32_COLOR(pe) RGB (pe.peRed, pe.peGreen, pe.peBlue)
1045 #define SET_W32_COLOR(pe, color) \
1046 do \
1048 pe.peRed = GetRValue (color); \
1049 pe.peGreen = GetGValue (color); \
1050 pe.peBlue = GetBValue (color); \
1051 pe.peFlags = 0; \
1052 } while (0)
1054 #if 0
1055 /* Keep these around in case we ever want to track color usage. */
1056 void
1057 w32_map_color (struct frame *f, COLORREF color)
1059 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1061 if (NILP (Vw32_enable_palette))
1062 return;
1064 /* check if color is already mapped */
1065 while (list)
1067 if (W32_COLOR (list->entry) == color)
1069 ++list->refcount;
1070 return;
1072 list = list->next;
1075 /* not already mapped, so add to list and recreate Windows palette */
1076 list = xmalloc (sizeof (struct w32_palette_entry));
1077 SET_W32_COLOR (list->entry, color);
1078 list->refcount = 1;
1079 list->next = FRAME_DISPLAY_INFO (f)->color_list;
1080 FRAME_DISPLAY_INFO (f)->color_list = list;
1081 FRAME_DISPLAY_INFO (f)->num_colors++;
1083 /* set flag that palette must be regenerated */
1084 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1087 void
1088 w32_unmap_color (struct frame *f, COLORREF color)
1090 struct w32_palette_entry * list = FRAME_DISPLAY_INFO (f)->color_list;
1091 struct w32_palette_entry **prev = &FRAME_DISPLAY_INFO (f)->color_list;
1093 if (NILP (Vw32_enable_palette))
1094 return;
1096 /* check if color is already mapped */
1097 while (list)
1099 if (W32_COLOR (list->entry) == color)
1101 if (--list->refcount == 0)
1103 *prev = list->next;
1104 xfree (list);
1105 FRAME_DISPLAY_INFO (f)->num_colors--;
1106 break;
1108 else
1109 return;
1111 prev = &list->next;
1112 list = list->next;
1115 /* set flag that palette must be regenerated */
1116 FRAME_DISPLAY_INFO (f)->regen_palette = TRUE;
1118 #endif
1121 /* Gamma-correct COLOR on frame F. */
1123 void
1124 gamma_correct (struct frame *f, COLORREF *color)
1126 if (f->gamma)
1128 *color = PALETTERGB (
1129 pow (GetRValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1130 pow (GetGValue (*color) / 255.0, f->gamma) * 255.0 + 0.5,
1131 pow (GetBValue (*color) / 255.0, f->gamma) * 255.0 + 0.5);
1136 /* Decide if color named COLOR is valid for the display associated with
1137 the selected frame; if so, return the rgb values in COLOR_DEF.
1138 If ALLOC is nonzero, allocate a new colormap cell. */
1141 w32_defined_color (struct frame *f, const char *color, XColor *color_def, int alloc)
1143 register Lisp_Object tem;
1144 COLORREF w32_color_ref;
1146 tem = x_to_w32_color (color);
1148 if (!NILP (tem))
1150 if (f)
1152 /* Apply gamma correction. */
1153 w32_color_ref = XUINT (tem);
1154 gamma_correct (f, &w32_color_ref);
1155 XSETINT (tem, w32_color_ref);
1158 /* Map this color to the palette if it is enabled. */
1159 if (!NILP (Vw32_enable_palette))
1161 struct w32_palette_entry * entry =
1162 one_w32_display_info.color_list;
1163 struct w32_palette_entry ** prev =
1164 &one_w32_display_info.color_list;
1166 /* check if color is already mapped */
1167 while (entry)
1169 if (W32_COLOR (entry->entry) == XUINT (tem))
1170 break;
1171 prev = &entry->next;
1172 entry = entry->next;
1175 if (entry == NULL && alloc)
1177 /* not already mapped, so add to list */
1178 entry = xmalloc (sizeof (struct w32_palette_entry));
1179 SET_W32_COLOR (entry->entry, XUINT (tem));
1180 entry->next = NULL;
1181 *prev = entry;
1182 one_w32_display_info.num_colors++;
1184 /* set flag that palette must be regenerated */
1185 one_w32_display_info.regen_palette = TRUE;
1188 /* Ensure COLORREF value is snapped to nearest color in (default)
1189 palette by simulating the PALETTERGB macro. This works whether
1190 or not the display device has a palette. */
1191 w32_color_ref = XUINT (tem) | 0x2000000;
1193 color_def->pixel = w32_color_ref;
1194 color_def->red = GetRValue (w32_color_ref) * 256;
1195 color_def->green = GetGValue (w32_color_ref) * 256;
1196 color_def->blue = GetBValue (w32_color_ref) * 256;
1198 return 1;
1200 else
1202 return 0;
1206 /* Given a string ARG naming a color, compute a pixel value from it
1207 suitable for screen F.
1208 If F is not a color screen, return DEF (default) regardless of what
1209 ARG says. */
1212 x_decode_color (struct frame *f, Lisp_Object arg, int def)
1214 XColor cdef;
1216 CHECK_STRING (arg);
1218 if (strcmp (SDATA (arg), "black") == 0)
1219 return BLACK_PIX_DEFAULT (f);
1220 else if (strcmp (SDATA (arg), "white") == 0)
1221 return WHITE_PIX_DEFAULT (f);
1223 if ((FRAME_DISPLAY_INFO (f)->n_planes * FRAME_DISPLAY_INFO (f)->n_cbits) == 1)
1224 return def;
1226 /* w32_defined_color is responsible for coping with failures
1227 by looking for a near-miss. */
1228 if (w32_defined_color (f, SDATA (arg), &cdef, 1))
1229 return cdef.pixel;
1231 /* defined_color failed; return an ultimate default. */
1232 return def;
1237 /* Functions called only from `x_set_frame_param'
1238 to set individual parameters.
1240 If FRAME_W32_WINDOW (f) is 0,
1241 the frame is being created and its window does not exist yet.
1242 In that case, just record the parameter's new value
1243 in the standard place; do not attempt to change the window. */
1245 void
1246 x_set_foreground_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1248 struct w32_output *x = f->output_data.w32;
1249 PIX_TYPE fg, old_fg;
1251 fg = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1252 old_fg = FRAME_FOREGROUND_PIXEL (f);
1253 FRAME_FOREGROUND_PIXEL (f) = fg;
1255 if (FRAME_W32_WINDOW (f) != 0)
1257 if (x->cursor_pixel == old_fg)
1259 x->cursor_pixel = fg;
1260 x->cursor_gc->background = fg;
1263 update_face_from_frame_parameter (f, Qforeground_color, arg);
1264 if (FRAME_VISIBLE_P (f))
1265 redraw_frame (f);
1269 void
1270 x_set_background_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1272 FRAME_BACKGROUND_PIXEL (f)
1273 = x_decode_color (f, arg, WHITE_PIX_DEFAULT (f));
1275 if (FRAME_W32_WINDOW (f) != 0)
1277 SetWindowLong (FRAME_W32_WINDOW (f), WND_BACKGROUND_INDEX,
1278 FRAME_BACKGROUND_PIXEL (f));
1280 update_face_from_frame_parameter (f, Qbackground_color, arg);
1282 if (FRAME_VISIBLE_P (f))
1283 redraw_frame (f);
1287 void
1288 x_set_mouse_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1290 Cursor cursor, nontext_cursor, mode_cursor, hand_cursor;
1291 int count;
1292 int mask_color;
1294 if (!EQ (Qnil, arg))
1295 f->output_data.w32->mouse_pixel
1296 = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1297 mask_color = FRAME_BACKGROUND_PIXEL (f);
1299 /* Don't let pointers be invisible. */
1300 if (mask_color == f->output_data.w32->mouse_pixel
1301 && mask_color == FRAME_BACKGROUND_PIXEL (f))
1302 f->output_data.w32->mouse_pixel = FRAME_FOREGROUND_PIXEL (f);
1304 #if 0 /* TODO : Mouse cursor customization. */
1305 block_input ();
1307 /* It's not okay to crash if the user selects a screwy cursor. */
1308 count = x_catch_errors (FRAME_W32_DISPLAY (f));
1310 if (!EQ (Qnil, Vx_pointer_shape))
1312 CHECK_NUMBER (Vx_pointer_shape);
1313 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XINT (Vx_pointer_shape));
1315 else
1316 cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1317 x_check_errors (FRAME_W32_DISPLAY (f), "bad text pointer cursor: %s");
1319 if (!EQ (Qnil, Vx_nontext_pointer_shape))
1321 CHECK_NUMBER (Vx_nontext_pointer_shape);
1322 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1323 XINT (Vx_nontext_pointer_shape));
1325 else
1326 nontext_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_left_ptr);
1327 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1329 if (!EQ (Qnil, Vx_hourglass_pointer_shape))
1331 CHECK_NUMBER (Vx_hourglass_pointer_shape);
1332 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1333 XINT (Vx_hourglass_pointer_shape));
1335 else
1336 hourglass_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_watch);
1337 x_check_errors (FRAME_W32_DISPLAY (f), "bad busy pointer cursor: %s");
1339 x_check_errors (FRAME_W32_DISPLAY (f), "bad nontext pointer cursor: %s");
1340 if (!EQ (Qnil, Vx_mode_pointer_shape))
1342 CHECK_NUMBER (Vx_mode_pointer_shape);
1343 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1344 XINT (Vx_mode_pointer_shape));
1346 else
1347 mode_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_xterm);
1348 x_check_errors (FRAME_W32_DISPLAY (f), "bad modeline pointer cursor: %s");
1350 if (!EQ (Qnil, Vx_sensitive_text_pointer_shape))
1352 CHECK_NUMBER (Vx_sensitive_text_pointer_shape);
1353 hand_cursor
1354 = XCreateFontCursor (FRAME_W32_DISPLAY (f),
1355 XINT (Vx_sensitive_text_pointer_shape));
1357 else
1358 hand_cursor = XCreateFontCursor (FRAME_W32_DISPLAY (f), XC_crosshair);
1360 if (!NILP (Vx_window_horizontal_drag_shape))
1362 CHECK_NUMBER (Vx_window_horizontal_drag_shape);
1363 horizontal_drag_cursor
1364 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1365 XINT (Vx_window_horizontal_drag_shape));
1367 else
1368 horizontal_drag_cursor
1369 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_h_double_arrow);
1371 if (!NILP (Vx_window_vertical_drag_shape))
1373 CHECK_NUMBER (Vx_window_vertical_drag_shape);
1374 vertical_drag_cursor
1375 = XCreateFontCursor (FRAME_X_DISPLAY (f),
1376 XINT (Vx_window_vertical_drag_shape));
1378 else
1379 vertical_drag_cursor
1380 = XCreateFontCursor (FRAME_X_DISPLAY (f), XC_sb_v_double_arrow);
1382 /* Check and report errors with the above calls. */
1383 x_check_errors (FRAME_W32_DISPLAY (f), "can't set cursor shape: %s");
1384 x_uncatch_errors (FRAME_W32_DISPLAY (f), count);
1387 XColor fore_color, back_color;
1389 fore_color.pixel = f->output_data.w32->mouse_pixel;
1390 back_color.pixel = mask_color;
1391 XQueryColor (FRAME_W32_DISPLAY (f),
1392 DefaultColormap (FRAME_W32_DISPLAY (f),
1393 DefaultScreen (FRAME_W32_DISPLAY (f))),
1394 &fore_color);
1395 XQueryColor (FRAME_W32_DISPLAY (f),
1396 DefaultColormap (FRAME_W32_DISPLAY (f),
1397 DefaultScreen (FRAME_W32_DISPLAY (f))),
1398 &back_color);
1399 XRecolorCursor (FRAME_W32_DISPLAY (f), cursor,
1400 &fore_color, &back_color);
1401 XRecolorCursor (FRAME_W32_DISPLAY (f), nontext_cursor,
1402 &fore_color, &back_color);
1403 XRecolorCursor (FRAME_W32_DISPLAY (f), mode_cursor,
1404 &fore_color, &back_color);
1405 XRecolorCursor (FRAME_W32_DISPLAY (f), hand_cursor,
1406 &fore_color, &back_color);
1407 XRecolorCursor (FRAME_W32_DISPLAY (f), hourglass_cursor,
1408 &fore_color, &back_color);
1411 if (FRAME_W32_WINDOW (f) != 0)
1412 XDefineCursor (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), cursor);
1414 if (cursor != f->output_data.w32->text_cursor && f->output_data.w32->text_cursor != 0)
1415 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->text_cursor);
1416 f->output_data.w32->text_cursor = cursor;
1418 if (nontext_cursor != f->output_data.w32->nontext_cursor
1419 && f->output_data.w32->nontext_cursor != 0)
1420 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->nontext_cursor);
1421 f->output_data.w32->nontext_cursor = nontext_cursor;
1423 if (hourglass_cursor != f->output_data.w32->hourglass_cursor
1424 && f->output_data.w32->hourglass_cursor != 0)
1425 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hourglass_cursor);
1426 f->output_data.w32->hourglass_cursor = hourglass_cursor;
1428 if (mode_cursor != f->output_data.w32->modeline_cursor
1429 && f->output_data.w32->modeline_cursor != 0)
1430 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->modeline_cursor);
1431 f->output_data.w32->modeline_cursor = mode_cursor;
1433 if (hand_cursor != f->output_data.w32->hand_cursor
1434 && f->output_data.w32->hand_cursor != 0)
1435 XFreeCursor (FRAME_W32_DISPLAY (f), f->output_data.w32->hand_cursor);
1436 f->output_data.w32->hand_cursor = hand_cursor;
1438 XFlush (FRAME_W32_DISPLAY (f));
1439 unblock_input ();
1441 update_face_from_frame_parameter (f, Qmouse_color, arg);
1442 #endif /* TODO */
1445 void
1446 x_set_cursor_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1448 unsigned long fore_pixel, pixel;
1450 if (!NILP (Vx_cursor_fore_pixel))
1451 fore_pixel = x_decode_color (f, Vx_cursor_fore_pixel,
1452 WHITE_PIX_DEFAULT (f));
1453 else
1454 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1456 pixel = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1458 /* Make sure that the cursor color differs from the background color. */
1459 if (pixel == FRAME_BACKGROUND_PIXEL (f))
1461 pixel = f->output_data.w32->mouse_pixel;
1462 if (pixel == fore_pixel)
1463 fore_pixel = FRAME_BACKGROUND_PIXEL (f);
1466 f->output_data.w32->cursor_foreground_pixel = fore_pixel;
1467 f->output_data.w32->cursor_pixel = pixel;
1469 if (FRAME_W32_WINDOW (f) != 0)
1471 block_input ();
1472 /* Update frame's cursor_gc. */
1473 f->output_data.w32->cursor_gc->foreground = fore_pixel;
1474 f->output_data.w32->cursor_gc->background = pixel;
1476 unblock_input ();
1478 if (FRAME_VISIBLE_P (f))
1480 x_update_cursor (f, 0);
1481 x_update_cursor (f, 1);
1485 update_face_from_frame_parameter (f, Qcursor_color, arg);
1488 /* Set the border-color of frame F to pixel value PIX.
1489 Note that this does not fully take effect if done before
1490 F has a window. */
1492 void
1493 x_set_border_pixel (struct frame *f, int pix)
1496 f->output_data.w32->border_pixel = pix;
1498 if (FRAME_W32_WINDOW (f) != 0 && f->border_width > 0)
1500 if (FRAME_VISIBLE_P (f))
1501 redraw_frame (f);
1505 /* Set the border-color of frame F to value described by ARG.
1506 ARG can be a string naming a color.
1507 The border-color is used for the border that is drawn by the server.
1508 Note that this does not fully take effect if done before
1509 F has a window; it must be redone when the window is created. */
1511 void
1512 x_set_border_color (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1514 int pix;
1516 CHECK_STRING (arg);
1517 pix = x_decode_color (f, arg, BLACK_PIX_DEFAULT (f));
1518 x_set_border_pixel (f, pix);
1519 update_face_from_frame_parameter (f, Qborder_color, arg);
1523 void
1524 x_set_cursor_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1526 set_frame_cursor_types (f, arg);
1529 void
1530 x_set_icon_type (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1532 int result;
1534 if (NILP (arg) && NILP (oldval))
1535 return;
1537 if (STRINGP (arg) && STRINGP (oldval)
1538 && EQ (Fstring_equal (oldval, arg), Qt))
1539 return;
1541 if (SYMBOLP (arg) && SYMBOLP (oldval) && EQ (arg, oldval))
1542 return;
1544 block_input ();
1546 result = x_bitmap_icon (f, arg);
1547 if (result)
1549 unblock_input ();
1550 error ("No icon window available");
1553 unblock_input ();
1556 void
1557 x_set_icon_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1559 if (STRINGP (arg))
1561 if (STRINGP (oldval) && EQ (Fstring_equal (oldval, arg), Qt))
1562 return;
1564 else if (!NILP (arg) || NILP (oldval))
1565 return;
1567 fset_icon_name (f, arg);
1569 #if 0
1570 if (f->output_data.w32->icon_bitmap != 0)
1571 return;
1573 block_input ();
1575 result = x_text_icon (f,
1576 SSDATA ((!NILP (f->icon_name)
1577 ? f->icon_name
1578 : !NILP (f->title)
1579 ? f->title
1580 : f->name)));
1582 if (result)
1584 unblock_input ();
1585 error ("No icon window available");
1588 /* If the window was unmapped (and its icon was mapped),
1589 the new icon is not mapped, so map the window in its stead. */
1590 if (FRAME_VISIBLE_P (f))
1592 #ifdef USE_X_TOOLKIT
1593 XtPopup (f->output_data.w32->widget, XtGrabNone);
1594 #endif
1595 XMapWindow (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f));
1598 XFlush (FRAME_W32_DISPLAY (f));
1599 unblock_input ();
1600 #endif
1604 void
1605 x_set_menu_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1607 int nlines;
1609 /* Right now, menu bars don't work properly in minibuf-only frames;
1610 most of the commands try to apply themselves to the minibuffer
1611 frame itself, and get an error because you can't switch buffers
1612 in or split the minibuffer window. */
1613 if (FRAME_MINIBUF_ONLY_P (f))
1614 return;
1616 if (INTEGERP (value))
1617 nlines = XINT (value);
1618 else
1619 nlines = 0;
1621 FRAME_MENU_BAR_LINES (f) = 0;
1622 FRAME_MENU_BAR_HEIGHT (f) = 0;
1623 if (nlines)
1624 FRAME_EXTERNAL_MENU_BAR (f) = 1;
1625 else
1627 if (FRAME_EXTERNAL_MENU_BAR (f) == 1)
1628 free_frame_menubar (f);
1629 FRAME_EXTERNAL_MENU_BAR (f) = 0;
1631 /* Adjust the frame size so that the client (text) dimensions
1632 remain the same. This depends on FRAME_EXTERNAL_MENU_BAR being
1633 set correctly. */
1634 x_set_window_size (f, 0, FRAME_TEXT_WIDTH (f), FRAME_TEXT_HEIGHT (f), 1);
1635 do_pending_window_change (0);
1637 adjust_frame_glyphs (f);
1641 /* Set the number of lines used for the tool bar of frame F to VALUE.
1642 VALUE not an integer, or < 0 means set the lines to zero. OLDVAL is
1643 the old number of tool bar lines (and is unused). This function may
1644 change the height of all windows on frame F to match the new tool bar
1645 height. By design, the frame's height doesn't change (but maybe it
1646 should if we don't get enough space otherwise). */
1648 void
1649 x_set_tool_bar_lines (struct frame *f, Lisp_Object value, Lisp_Object oldval)
1651 int delta, nlines, root_height;
1652 int unit = FRAME_LINE_HEIGHT (f);
1654 /* Treat tool bars like menu bars. */
1655 if (FRAME_MINIBUF_ONLY_P (f))
1656 return;
1658 /* Use VALUE only if an integer >= 0. */
1659 if (INTEGERP (value) && XINT (value) >= 0)
1660 nlines = XFASTINT (value);
1661 else
1662 nlines = 0;
1664 /* Make sure we redisplay all windows in this frame. */
1665 windows_or_buffers_changed = 23;
1667 /* DELTA is in pixels now. */
1668 delta = (nlines - FRAME_TOOL_BAR_LINES (f)) * unit;
1670 /* Don't resize the tool-bar to more than we have room for. Note: The
1671 calculations below and the subsequent call to resize_frame_windows
1672 are inherently flawed because they can make the toolbar higher than
1673 the containing frame. */
1674 if (delta > 0)
1676 root_height = WINDOW_PIXEL_HEIGHT (XWINDOW (FRAME_ROOT_WINDOW (f)));
1677 if (root_height - delta < unit)
1679 delta = root_height - unit;
1680 /* When creating a new frame and toolbar mode is enabled, we
1681 need at least one toolbar line. */
1682 nlines = max (FRAME_TOOL_BAR_LINES (f) + delta / unit, 1);
1686 FRAME_TOOL_BAR_LINES (f) = nlines;
1687 FRAME_TOOL_BAR_HEIGHT (f) = nlines * FRAME_LINE_HEIGHT (f);
1688 ++windows_or_buffers_changed;
1689 resize_frame_windows (f, FRAME_TEXT_HEIGHT (f), 0, 1);
1690 adjust_frame_glyphs (f);
1692 /* We also have to make sure that the internal border at the top of
1693 the frame, below the menu bar or tool bar, is redrawn when the
1694 tool bar disappears. This is so because the internal border is
1695 below the tool bar if one is displayed, but is below the menu bar
1696 if there isn't a tool bar. The tool bar draws into the area
1697 below the menu bar. */
1698 if (FRAME_W32_WINDOW (f) && FRAME_TOOL_BAR_HEIGHT (f) == 0)
1700 clear_frame (f);
1701 clear_current_matrices (f);
1704 /* If the tool bar gets smaller, the internal border below it
1705 has to be cleared. It was formerly part of the display
1706 of the larger tool bar, and updating windows won't clear it. */
1707 if (FRAME_INTERNAL_BORDER_WIDTH (f) != 0 && FRAME_VISIBLE_P (f))
1709 int height = FRAME_INTERNAL_BORDER_WIDTH (f);
1710 int width = FRAME_PIXEL_WIDTH (f);
1711 int y = nlines * unit;
1712 HDC hdc = get_frame_dc (f);
1714 block_input ();
1715 w32_clear_area (f, hdc, 0, y, width, height);
1716 release_frame_dc (f, hdc);
1717 unblock_input ();
1720 if (delta < 0 && WINDOWP (f->tool_bar_window))
1721 clear_glyph_matrix (XWINDOW (f->tool_bar_window)->current_matrix);
1723 run_window_configuration_change_hook (f);
1727 /* Change the name of frame F to NAME. If NAME is nil, set F's name to
1728 w32_id_name.
1730 If EXPLICIT is non-zero, that indicates that lisp code is setting the
1731 name; if NAME is a string, set F's name to NAME and set
1732 F->explicit_name; if NAME is Qnil, then clear F->explicit_name.
1734 If EXPLICIT is zero, that indicates that Emacs redisplay code is
1735 suggesting a new name, which lisp code should override; if
1736 F->explicit_name is set, ignore the new name; otherwise, set it. */
1738 void
1739 x_set_name (struct frame *f, Lisp_Object name, int explicit)
1741 /* Make sure that requests from lisp code override requests from
1742 Emacs redisplay code. */
1743 if (explicit)
1745 /* If we're switching from explicit to implicit, we had better
1746 update the mode lines and thereby update the title. */
1747 if (f->explicit_name && NILP (name))
1748 update_mode_lines = 25;
1750 f->explicit_name = ! NILP (name);
1752 else if (f->explicit_name)
1753 return;
1755 /* If NAME is nil, set the name to the w32_id_name. */
1756 if (NILP (name))
1758 /* Check for no change needed in this very common case
1759 before we do any consing. */
1760 if (!strcmp (FRAME_DISPLAY_INFO (f)->w32_id_name,
1761 SDATA (f->name)))
1762 return;
1763 name = build_string (FRAME_DISPLAY_INFO (f)->w32_id_name);
1765 else
1766 CHECK_STRING (name);
1768 /* Don't change the name if it's already NAME. */
1769 if (! NILP (Fstring_equal (name, f->name)))
1770 return;
1772 fset_name (f, name);
1774 /* For setting the frame title, the title parameter should override
1775 the name parameter. */
1776 if (! NILP (f->title))
1777 name = f->title;
1779 if (FRAME_W32_WINDOW (f))
1781 block_input ();
1782 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1783 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1784 unblock_input ();
1788 /* This function should be called when the user's lisp code has
1789 specified a name for the frame; the name will override any set by the
1790 redisplay code. */
1791 void
1792 x_explicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1794 x_set_name (f, arg, 1);
1797 /* This function should be called by Emacs redisplay code to set the
1798 name; names set this way will never override names set by the user's
1799 lisp code. */
1800 void
1801 x_implicitly_set_name (struct frame *f, Lisp_Object arg, Lisp_Object oldval)
1803 x_set_name (f, arg, 0);
1806 /* Change the title of frame F to NAME.
1807 If NAME is nil, use the frame name as the title. */
1809 void
1810 x_set_title (struct frame *f, Lisp_Object name, Lisp_Object old_name)
1812 /* Don't change the title if it's already NAME. */
1813 if (EQ (name, f->title))
1814 return;
1816 update_mode_lines = 26;
1818 fset_title (f, name);
1820 if (NILP (name))
1821 name = f->name;
1823 if (FRAME_W32_WINDOW (f))
1825 block_input ();
1826 GUI_FN (SetWindowText) (FRAME_W32_WINDOW (f),
1827 GUI_SDATA (GUI_ENCODE_SYSTEM (name)));
1828 unblock_input ();
1832 void
1833 x_set_scroll_bar_default_width (struct frame *f)
1835 int unit = FRAME_COLUMN_WIDTH (f);
1837 FRAME_CONFIG_SCROLL_BAR_WIDTH (f) = GetSystemMetrics (SM_CXVSCROLL);
1838 FRAME_CONFIG_SCROLL_BAR_COLS (f)
1839 = (FRAME_CONFIG_SCROLL_BAR_WIDTH (f) + unit - 1) / unit;
1843 /* Subroutines for creating a frame. */
1845 Cursor
1846 w32_load_cursor (LPCTSTR name)
1848 /* Try first to load cursor from application resource. */
1849 Cursor cursor = LoadImage ((HINSTANCE) GetModuleHandle (NULL),
1850 name, IMAGE_CURSOR, 0, 0,
1851 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1852 if (!cursor)
1854 /* Then try to load a shared predefined cursor. */
1855 cursor = LoadImage (NULL, name, IMAGE_CURSOR, 0, 0,
1856 LR_DEFAULTCOLOR | LR_DEFAULTSIZE | LR_SHARED);
1858 return cursor;
1861 static LRESULT CALLBACK w32_wnd_proc (HWND, UINT, WPARAM, LPARAM);
1863 #define INIT_WINDOW_CLASS(WC) \
1864 (WC).style = CS_HREDRAW | CS_VREDRAW; \
1865 (WC).lpfnWndProc = (WNDPROC) w32_wnd_proc; \
1866 (WC).cbClsExtra = 0; \
1867 (WC).cbWndExtra = WND_EXTRA_BYTES; \
1868 (WC).hInstance = hinst; \
1869 (WC).hIcon = LoadIcon (hinst, EMACS_CLASS); \
1870 (WC).hCursor = w32_load_cursor (IDC_ARROW); \
1871 (WC).hbrBackground = NULL; \
1872 (WC).lpszMenuName = NULL; \
1874 static BOOL
1875 w32_init_class (HINSTANCE hinst)
1877 if (w32_unicode_gui)
1879 WNDCLASSW uwc;
1880 INIT_WINDOW_CLASS(uwc);
1881 uwc.lpszClassName = L"Emacs";
1883 return RegisterClassW (&uwc);
1885 else
1887 WNDCLASS wc;
1888 INIT_WINDOW_CLASS(wc);
1889 wc.lpszClassName = EMACS_CLASS;
1891 return RegisterClassA (&wc);
1895 static HWND
1896 w32_createscrollbar (struct frame *f, struct scroll_bar * bar)
1898 return CreateWindow ("SCROLLBAR", "", SBS_VERT | WS_CHILD | WS_VISIBLE,
1899 /* Position and size of scroll bar. */
1900 bar->left, bar->top, bar->width, bar->height,
1901 FRAME_W32_WINDOW (f), NULL, hinst, NULL);
1904 static void
1905 w32_createwindow (struct frame *f)
1907 HWND hwnd;
1908 RECT rect;
1909 Lisp_Object top = Qunbound;
1910 Lisp_Object left = Qunbound;
1911 struct w32_display_info *dpyinfo = &one_w32_display_info;
1913 rect.left = rect.top = 0;
1914 rect.right = FRAME_PIXEL_WIDTH (f);
1915 rect.bottom = FRAME_PIXEL_HEIGHT (f);
1917 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
1918 FRAME_EXTERNAL_MENU_BAR (f));
1920 /* Do first time app init */
1922 w32_init_class (hinst);
1924 if (f->size_hint_flags & USPosition || f->size_hint_flags & PPosition)
1926 XSETINT (left, f->left_pos);
1927 XSETINT (top, f->top_pos);
1929 else if (EQ (left, Qunbound) && EQ (top, Qunbound))
1931 /* When called with RES_TYPE_NUMBER, w32_get_arg will return zero
1932 for anything that is not a number and is not Qunbound. */
1933 left = x_get_arg (dpyinfo, Qnil, Qleft, "left", "Left", RES_TYPE_NUMBER);
1934 top = x_get_arg (dpyinfo, Qnil, Qtop, "top", "Top", RES_TYPE_NUMBER);
1937 FRAME_W32_WINDOW (f) = hwnd
1938 = CreateWindow (EMACS_CLASS,
1939 f->namebuf,
1940 f->output_data.w32->dwStyle | WS_CLIPCHILDREN,
1941 EQ (left, Qunbound) ? CW_USEDEFAULT : XINT (left),
1942 EQ (top, Qunbound) ? CW_USEDEFAULT : XINT (top),
1943 rect.right - rect.left,
1944 rect.bottom - rect.top,
1945 NULL,
1946 NULL,
1947 hinst,
1948 NULL);
1950 if (hwnd)
1952 SetWindowLong (hwnd, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
1953 SetWindowLong (hwnd, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
1954 SetWindowLong (hwnd, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
1955 SetWindowLong (hwnd, WND_SCROLLBAR_INDEX, FRAME_SCROLL_BAR_AREA_WIDTH (f));
1956 SetWindowLong (hwnd, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
1958 /* Enable drag-n-drop. */
1959 DragAcceptFiles (hwnd, TRUE);
1961 /* Do this to discard the default setting specified by our parent. */
1962 ShowWindow (hwnd, SW_HIDE);
1964 /* Update frame positions. */
1965 GetWindowRect (hwnd, &rect);
1966 f->left_pos = rect.left;
1967 f->top_pos = rect.top;
1971 static void
1972 my_post_msg (W32Msg * wmsg, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1974 wmsg->msg.hwnd = hwnd;
1975 wmsg->msg.message = msg;
1976 wmsg->msg.wParam = wParam;
1977 wmsg->msg.lParam = lParam;
1978 wmsg->msg.time = GetMessageTime ();
1980 post_msg (wmsg);
1983 /* GetKeyState and MapVirtualKey on Windows 95 do not actually distinguish
1984 between left and right keys as advertised. We test for this
1985 support dynamically, and set a flag when the support is absent. If
1986 absent, we keep track of the left and right control and alt keys
1987 ourselves. This is particularly necessary on keyboards that rely
1988 upon the AltGr key, which is represented as having the left control
1989 and right alt keys pressed. For these keyboards, we need to know
1990 when the left alt key has been pressed in addition to the AltGr key
1991 so that we can properly support M-AltGr-key sequences (such as M-@
1992 on Swedish keyboards). */
1994 #define EMACS_LCONTROL 0
1995 #define EMACS_RCONTROL 1
1996 #define EMACS_LMENU 2
1997 #define EMACS_RMENU 3
1999 static int modifiers[4];
2000 static int modifiers_recorded;
2001 static int modifier_key_support_tested;
2003 static void
2004 test_modifier_support (unsigned int wparam)
2006 unsigned int l, r;
2008 if (wparam != VK_CONTROL && wparam != VK_MENU)
2009 return;
2010 if (wparam == VK_CONTROL)
2012 l = VK_LCONTROL;
2013 r = VK_RCONTROL;
2015 else
2017 l = VK_LMENU;
2018 r = VK_RMENU;
2020 if (!(GetKeyState (l) & 0x8000) && !(GetKeyState (r) & 0x8000))
2021 modifiers_recorded = 1;
2022 else
2023 modifiers_recorded = 0;
2024 modifier_key_support_tested = 1;
2027 static void
2028 record_keydown (unsigned int wparam, unsigned int lparam)
2030 int i;
2032 if (!modifier_key_support_tested)
2033 test_modifier_support (wparam);
2035 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2036 return;
2038 if (wparam == VK_CONTROL)
2039 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2040 else
2041 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2043 modifiers[i] = 1;
2046 static void
2047 record_keyup (unsigned int wparam, unsigned int lparam)
2049 int i;
2051 if ((wparam != VK_CONTROL && wparam != VK_MENU) || !modifiers_recorded)
2052 return;
2054 if (wparam == VK_CONTROL)
2055 i = (lparam & 0x1000000) ? EMACS_RCONTROL : EMACS_LCONTROL;
2056 else
2057 i = (lparam & 0x1000000) ? EMACS_RMENU : EMACS_LMENU;
2059 modifiers[i] = 0;
2062 /* Emacs can lose focus while a modifier key has been pressed. When
2063 it regains focus, be conservative and clear all modifiers since
2064 we cannot reconstruct the left and right modifier state. */
2065 static void
2066 reset_modifiers (void)
2068 SHORT ctrl, alt;
2070 if (GetFocus () == NULL)
2071 /* Emacs doesn't have keyboard focus. Do nothing. */
2072 return;
2074 ctrl = GetAsyncKeyState (VK_CONTROL);
2075 alt = GetAsyncKeyState (VK_MENU);
2077 if (!(ctrl & 0x08000))
2078 /* Clear any recorded control modifier state. */
2079 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2081 if (!(alt & 0x08000))
2082 /* Clear any recorded alt modifier state. */
2083 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2085 /* Update the state of all modifier keys, because modifiers used in
2086 hot-key combinations can get stuck on if Emacs loses focus as a
2087 result of a hot-key being pressed. */
2089 BYTE keystate[256];
2091 #define CURRENT_STATE(key) ((GetAsyncKeyState (key) & 0x8000) >> 8)
2093 memset (keystate, 0, sizeof (keystate));
2094 GetKeyboardState (keystate);
2095 keystate[VK_SHIFT] = CURRENT_STATE (VK_SHIFT);
2096 keystate[VK_CONTROL] = CURRENT_STATE (VK_CONTROL);
2097 keystate[VK_LCONTROL] = CURRENT_STATE (VK_LCONTROL);
2098 keystate[VK_RCONTROL] = CURRENT_STATE (VK_RCONTROL);
2099 keystate[VK_MENU] = CURRENT_STATE (VK_MENU);
2100 keystate[VK_LMENU] = CURRENT_STATE (VK_LMENU);
2101 keystate[VK_RMENU] = CURRENT_STATE (VK_RMENU);
2102 keystate[VK_LWIN] = CURRENT_STATE (VK_LWIN);
2103 keystate[VK_RWIN] = CURRENT_STATE (VK_RWIN);
2104 keystate[VK_APPS] = CURRENT_STATE (VK_APPS);
2105 SetKeyboardState (keystate);
2109 /* Synchronize modifier state with what is reported with the current
2110 keystroke. Even if we cannot distinguish between left and right
2111 modifier keys, we know that, if no modifiers are set, then neither
2112 the left or right modifier should be set. */
2113 static void
2114 sync_modifiers (void)
2116 if (!modifiers_recorded)
2117 return;
2119 if (!(GetKeyState (VK_CONTROL) & 0x8000))
2120 modifiers[EMACS_RCONTROL] = modifiers[EMACS_LCONTROL] = 0;
2122 if (!(GetKeyState (VK_MENU) & 0x8000))
2123 modifiers[EMACS_RMENU] = modifiers[EMACS_LMENU] = 0;
2126 static int
2127 modifier_set (int vkey)
2129 /* Warning: The fact that VK_NUMLOCK is not treated as the other 2
2130 toggle keys is not an omission! If you want to add it, you will
2131 have to make changes in the default sub-case of the WM_KEYDOWN
2132 switch, because if the NUMLOCK modifier is set, the code there
2133 will directly convert any key that looks like an ASCII letter,
2134 and also downcase those that look like upper-case ASCII. */
2135 if (vkey == VK_CAPITAL)
2137 if (NILP (Vw32_enable_caps_lock))
2138 return 0;
2139 else
2140 return (GetKeyState (vkey) & 0x1);
2142 if (vkey == VK_SCROLL)
2144 if (NILP (Vw32_scroll_lock_modifier)
2145 /* w32-scroll-lock-modifier can be any non-nil value that is
2146 not one of the modifiers, in which case it shall be ignored. */
2147 || !( EQ (Vw32_scroll_lock_modifier, Qhyper)
2148 || EQ (Vw32_scroll_lock_modifier, Qsuper)
2149 || EQ (Vw32_scroll_lock_modifier, Qmeta)
2150 || EQ (Vw32_scroll_lock_modifier, Qalt)
2151 || EQ (Vw32_scroll_lock_modifier, Qcontrol)
2152 || EQ (Vw32_scroll_lock_modifier, Qshift)))
2153 return 0;
2154 else
2155 return (GetKeyState (vkey) & 0x1);
2158 if (!modifiers_recorded)
2159 return (GetKeyState (vkey) & 0x8000);
2161 switch (vkey)
2163 case VK_LCONTROL:
2164 return modifiers[EMACS_LCONTROL];
2165 case VK_RCONTROL:
2166 return modifiers[EMACS_RCONTROL];
2167 case VK_LMENU:
2168 return modifiers[EMACS_LMENU];
2169 case VK_RMENU:
2170 return modifiers[EMACS_RMENU];
2172 return (GetKeyState (vkey) & 0x8000);
2175 /* Convert between the modifier bits W32 uses and the modifier bits
2176 Emacs uses. */
2178 unsigned int
2179 w32_key_to_modifier (int key)
2181 Lisp_Object key_mapping;
2183 switch (key)
2185 case VK_LWIN:
2186 key_mapping = Vw32_lwindow_modifier;
2187 break;
2188 case VK_RWIN:
2189 key_mapping = Vw32_rwindow_modifier;
2190 break;
2191 case VK_APPS:
2192 key_mapping = Vw32_apps_modifier;
2193 break;
2194 case VK_SCROLL:
2195 key_mapping = Vw32_scroll_lock_modifier;
2196 break;
2197 default:
2198 key_mapping = Qnil;
2201 /* NB. This code runs in the input thread, asynchronously to the lisp
2202 thread, so we must be careful to ensure access to lisp data is
2203 thread-safe. The following code is safe because the modifier
2204 variable values are updated atomically from lisp and symbols are
2205 not relocated by GC. Also, we don't have to worry about seeing GC
2206 markbits here. */
2207 if (EQ (key_mapping, Qhyper))
2208 return hyper_modifier;
2209 if (EQ (key_mapping, Qsuper))
2210 return super_modifier;
2211 if (EQ (key_mapping, Qmeta))
2212 return meta_modifier;
2213 if (EQ (key_mapping, Qalt))
2214 return alt_modifier;
2215 if (EQ (key_mapping, Qctrl))
2216 return ctrl_modifier;
2217 if (EQ (key_mapping, Qcontrol)) /* synonym for ctrl */
2218 return ctrl_modifier;
2219 if (EQ (key_mapping, Qshift))
2220 return shift_modifier;
2222 /* Don't generate any modifier if not explicitly requested. */
2223 return 0;
2226 static unsigned int
2227 w32_get_modifiers (void)
2229 return ((modifier_set (VK_SHIFT) ? shift_modifier : 0) |
2230 (modifier_set (VK_CONTROL) ? ctrl_modifier : 0) |
2231 (modifier_set (VK_LWIN) ? w32_key_to_modifier (VK_LWIN) : 0) |
2232 (modifier_set (VK_RWIN) ? w32_key_to_modifier (VK_RWIN) : 0) |
2233 (modifier_set (VK_APPS) ? w32_key_to_modifier (VK_APPS) : 0) |
2234 (modifier_set (VK_SCROLL) ? w32_key_to_modifier (VK_SCROLL) : 0) |
2235 (modifier_set (VK_MENU) ?
2236 ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier) : 0));
2239 /* We map the VK_* modifiers into console modifier constants
2240 so that we can use the same routines to handle both console
2241 and window input. */
2243 static int
2244 construct_console_modifiers (void)
2246 int mods;
2248 mods = 0;
2249 mods |= (modifier_set (VK_SHIFT)) ? SHIFT_PRESSED : 0;
2250 mods |= (modifier_set (VK_CAPITAL)) ? CAPSLOCK_ON : 0;
2251 mods |= (modifier_set (VK_SCROLL)) ? SCROLLLOCK_ON : 0;
2252 mods |= (modifier_set (VK_NUMLOCK)) ? NUMLOCK_ON : 0;
2253 mods |= (modifier_set (VK_LCONTROL)) ? LEFT_CTRL_PRESSED : 0;
2254 mods |= (modifier_set (VK_RCONTROL)) ? RIGHT_CTRL_PRESSED : 0;
2255 mods |= (modifier_set (VK_LMENU)) ? LEFT_ALT_PRESSED : 0;
2256 mods |= (modifier_set (VK_RMENU)) ? RIGHT_ALT_PRESSED : 0;
2257 mods |= (modifier_set (VK_LWIN)) ? LEFT_WIN_PRESSED : 0;
2258 mods |= (modifier_set (VK_RWIN)) ? RIGHT_WIN_PRESSED : 0;
2259 mods |= (modifier_set (VK_APPS)) ? APPS_PRESSED : 0;
2261 return mods;
2264 static int
2265 w32_get_key_modifiers (unsigned int wparam, unsigned int lparam)
2267 int mods;
2269 /* Convert to emacs modifiers. */
2270 mods = w32_kbd_mods_to_emacs (construct_console_modifiers (), wparam);
2272 return mods;
2275 unsigned int
2276 map_keypad_keys (unsigned int virt_key, unsigned int extended)
2278 if (virt_key < VK_CLEAR || virt_key > VK_DELETE)
2279 return virt_key;
2281 if (virt_key == VK_RETURN)
2282 return (extended ? VK_NUMPAD_ENTER : VK_RETURN);
2284 if (virt_key >= VK_PRIOR && virt_key <= VK_DOWN)
2285 return (!extended ? (VK_NUMPAD_PRIOR + (virt_key - VK_PRIOR)) : virt_key);
2287 if (virt_key == VK_INSERT || virt_key == VK_DELETE)
2288 return (!extended ? (VK_NUMPAD_INSERT + (virt_key - VK_INSERT)) : virt_key);
2290 if (virt_key == VK_CLEAR)
2291 return (!extended ? VK_NUMPAD_CLEAR : virt_key);
2293 return virt_key;
2296 /* List of special key combinations which w32 would normally capture,
2297 but Emacs should grab instead. Not directly visible to lisp, to
2298 simplify synchronization. Each item is an integer encoding a virtual
2299 key code and modifier combination to capture. */
2300 static Lisp_Object w32_grabbed_keys;
2302 #define HOTKEY(vk, mods) make_number (((vk) & 255) | ((mods) << 8))
2303 #define HOTKEY_ID(k) (XFASTINT (k) & 0xbfff)
2304 #define HOTKEY_VK_CODE(k) (XFASTINT (k) & 255)
2305 #define HOTKEY_MODIFIERS(k) (XFASTINT (k) >> 8)
2307 #define RAW_HOTKEY_ID(k) ((k) & 0xbfff)
2308 #define RAW_HOTKEY_VK_CODE(k) ((k) & 255)
2309 #define RAW_HOTKEY_MODIFIERS(k) ((k) >> 8)
2311 /* Register hot-keys for reserved key combinations when Emacs has
2312 keyboard focus, since this is the only way Emacs can receive key
2313 combinations like Alt-Tab which are used by the system. */
2315 static void
2316 register_hot_keys (HWND hwnd)
2318 Lisp_Object keylist;
2320 /* Use CONSP, since we are called asynchronously. */
2321 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2323 Lisp_Object key = XCAR (keylist);
2325 /* Deleted entries get set to nil. */
2326 if (!INTEGERP (key))
2327 continue;
2329 RegisterHotKey (hwnd, HOTKEY_ID (key),
2330 HOTKEY_MODIFIERS (key), HOTKEY_VK_CODE (key));
2334 static void
2335 unregister_hot_keys (HWND hwnd)
2337 Lisp_Object keylist;
2339 for (keylist = w32_grabbed_keys; CONSP (keylist); keylist = XCDR (keylist))
2341 Lisp_Object key = XCAR (keylist);
2343 if (!INTEGERP (key))
2344 continue;
2346 UnregisterHotKey (hwnd, HOTKEY_ID (key));
2350 #if EMACSDEBUG
2351 const char*
2352 w32_name_of_message (UINT msg)
2354 unsigned i;
2355 static char buf[64];
2356 static const struct {
2357 UINT msg;
2358 const char* name;
2359 } msgnames[] = {
2360 #define M(msg) { msg, # msg }
2361 M (WM_PAINT),
2362 M (WM_TIMER),
2363 M (WM_USER),
2364 M (WM_MOUSEMOVE),
2365 M (WM_LBUTTONUP),
2366 M (WM_KEYDOWN),
2367 M (WM_EMACS_KILL),
2368 M (WM_EMACS_CREATEWINDOW),
2369 M (WM_EMACS_DONE),
2370 M (WM_EMACS_CREATESCROLLBAR),
2371 M (WM_EMACS_SHOWWINDOW),
2372 M (WM_EMACS_SETWINDOWPOS),
2373 M (WM_EMACS_DESTROYWINDOW),
2374 M (WM_EMACS_TRACKPOPUPMENU),
2375 M (WM_EMACS_SETFOCUS),
2376 M (WM_EMACS_SETFOREGROUND),
2377 M (WM_EMACS_SETLOCALE),
2378 M (WM_EMACS_SETKEYBOARDLAYOUT),
2379 M (WM_EMACS_REGISTER_HOT_KEY),
2380 M (WM_EMACS_UNREGISTER_HOT_KEY),
2381 M (WM_EMACS_TOGGLE_LOCK_KEY),
2382 M (WM_EMACS_TRACK_CARET),
2383 M (WM_EMACS_DESTROY_CARET),
2384 M (WM_EMACS_SHOW_CARET),
2385 M (WM_EMACS_HIDE_CARET),
2386 M (WM_EMACS_SETCURSOR),
2387 M (WM_EMACS_PAINT),
2388 M (WM_CHAR),
2389 #undef M
2390 { 0, 0 }
2393 for (i = 0; msgnames[i].name; ++i)
2394 if (msgnames[i].msg == msg)
2395 return msgnames[i].name;
2397 sprintf (buf, "message 0x%04x", (unsigned)msg);
2398 return buf;
2400 #endif /* EMACSDEBUG */
2402 /* Here's an overview of how Emacs input works in GUI sessions on
2403 MS-Windows. (For description of non-GUI input, see the commentary
2404 before w32_console_read_socket in w32inevt.c.)
2406 System messages are read and processed by w32_msg_pump below. This
2407 function runs in a separate thread. It handles a small number of
2408 custom WM_EMACS_* messages (posted by the main thread, look for
2409 PostMessage calls), and dispatches the rest to w32_wnd_proc, which
2410 is the main window procedure for the entire Emacs application.
2412 w32_wnd_proc also runs in the same separate input thread. It
2413 handles some messages, mostly those that need GDI calls, by itself.
2414 For the others, it calls my_post_msg, which inserts the messages
2415 into the input queue serviced by w32_read_socket.
2417 w32_read_socket runs in the main (a.k.a. "Lisp") thread, and is
2418 called synchronously from keyboard.c when it is known or suspected
2419 that some input is available. w32_read_socket either handles
2420 messages immediately, or converts them into Emacs input events and
2421 stuffs them into kbd_buffer, where kbd_buffer_get_event can get at
2422 them and process them when read_char and its callers require
2423 input.
2425 Under Cygwin with the W32 toolkit, the use of /dev/windows with
2426 select(2) takes the place of w32_read_socket.
2430 /* Main message dispatch loop. */
2432 static void
2433 w32_msg_pump (deferred_msg * msg_buf)
2435 MSG msg;
2436 WPARAM result;
2437 HWND focus_window;
2439 msh_mousewheel = RegisterWindowMessage (MSH_MOUSEWHEEL);
2441 while ((w32_unicode_gui ? GetMessageW : GetMessageA) (&msg, NULL, 0, 0))
2444 /* DebPrint (("w32_msg_pump: %s time:%u\n", */
2445 /* w32_name_of_message (msg.message), msg.time)); */
2447 if (msg.hwnd == NULL)
2449 switch (msg.message)
2451 case WM_NULL:
2452 /* Produced by complete_deferred_msg; just ignore. */
2453 break;
2454 case WM_EMACS_CREATEWINDOW:
2455 /* Initialize COM for this window. Even though we don't use it,
2456 some third party shell extensions can cause it to be used in
2457 system dialogs, which causes a crash if it is not initialized.
2458 This is a known bug in Windows, which was fixed long ago, but
2459 the patch for XP is not publicly available until XP SP3,
2460 and older versions will never be patched. */
2461 CoInitialize (NULL);
2462 w32_createwindow ((struct frame *) msg.wParam);
2463 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2464 emacs_abort ();
2465 break;
2466 case WM_EMACS_SETLOCALE:
2467 SetThreadLocale (msg.wParam);
2468 /* Reply is not expected. */
2469 break;
2470 case WM_EMACS_SETKEYBOARDLAYOUT:
2471 result = (WPARAM) ActivateKeyboardLayout ((HKL) msg.wParam, 0);
2472 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2473 result, 0))
2474 emacs_abort ();
2475 break;
2476 case WM_EMACS_REGISTER_HOT_KEY:
2477 focus_window = GetFocus ();
2478 if (focus_window != NULL)
2479 RegisterHotKey (focus_window,
2480 RAW_HOTKEY_ID (msg.wParam),
2481 RAW_HOTKEY_MODIFIERS (msg.wParam),
2482 RAW_HOTKEY_VK_CODE (msg.wParam));
2483 /* Reply is not expected. */
2484 break;
2485 case WM_EMACS_UNREGISTER_HOT_KEY:
2486 focus_window = GetFocus ();
2487 if (focus_window != NULL)
2488 UnregisterHotKey (focus_window, RAW_HOTKEY_ID (msg.wParam));
2489 /* Mark item as erased. NB: this code must be
2490 thread-safe. The next line is okay because the cons
2491 cell is never made into garbage and is not relocated by
2492 GC. */
2493 XSETCAR (XIL ((EMACS_INT) msg.lParam), Qnil);
2494 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2495 emacs_abort ();
2496 break;
2497 case WM_EMACS_TOGGLE_LOCK_KEY:
2499 int vk_code = (int) msg.wParam;
2500 int cur_state = (GetKeyState (vk_code) & 1);
2501 Lisp_Object new_state = XIL ((EMACS_INT) msg.lParam);
2503 /* NB: This code must be thread-safe. It is safe to
2504 call NILP because symbols are not relocated by GC,
2505 and pointer here is not touched by GC (so the markbit
2506 can't be set). Numbers are safe because they are
2507 immediate values. */
2508 if (NILP (new_state)
2509 || (NUMBERP (new_state)
2510 && ((XUINT (new_state)) & 1) != cur_state))
2512 one_w32_display_info.faked_key = vk_code;
2514 keybd_event ((BYTE) vk_code,
2515 (BYTE) MapVirtualKey (vk_code, 0),
2516 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2517 keybd_event ((BYTE) vk_code,
2518 (BYTE) MapVirtualKey (vk_code, 0),
2519 KEYEVENTF_EXTENDEDKEY | 0, 0);
2520 keybd_event ((BYTE) vk_code,
2521 (BYTE) MapVirtualKey (vk_code, 0),
2522 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
2523 cur_state = !cur_state;
2525 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE,
2526 cur_state, 0))
2527 emacs_abort ();
2529 break;
2530 #ifdef MSG_DEBUG
2531 /* Broadcast messages make it here, so you need to be looking
2532 for something in particular for this to be useful. */
2533 default:
2534 DebPrint (("msg %x not expected by w32_msg_pump\n", msg.message));
2535 #endif
2538 else
2540 if (w32_unicode_gui)
2541 DispatchMessageW (&msg);
2542 else
2543 DispatchMessageA (&msg);
2546 /* Exit nested loop when our deferred message has completed. */
2547 if (msg_buf->completed)
2548 break;
2552 deferred_msg * deferred_msg_head;
2554 static deferred_msg *
2555 find_deferred_msg (HWND hwnd, UINT msg)
2557 deferred_msg * item;
2559 /* Don't actually need synchronization for read access, since
2560 modification of single pointer is always atomic. */
2561 /* enter_crit (); */
2563 for (item = deferred_msg_head; item != NULL; item = item->next)
2564 if (item->w32msg.msg.hwnd == hwnd
2565 && item->w32msg.msg.message == msg)
2566 break;
2568 /* leave_crit (); */
2570 return item;
2573 static LRESULT
2574 send_deferred_msg (deferred_msg * msg_buf,
2575 HWND hwnd,
2576 UINT msg,
2577 WPARAM wParam,
2578 LPARAM lParam)
2580 /* Only input thread can send deferred messages. */
2581 if (GetCurrentThreadId () != dwWindowsThreadId)
2582 emacs_abort ();
2584 /* It is an error to send a message that is already deferred. */
2585 if (find_deferred_msg (hwnd, msg) != NULL)
2586 emacs_abort ();
2588 /* Enforced synchronization is not needed because this is the only
2589 function that alters deferred_msg_head, and the following critical
2590 section is guaranteed to only be serially reentered (since only the
2591 input thread can call us). */
2593 /* enter_crit (); */
2595 msg_buf->completed = 0;
2596 msg_buf->next = deferred_msg_head;
2597 deferred_msg_head = msg_buf;
2598 my_post_msg (&msg_buf->w32msg, hwnd, msg, wParam, lParam);
2600 /* leave_crit (); */
2602 /* Start a new nested message loop to process other messages until
2603 this one is completed. */
2604 w32_msg_pump (msg_buf);
2606 deferred_msg_head = msg_buf->next;
2608 return msg_buf->result;
2611 void
2612 complete_deferred_msg (HWND hwnd, UINT msg, LRESULT result)
2614 deferred_msg * msg_buf = find_deferred_msg (hwnd, msg);
2616 if (msg_buf == NULL)
2617 /* Message may have been canceled, so don't abort. */
2618 return;
2620 msg_buf->result = result;
2621 msg_buf->completed = 1;
2623 /* Ensure input thread is woken so it notices the completion. */
2624 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2627 static void
2628 cancel_all_deferred_msgs (void)
2630 deferred_msg * item;
2632 /* Don't actually need synchronization for read access, since
2633 modification of single pointer is always atomic. */
2634 /* enter_crit (); */
2636 for (item = deferred_msg_head; item != NULL; item = item->next)
2638 item->result = 0;
2639 item->completed = 1;
2642 /* leave_crit (); */
2644 /* Ensure input thread is woken so it notices the completion. */
2645 PostThreadMessage (dwWindowsThreadId, WM_NULL, 0, 0);
2648 DWORD WINAPI
2649 w32_msg_worker (void *arg)
2651 MSG msg;
2652 deferred_msg dummy_buf;
2654 /* Ensure our message queue is created */
2656 PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);
2658 if (!PostThreadMessage (dwMainThreadId, WM_EMACS_DONE, 0, 0))
2659 emacs_abort ();
2661 memset (&dummy_buf, 0, sizeof (dummy_buf));
2662 dummy_buf.w32msg.msg.hwnd = NULL;
2663 dummy_buf.w32msg.msg.message = WM_NULL;
2665 /* This is the initial message loop which should only exit when the
2666 application quits. */
2667 w32_msg_pump (&dummy_buf);
2669 return 0;
2672 static void
2673 signal_user_input (void)
2675 /* Interrupt any lisp that wants to be interrupted by input. */
2676 if (!NILP (Vthrow_on_input))
2678 Vquit_flag = Vthrow_on_input;
2679 /* Doing a QUIT from this thread is a bad idea, since this
2680 unwinds the stack of the Lisp thread, and the Windows runtime
2681 rightfully barfs. Disabled. */
2682 #if 0
2683 /* If we're inside a function that wants immediate quits,
2684 do it now. */
2685 if (immediate_quit && NILP (Vinhibit_quit))
2687 immediate_quit = 0;
2688 QUIT;
2690 #endif
2695 static void
2696 post_character_message (HWND hwnd, UINT msg,
2697 WPARAM wParam, LPARAM lParam,
2698 DWORD modifiers)
2700 W32Msg wmsg;
2702 wmsg.dwModifiers = modifiers;
2704 /* Detect quit_char and set quit-flag directly. Note that we
2705 still need to post a message to ensure the main thread will be
2706 woken up if blocked in sys_select, but we do NOT want to post
2707 the quit_char message itself (because it will usually be as if
2708 the user had typed quit_char twice). Instead, we post a dummy
2709 message that has no particular effect. */
2711 int c = wParam;
2712 if (isalpha (c) && wmsg.dwModifiers == ctrl_modifier)
2713 c = make_ctrl_char (c) & 0377;
2714 if (c == quit_char
2715 || (wmsg.dwModifiers == 0
2716 && w32_quit_key && wParam == w32_quit_key))
2718 Vquit_flag = Qt;
2720 /* The choice of message is somewhat arbitrary, as long as
2721 the main thread handler just ignores it. */
2722 msg = WM_NULL;
2724 /* Interrupt any blocking system calls. */
2725 signal_quit ();
2727 /* As a safety precaution, forcibly complete any deferred
2728 messages. This is a kludge, but I don't see any particularly
2729 clean way to handle the situation where a deferred message is
2730 "dropped" in the lisp thread, and will thus never be
2731 completed, eg. by the user trying to activate the menubar
2732 when the lisp thread is busy, and then typing C-g when the
2733 menubar doesn't open promptly (with the result that the
2734 menubar never responds at all because the deferred
2735 WM_INITMENU message is never completed). Another problem
2736 situation is when the lisp thread calls SendMessage (to send
2737 a window manager command) when a message has been deferred;
2738 the lisp thread gets blocked indefinitely waiting for the
2739 deferred message to be completed, which itself is waiting for
2740 the lisp thread to respond.
2742 Note that we don't want to block the input thread waiting for
2743 a response from the lisp thread (although that would at least
2744 solve the deadlock problem above), because we want to be able
2745 to receive C-g to interrupt the lisp thread. */
2746 cancel_all_deferred_msgs ();
2748 else
2749 signal_user_input ();
2752 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2755 /* Main window procedure */
2757 static LRESULT CALLBACK
2758 w32_wnd_proc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2760 struct frame *f;
2761 struct w32_display_info *dpyinfo = &one_w32_display_info;
2762 W32Msg wmsg;
2763 int windows_translate;
2764 int key;
2766 /* Note that it is okay to call x_window_to_frame, even though we are
2767 not running in the main lisp thread, because frame deletion
2768 requires the lisp thread to synchronize with this thread. Thus, if
2769 a frame struct is returned, it can be used without concern that the
2770 lisp thread might make it disappear while we are using it.
2772 NB. Walking the frame list in this thread is safe (as long as
2773 writes of Lisp_Object slots are atomic, which they are on Windows).
2774 Although delete-frame can destructively modify the frame list while
2775 we are walking it, a garbage collection cannot occur until after
2776 delete-frame has synchronized with this thread.
2778 It is also safe to use functions that make GDI calls, such as
2779 w32_clear_rect, because these functions must obtain a DC handle
2780 from the frame struct using get_frame_dc which is thread-aware. */
2782 switch (msg)
2784 case WM_ERASEBKGND:
2785 f = x_window_to_frame (dpyinfo, hwnd);
2786 if (f)
2788 HDC hdc = get_frame_dc (f);
2789 GetUpdateRect (hwnd, &wmsg.rect, FALSE);
2790 w32_clear_rect (f, hdc, &wmsg.rect);
2791 release_frame_dc (f, hdc);
2793 #if defined (W32_DEBUG_DISPLAY)
2794 DebPrint (("WM_ERASEBKGND (frame %p): erasing %d,%d-%d,%d\n",
2796 wmsg.rect.left, wmsg.rect.top,
2797 wmsg.rect.right, wmsg.rect.bottom));
2798 #endif /* W32_DEBUG_DISPLAY */
2800 return 1;
2801 case WM_PALETTECHANGED:
2802 /* ignore our own changes */
2803 if ((HWND)wParam != hwnd)
2805 f = x_window_to_frame (dpyinfo, hwnd);
2806 if (f)
2807 /* get_frame_dc will realize our palette and force all
2808 frames to be redrawn if needed. */
2809 release_frame_dc (f, get_frame_dc (f));
2811 return 0;
2812 case WM_PAINT:
2814 PAINTSTRUCT paintStruct;
2815 RECT update_rect;
2816 memset (&update_rect, 0, sizeof (update_rect));
2818 f = x_window_to_frame (dpyinfo, hwnd);
2819 if (f == 0)
2821 DebPrint (("WM_PAINT received for unknown window %p\n", hwnd));
2822 return 0;
2825 /* MSDN Docs say not to call BeginPaint if GetUpdateRect
2826 fails. Apparently this can happen under some
2827 circumstances. */
2828 if (GetUpdateRect (hwnd, &update_rect, FALSE) || !w32_strict_painting)
2830 enter_crit ();
2831 BeginPaint (hwnd, &paintStruct);
2833 /* The rectangles returned by GetUpdateRect and BeginPaint
2834 do not always match. Play it safe by assuming both areas
2835 are invalid. */
2836 UnionRect (&(wmsg.rect), &update_rect, &(paintStruct.rcPaint));
2838 #if defined (W32_DEBUG_DISPLAY)
2839 DebPrint (("WM_PAINT (frame %p): painting %d,%d-%d,%d\n",
2841 wmsg.rect.left, wmsg.rect.top,
2842 wmsg.rect.right, wmsg.rect.bottom));
2843 DebPrint ((" [update region is %d,%d-%d,%d]\n",
2844 update_rect.left, update_rect.top,
2845 update_rect.right, update_rect.bottom));
2846 #endif
2847 EndPaint (hwnd, &paintStruct);
2848 leave_crit ();
2850 /* Change the message type to prevent Windows from
2851 combining WM_PAINT messages in the Lisp thread's queue,
2852 since Windows assumes that each message queue is
2853 dedicated to one frame and does not bother checking
2854 that hwnd matches before combining them. */
2855 my_post_msg (&wmsg, hwnd, WM_EMACS_PAINT, wParam, lParam);
2857 return 0;
2860 /* If GetUpdateRect returns 0 (meaning there is no update
2861 region), assume the whole window needs to be repainted. */
2862 GetClientRect (hwnd, &wmsg.rect);
2863 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2864 return 0;
2867 case WM_INPUTLANGCHANGE:
2868 /* Inform lisp thread of keyboard layout changes. */
2869 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
2871 /* Clear dead keys in the keyboard state; for simplicity only
2872 preserve modifier key states. */
2874 int i;
2875 BYTE keystate[256];
2877 GetKeyboardState (keystate);
2878 for (i = 0; i < 256; i++)
2879 if (1
2880 && i != VK_SHIFT
2881 && i != VK_LSHIFT
2882 && i != VK_RSHIFT
2883 && i != VK_CAPITAL
2884 && i != VK_NUMLOCK
2885 && i != VK_SCROLL
2886 && i != VK_CONTROL
2887 && i != VK_LCONTROL
2888 && i != VK_RCONTROL
2889 && i != VK_MENU
2890 && i != VK_LMENU
2891 && i != VK_RMENU
2892 && i != VK_LWIN
2893 && i != VK_RWIN)
2894 keystate[i] = 0;
2895 SetKeyboardState (keystate);
2897 goto dflt;
2899 case WM_HOTKEY:
2900 /* Synchronize hot keys with normal input. */
2901 PostMessage (hwnd, WM_KEYDOWN, HIWORD (lParam), 0);
2902 return (0);
2904 case WM_KEYUP:
2905 case WM_SYSKEYUP:
2906 record_keyup (wParam, lParam);
2907 goto dflt;
2909 case WM_KEYDOWN:
2910 case WM_SYSKEYDOWN:
2911 /* Ignore keystrokes we fake ourself; see below. */
2912 if (dpyinfo->faked_key == wParam)
2914 dpyinfo->faked_key = 0;
2915 /* Make sure TranslateMessage sees them though (as long as
2916 they don't produce WM_CHAR messages). This ensures that
2917 indicator lights are toggled promptly on Windows 9x, for
2918 example. */
2919 if (wParam < 256 && lispy_function_keys[wParam])
2921 windows_translate = 1;
2922 goto translate;
2924 return 0;
2927 /* Synchronize modifiers with current keystroke. */
2928 sync_modifiers ();
2929 record_keydown (wParam, lParam);
2930 wParam = map_keypad_keys (wParam, (lParam & 0x1000000L) != 0);
2932 windows_translate = 0;
2934 switch (wParam)
2936 case VK_LWIN:
2937 if (NILP (Vw32_pass_lwindow_to_system))
2939 /* Prevent system from acting on keyup (which opens the
2940 Start menu if no other key was pressed) by simulating a
2941 press of Space which we will ignore. */
2942 if (GetAsyncKeyState (wParam) & 1)
2944 if (NUMBERP (Vw32_phantom_key_code))
2945 key = XUINT (Vw32_phantom_key_code) & 255;
2946 else
2947 key = VK_SPACE;
2948 dpyinfo->faked_key = key;
2949 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2952 if (!NILP (Vw32_lwindow_modifier))
2953 return 0;
2954 break;
2955 case VK_RWIN:
2956 if (NILP (Vw32_pass_rwindow_to_system))
2958 if (GetAsyncKeyState (wParam) & 1)
2960 if (NUMBERP (Vw32_phantom_key_code))
2961 key = XUINT (Vw32_phantom_key_code) & 255;
2962 else
2963 key = VK_SPACE;
2964 dpyinfo->faked_key = key;
2965 keybd_event (key, (BYTE) MapVirtualKey (key, 0), 0, 0);
2968 if (!NILP (Vw32_rwindow_modifier))
2969 return 0;
2970 break;
2971 case VK_APPS:
2972 if (!NILP (Vw32_apps_modifier))
2973 return 0;
2974 break;
2975 case VK_MENU:
2976 if (NILP (Vw32_pass_alt_to_system))
2977 /* Prevent DefWindowProc from activating the menu bar if an
2978 Alt key is pressed and released by itself. */
2979 return 0;
2980 windows_translate = 1;
2981 break;
2982 case VK_CAPITAL:
2983 /* Decide whether to treat as modifier or function key. */
2984 if (NILP (Vw32_enable_caps_lock))
2985 goto disable_lock_key;
2986 windows_translate = 1;
2987 break;
2988 case VK_NUMLOCK:
2989 /* Decide whether to treat as modifier or function key. */
2990 if (NILP (Vw32_enable_num_lock))
2991 goto disable_lock_key;
2992 windows_translate = 1;
2993 break;
2994 case VK_SCROLL:
2995 /* Decide whether to treat as modifier or function key. */
2996 if (NILP (Vw32_scroll_lock_modifier))
2997 goto disable_lock_key;
2998 windows_translate = 1;
2999 break;
3000 disable_lock_key:
3001 /* Ensure the appropriate lock key state (and indicator light)
3002 remains in the same state. We do this by faking another
3003 press of the relevant key. Apparently, this really is the
3004 only way to toggle the state of the indicator lights. */
3005 dpyinfo->faked_key = wParam;
3006 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3007 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3008 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3009 KEYEVENTF_EXTENDEDKEY | 0, 0);
3010 keybd_event ((BYTE) wParam, (BYTE) MapVirtualKey (wParam, 0),
3011 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
3012 /* Ensure indicator lights are updated promptly on Windows 9x
3013 (TranslateMessage apparently does this), after forwarding
3014 input event. */
3015 post_character_message (hwnd, msg, wParam, lParam,
3016 w32_get_key_modifiers (wParam, lParam));
3017 windows_translate = 1;
3018 break;
3019 case VK_CONTROL:
3020 case VK_SHIFT:
3021 case VK_PROCESSKEY: /* Generated by IME. */
3022 windows_translate = 1;
3023 break;
3024 case VK_CANCEL:
3025 /* Windows maps Ctrl-Pause (aka Ctrl-Break) into VK_CANCEL,
3026 which is confusing for purposes of key binding; convert
3027 VK_CANCEL events into VK_PAUSE events. */
3028 wParam = VK_PAUSE;
3029 break;
3030 case VK_PAUSE:
3031 /* Windows maps Ctrl-NumLock into VK_PAUSE, which is confusing
3032 for purposes of key binding; convert these back into
3033 VK_NUMLOCK events, at least when we want to see NumLock key
3034 presses. (Note that there is never any possibility that
3035 VK_PAUSE with Ctrl really is C-Pause as per above.) */
3036 if (NILP (Vw32_enable_num_lock) && modifier_set (VK_CONTROL))
3037 wParam = VK_NUMLOCK;
3038 break;
3039 default:
3040 /* If not defined as a function key, change it to a WM_CHAR message. */
3041 if (wParam > 255 || !lispy_function_keys[wParam])
3043 DWORD modifiers = construct_console_modifiers ();
3045 if (!NILP (Vw32_recognize_altgr)
3046 && modifier_set (VK_LCONTROL) && modifier_set (VK_RMENU))
3048 /* Always let TranslateMessage handle AltGr key chords;
3049 for some reason, ToAscii doesn't always process AltGr
3050 chords correctly. */
3051 windows_translate = 1;
3053 else if ((modifiers & (~SHIFT_PRESSED & ~CAPSLOCK_ON)) != 0)
3055 /* Handle key chords including any modifiers other
3056 than shift directly, in order to preserve as much
3057 modifier information as possible. */
3058 if ('A' <= wParam && wParam <= 'Z')
3060 /* Don't translate modified alphabetic keystrokes,
3061 so the user doesn't need to constantly switch
3062 layout to type control or meta keystrokes when
3063 the normal layout translates alphabetic
3064 characters to non-ascii characters. */
3065 if (!modifier_set (VK_SHIFT))
3066 wParam += ('a' - 'A');
3067 msg = WM_CHAR;
3069 else
3071 /* Try to handle other keystrokes by determining the
3072 base character (ie. translating the base key plus
3073 shift modifier). */
3074 int add;
3075 KEY_EVENT_RECORD key;
3077 key.bKeyDown = TRUE;
3078 key.wRepeatCount = 1;
3079 key.wVirtualKeyCode = wParam;
3080 key.wVirtualScanCode = (lParam & 0xFF0000) >> 16;
3081 key.uChar.AsciiChar = 0;
3082 key.dwControlKeyState = modifiers;
3084 add = w32_kbd_patch_key (&key, w32_keyboard_codepage);
3085 /* 0 means an unrecognized keycode, negative means
3086 dead key. Ignore both. */
3087 while (--add >= 0)
3089 /* Forward asciified character sequence. */
3090 post_character_message
3091 (hwnd, WM_CHAR,
3092 (unsigned char) key.uChar.AsciiChar, lParam,
3093 w32_get_key_modifiers (wParam, lParam));
3094 w32_kbd_patch_key (&key, w32_keyboard_codepage);
3096 return 0;
3099 else
3101 /* Let TranslateMessage handle everything else. */
3102 windows_translate = 1;
3107 translate:
3108 if (windows_translate)
3110 MSG windows_msg = { hwnd, msg, wParam, lParam, 0, {0,0} };
3111 windows_msg.time = GetMessageTime ();
3112 TranslateMessage (&windows_msg);
3113 goto dflt;
3116 /* Fall through */
3118 case WM_SYSCHAR:
3119 case WM_CHAR:
3120 if (wParam > 255 )
3122 W32Msg wmsg;
3124 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3125 signal_user_input ();
3126 my_post_msg (&wmsg, hwnd, WM_UNICHAR, wParam, lParam);
3129 else
3130 post_character_message (hwnd, msg, wParam, lParam,
3131 w32_get_key_modifiers (wParam, lParam));
3132 break;
3134 case WM_UNICHAR:
3135 /* WM_UNICHAR looks promising from the docs, but the exact
3136 circumstances in which TranslateMessage sends it is one of those
3137 Microsoft secret API things that EU and US courts are supposed
3138 to have put a stop to already. Spy++ shows it being sent to Notepad
3139 and other MS apps, but never to Emacs.
3141 Some third party IMEs send it in accordance with the official
3142 documentation though, so handle it here.
3144 UNICODE_NOCHAR is used to test for support for this message.
3145 TRUE indicates that the message is supported. */
3146 if (wParam == UNICODE_NOCHAR)
3147 return TRUE;
3150 W32Msg wmsg;
3151 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3152 signal_user_input ();
3153 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3155 break;
3157 case WM_IME_CHAR:
3158 /* If we can't get the IME result as Unicode, use default processing,
3159 which will at least allow characters decodable in the system locale
3160 get through. */
3161 if (!get_composition_string_fn)
3162 goto dflt;
3164 else if (!ignore_ime_char)
3166 wchar_t * buffer;
3167 int size, i;
3168 W32Msg wmsg;
3169 HIMC context = get_ime_context_fn (hwnd);
3170 wmsg.dwModifiers = w32_get_key_modifiers (wParam, lParam);
3171 /* Get buffer size. */
3172 size = get_composition_string_fn (context, GCS_RESULTSTR, NULL, 0);
3173 buffer = alloca (size);
3174 size = get_composition_string_fn (context, GCS_RESULTSTR,
3175 buffer, size);
3176 release_ime_context_fn (hwnd, context);
3178 signal_user_input ();
3179 for (i = 0; i < size / sizeof (wchar_t); i++)
3181 my_post_msg (&wmsg, hwnd, WM_UNICHAR, (WPARAM) buffer[i],
3182 lParam);
3184 /* Ignore the messages for the rest of the
3185 characters in the string that was output above. */
3186 ignore_ime_char = (size / sizeof (wchar_t)) - 1;
3188 else
3189 ignore_ime_char--;
3191 break;
3193 case WM_IME_STARTCOMPOSITION:
3194 if (!set_ime_composition_window_fn)
3195 goto dflt;
3196 else
3198 COMPOSITIONFORM form;
3199 HIMC context;
3200 struct window *w;
3202 /* Implementation note: The code below does something that
3203 one shouldn't do: it accesses the window object from a
3204 separate thread, while the main (a.k.a. "Lisp") thread
3205 runs and can legitimately delete and even GC it. That is
3206 why we are extra careful not to futz with a window that
3207 is different from the one recorded when the system caret
3208 coordinates were last modified. That is also why we are
3209 careful not to move the IME window if the window
3210 described by W was deleted, as indicated by its buffer
3211 field being reset to nil. */
3212 f = x_window_to_frame (dpyinfo, hwnd);
3213 if (!(f && FRAME_LIVE_P (f)))
3214 break;
3215 w = XWINDOW (FRAME_SELECTED_WINDOW (f));
3216 /* Punt if someone changed the frame's selected window
3217 behind our back. */
3218 if (w != w32_system_caret_window)
3219 break;
3221 form.dwStyle = CFS_RECT;
3222 form.ptCurrentPos.x = w32_system_caret_x;
3223 form.ptCurrentPos.y = w32_system_caret_y;
3225 form.rcArea.left = WINDOW_TEXT_TO_FRAME_PIXEL_X (w, 0);
3226 form.rcArea.top = (WINDOW_TOP_EDGE_Y (w)
3227 + w32_system_caret_hdr_height);
3228 form.rcArea.right = (WINDOW_BOX_RIGHT_EDGE_X (w)
3229 - WINDOW_RIGHT_MARGIN_WIDTH (w)
3230 - WINDOW_RIGHT_FRINGE_WIDTH (w));
3231 form.rcArea.bottom = (WINDOW_BOTTOM_EDGE_Y (w)
3232 - WINDOW_BOTTOM_DIVIDER_WIDTH (w)
3233 - w32_system_caret_mode_height);
3235 /* Punt if the window was deleted behind our back. */
3236 if (!BUFFERP (w->contents))
3237 break;
3239 context = get_ime_context_fn (hwnd);
3241 if (!context)
3242 break;
3244 set_ime_composition_window_fn (context, &form);
3245 release_ime_context_fn (hwnd, context);
3247 break;
3249 case WM_IME_ENDCOMPOSITION:
3250 ignore_ime_char = 0;
3251 goto dflt;
3253 /* Simulate middle mouse button events when left and right buttons
3254 are used together, but only if user has two button mouse. */
3255 case WM_LBUTTONDOWN:
3256 case WM_RBUTTONDOWN:
3257 if (w32_num_mouse_buttons > 2)
3258 goto handle_plain_button;
3261 int this = (msg == WM_LBUTTONDOWN) ? LMOUSE : RMOUSE;
3262 int other = (msg == WM_LBUTTONDOWN) ? RMOUSE : LMOUSE;
3264 if (button_state & this)
3265 return 0;
3267 if (button_state == 0)
3268 SetCapture (hwnd);
3270 button_state |= this;
3272 if (button_state & other)
3274 if (mouse_button_timer)
3276 KillTimer (hwnd, mouse_button_timer);
3277 mouse_button_timer = 0;
3279 /* Generate middle mouse event instead. */
3280 msg = WM_MBUTTONDOWN;
3281 button_state |= MMOUSE;
3283 else if (button_state & MMOUSE)
3285 /* Ignore button event if we've already generated a
3286 middle mouse down event. This happens if the
3287 user releases and press one of the two buttons
3288 after we've faked a middle mouse event. */
3289 return 0;
3291 else
3293 /* Flush out saved message. */
3294 post_msg (&saved_mouse_button_msg);
3296 wmsg.dwModifiers = w32_get_modifiers ();
3297 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3298 signal_user_input ();
3300 /* Clear message buffer. */
3301 saved_mouse_button_msg.msg.hwnd = 0;
3303 else
3305 /* Hold onto message for now. */
3306 mouse_button_timer =
3307 SetTimer (hwnd, MOUSE_BUTTON_ID,
3308 w32_mouse_button_tolerance, NULL);
3309 saved_mouse_button_msg.msg.hwnd = hwnd;
3310 saved_mouse_button_msg.msg.message = msg;
3311 saved_mouse_button_msg.msg.wParam = wParam;
3312 saved_mouse_button_msg.msg.lParam = lParam;
3313 saved_mouse_button_msg.msg.time = GetMessageTime ();
3314 saved_mouse_button_msg.dwModifiers = w32_get_modifiers ();
3317 return 0;
3319 case WM_LBUTTONUP:
3320 case WM_RBUTTONUP:
3321 if (w32_num_mouse_buttons > 2)
3322 goto handle_plain_button;
3325 int this = (msg == WM_LBUTTONUP) ? LMOUSE : RMOUSE;
3326 int other = (msg == WM_LBUTTONUP) ? RMOUSE : LMOUSE;
3328 if ((button_state & this) == 0)
3329 return 0;
3331 button_state &= ~this;
3333 if (button_state & MMOUSE)
3335 /* Only generate event when second button is released. */
3336 if ((button_state & other) == 0)
3338 msg = WM_MBUTTONUP;
3339 button_state &= ~MMOUSE;
3341 if (button_state) emacs_abort ();
3343 else
3344 return 0;
3346 else
3348 /* Flush out saved message if necessary. */
3349 if (saved_mouse_button_msg.msg.hwnd)
3351 post_msg (&saved_mouse_button_msg);
3354 wmsg.dwModifiers = w32_get_modifiers ();
3355 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3356 signal_user_input ();
3358 /* Always clear message buffer and cancel timer. */
3359 saved_mouse_button_msg.msg.hwnd = 0;
3360 KillTimer (hwnd, mouse_button_timer);
3361 mouse_button_timer = 0;
3363 if (button_state == 0)
3364 ReleaseCapture ();
3366 return 0;
3368 case WM_XBUTTONDOWN:
3369 case WM_XBUTTONUP:
3370 if (w32_pass_extra_mouse_buttons_to_system)
3371 goto dflt;
3372 /* else fall through and process them. */
3373 case WM_MBUTTONDOWN:
3374 case WM_MBUTTONUP:
3375 handle_plain_button:
3377 BOOL up;
3378 int button;
3380 /* Ignore middle and extra buttons as long as the menu is active. */
3381 f = x_window_to_frame (dpyinfo, hwnd);
3382 if (f && f->output_data.w32->menubar_active)
3383 return 0;
3385 if (parse_button (msg, HIWORD (wParam), &button, &up))
3387 if (up) ReleaseCapture ();
3388 else SetCapture (hwnd);
3389 button = (button == 0) ? LMOUSE :
3390 ((button == 1) ? MMOUSE : RMOUSE);
3391 if (up)
3392 button_state &= ~button;
3393 else
3394 button_state |= button;
3398 wmsg.dwModifiers = w32_get_modifiers ();
3399 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3400 signal_user_input ();
3402 /* Need to return true for XBUTTON messages, false for others,
3403 to indicate that we processed the message. */
3404 return (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP);
3406 case WM_MOUSEMOVE:
3407 /* Ignore mouse movements as long as the menu is active. These
3408 movements are processed by the window manager anyway, and
3409 it's wrong to handle them as if they happened on the
3410 underlying frame. */
3411 f = x_window_to_frame (dpyinfo, hwnd);
3412 if (f && f->output_data.w32->menubar_active)
3413 return 0;
3415 /* If the mouse has just moved into the frame, start tracking
3416 it, so we will be notified when it leaves the frame. Mouse
3417 tracking only works under W98 and NT4 and later. On earlier
3418 versions, there is no way of telling when the mouse leaves the
3419 frame, so we just have to put up with help-echo and mouse
3420 highlighting remaining while the frame is not active. */
3421 if (track_mouse_event_fn && !track_mouse_window
3422 /* If the menu bar is active, turning on tracking of mouse
3423 movement events might send these events to the tooltip
3424 frame, if the user happens to move the mouse pointer over
3425 the tooltip. But since we don't process events for
3426 tooltip frames, this causes Windows to present a
3427 hourglass cursor, which is ugly and unexpected. So don't
3428 enable tracking mouse events in this case; they will be
3429 restarted when the menu pops down. (Confusingly, the
3430 menubar_active member of f->output_data.w32, tested
3431 above, is only set when a menu was popped up _not_ from
3432 the frame's menu bar, but via x-popup-menu.) */
3433 && !menubar_in_use)
3435 TRACKMOUSEEVENT tme;
3436 tme.cbSize = sizeof (tme);
3437 tme.dwFlags = TME_LEAVE;
3438 tme.hwndTrack = hwnd;
3439 tme.dwHoverTime = HOVER_DEFAULT;
3441 track_mouse_event_fn (&tme);
3442 track_mouse_window = hwnd;
3444 case WM_VSCROLL:
3445 if (w32_mouse_move_interval <= 0
3446 || (msg == WM_MOUSEMOVE && button_state == 0))
3448 wmsg.dwModifiers = w32_get_modifiers ();
3449 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3450 return 0;
3453 /* Hang onto mouse move and scroll messages for a bit, to avoid
3454 sending such events to Emacs faster than it can process them.
3455 If we get more events before the timer from the first message
3456 expires, we just replace the first message. */
3458 if (saved_mouse_move_msg.msg.hwnd == 0)
3459 mouse_move_timer =
3460 SetTimer (hwnd, MOUSE_MOVE_ID,
3461 w32_mouse_move_interval, NULL);
3463 /* Hold onto message for now. */
3464 saved_mouse_move_msg.msg.hwnd = hwnd;
3465 saved_mouse_move_msg.msg.message = msg;
3466 saved_mouse_move_msg.msg.wParam = wParam;
3467 saved_mouse_move_msg.msg.lParam = lParam;
3468 saved_mouse_move_msg.msg.time = GetMessageTime ();
3469 saved_mouse_move_msg.dwModifiers = w32_get_modifiers ();
3471 return 0;
3473 case WM_MOUSEWHEEL:
3474 case WM_DROPFILES:
3475 wmsg.dwModifiers = w32_get_modifiers ();
3476 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3477 signal_user_input ();
3478 return 0;
3480 case WM_APPCOMMAND:
3481 if (w32_pass_multimedia_buttons_to_system)
3482 goto dflt;
3483 /* Otherwise, pass to lisp, the same way we do with mousehwheel. */
3484 case WM_MOUSEHWHEEL:
3485 wmsg.dwModifiers = w32_get_modifiers ();
3486 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3487 signal_user_input ();
3488 /* Non-zero must be returned when WM_MOUSEHWHEEL messages are
3489 handled, to prevent the system trying to handle it by faking
3490 scroll bar events. */
3491 return 1;
3493 case WM_TIMER:
3494 /* Flush out saved messages if necessary. */
3495 if (wParam == mouse_button_timer)
3497 if (saved_mouse_button_msg.msg.hwnd)
3499 post_msg (&saved_mouse_button_msg);
3500 signal_user_input ();
3501 saved_mouse_button_msg.msg.hwnd = 0;
3503 KillTimer (hwnd, mouse_button_timer);
3504 mouse_button_timer = 0;
3506 else if (wParam == mouse_move_timer)
3508 if (saved_mouse_move_msg.msg.hwnd)
3510 post_msg (&saved_mouse_move_msg);
3511 saved_mouse_move_msg.msg.hwnd = 0;
3513 KillTimer (hwnd, mouse_move_timer);
3514 mouse_move_timer = 0;
3516 else if (wParam == menu_free_timer)
3518 KillTimer (hwnd, menu_free_timer);
3519 menu_free_timer = 0;
3520 f = x_window_to_frame (dpyinfo, hwnd);
3521 /* If a popup menu is active, don't wipe its strings. */
3522 if (menubar_in_use
3523 && current_popup_menu == NULL)
3525 /* Free memory used by owner-drawn and help-echo strings. */
3526 w32_free_menu_strings (hwnd);
3527 if (f)
3528 f->output_data.w32->menubar_active = 0;
3529 menubar_in_use = 0;
3532 return 0;
3534 case WM_NCACTIVATE:
3535 /* Windows doesn't send us focus messages when putting up and
3536 taking down a system popup dialog as for Ctrl-Alt-Del on Windows 95.
3537 The only indication we get that something happened is receiving
3538 this message afterwards. So this is a good time to reset our
3539 keyboard modifiers' state. */
3540 reset_modifiers ();
3541 goto dflt;
3543 case WM_INITMENU:
3544 button_state = 0;
3545 ReleaseCapture ();
3546 /* We must ensure menu bar is fully constructed and up to date
3547 before allowing user interaction with it. To achieve this
3548 we send this message to the lisp thread and wait for a
3549 reply (whose value is not actually needed) to indicate that
3550 the menu bar is now ready for use, so we can now return.
3552 To remain responsive in the meantime, we enter a nested message
3553 loop that can process all other messages.
3555 However, we skip all this if the message results from calling
3556 TrackPopupMenu - in fact, we must NOT attempt to send the lisp
3557 thread a message because it is blocked on us at this point. We
3558 set menubar_active before calling TrackPopupMenu to indicate
3559 this (there is no possibility of confusion with real menubar
3560 being active). */
3562 f = x_window_to_frame (dpyinfo, hwnd);
3563 if (f
3564 && (f->output_data.w32->menubar_active
3565 /* We can receive this message even in the absence of a
3566 menubar (ie. when the system menu is activated) - in this
3567 case we do NOT want to forward the message, otherwise it
3568 will cause the menubar to suddenly appear when the user
3569 had requested it to be turned off! */
3570 || f->output_data.w32->menubar_widget == NULL))
3571 return 0;
3574 deferred_msg msg_buf;
3576 /* Detect if message has already been deferred; in this case
3577 we cannot return any sensible value to ignore this. */
3578 if (find_deferred_msg (hwnd, msg) != NULL)
3579 emacs_abort ();
3581 menubar_in_use = 1;
3583 return send_deferred_msg (&msg_buf, hwnd, msg, wParam, lParam);
3586 case WM_EXITMENULOOP:
3587 f = x_window_to_frame (dpyinfo, hwnd);
3589 /* If a menu is still active, check again after a short delay,
3590 since Windows often (always?) sends the WM_EXITMENULOOP
3591 before the corresponding WM_COMMAND message.
3592 Don't do this if a popup menu is active, since it is only
3593 menubar menus that require cleaning up in this way.
3595 if (f && menubar_in_use && current_popup_menu == NULL)
3596 menu_free_timer = SetTimer (hwnd, MENU_FREE_ID, MENU_FREE_DELAY, NULL);
3598 /* If hourglass cursor should be displayed, display it now. */
3599 if (f && f->output_data.w32->hourglass_p)
3600 SetCursor (f->output_data.w32->hourglass_cursor);
3602 goto dflt;
3604 case WM_MENUSELECT:
3605 /* Direct handling of help_echo in menus. Should be safe now
3606 that we generate the help_echo by placing a help event in the
3607 keyboard buffer. */
3609 HMENU menu = (HMENU) lParam;
3610 UINT menu_item = (UINT) LOWORD (wParam);
3611 UINT flags = (UINT) HIWORD (wParam);
3613 w32_menu_display_help (hwnd, menu, menu_item, flags);
3615 return 0;
3617 case WM_MEASUREITEM:
3618 f = x_window_to_frame (dpyinfo, hwnd);
3619 if (f)
3621 MEASUREITEMSTRUCT * pMis = (MEASUREITEMSTRUCT *) lParam;
3623 if (pMis->CtlType == ODT_MENU)
3625 /* Work out dimensions for popup menu titles. */
3626 char * title = (char *) pMis->itemData;
3627 HDC hdc = GetDC (hwnd);
3628 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3629 LOGFONT menu_logfont;
3630 HFONT old_font;
3631 SIZE size;
3633 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3634 menu_logfont.lfWeight = FW_BOLD;
3635 menu_font = CreateFontIndirect (&menu_logfont);
3636 old_font = SelectObject (hdc, menu_font);
3638 pMis->itemHeight = GetSystemMetrics (SM_CYMENUSIZE);
3639 if (title)
3641 if (unicode_append_menu)
3642 GetTextExtentPoint32W (hdc, (WCHAR *) title,
3643 wcslen ((WCHAR *) title),
3644 &size);
3645 else
3646 GetTextExtentPoint32 (hdc, title, strlen (title), &size);
3648 pMis->itemWidth = size.cx;
3649 if (pMis->itemHeight < size.cy)
3650 pMis->itemHeight = size.cy;
3652 else
3653 pMis->itemWidth = 0;
3655 SelectObject (hdc, old_font);
3656 DeleteObject (menu_font);
3657 ReleaseDC (hwnd, hdc);
3658 return TRUE;
3661 return 0;
3663 case WM_DRAWITEM:
3664 f = x_window_to_frame (dpyinfo, hwnd);
3665 if (f)
3667 DRAWITEMSTRUCT * pDis = (DRAWITEMSTRUCT *) lParam;
3669 if (pDis->CtlType == ODT_MENU)
3671 /* Draw popup menu title. */
3672 char * title = (char *) pDis->itemData;
3673 if (title)
3675 HDC hdc = pDis->hDC;
3676 HFONT menu_font = GetCurrentObject (hdc, OBJ_FONT);
3677 LOGFONT menu_logfont;
3678 HFONT old_font;
3680 GetObject (menu_font, sizeof (menu_logfont), &menu_logfont);
3681 menu_logfont.lfWeight = FW_BOLD;
3682 menu_font = CreateFontIndirect (&menu_logfont);
3683 old_font = SelectObject (hdc, menu_font);
3685 /* Always draw title as if not selected. */
3686 if (unicode_append_menu)
3687 ExtTextOutW (hdc,
3688 pDis->rcItem.left
3689 + GetSystemMetrics (SM_CXMENUCHECK),
3690 pDis->rcItem.top,
3691 ETO_OPAQUE, &pDis->rcItem,
3692 (WCHAR *) title,
3693 wcslen ((WCHAR *) title), NULL);
3694 else
3695 ExtTextOut (hdc,
3696 pDis->rcItem.left
3697 + GetSystemMetrics (SM_CXMENUCHECK),
3698 pDis->rcItem.top,
3699 ETO_OPAQUE, &pDis->rcItem,
3700 title, strlen (title), NULL);
3702 SelectObject (hdc, old_font);
3703 DeleteObject (menu_font);
3705 return TRUE;
3708 return 0;
3710 #if 0
3711 /* Still not right - can't distinguish between clicks in the
3712 client area of the frame from clicks forwarded from the scroll
3713 bars - may have to hook WM_NCHITTEST to remember the mouse
3714 position and then check if it is in the client area ourselves. */
3715 case WM_MOUSEACTIVATE:
3716 /* Discard the mouse click that activates a frame, allowing the
3717 user to click anywhere without changing point (or worse!).
3718 Don't eat mouse clicks on scrollbars though!! */
3719 if (LOWORD (lParam) == HTCLIENT )
3720 return MA_ACTIVATEANDEAT;
3721 goto dflt;
3722 #endif
3724 case WM_MOUSELEAVE:
3725 /* No longer tracking mouse. */
3726 track_mouse_window = NULL;
3728 case WM_ACTIVATEAPP:
3729 case WM_ACTIVATE:
3730 case WM_WINDOWPOSCHANGED:
3731 case WM_SHOWWINDOW:
3732 /* Inform lisp thread that a frame might have just been obscured
3733 or exposed, so should recheck visibility of all frames. */
3734 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3735 goto dflt;
3737 case WM_SETFOCUS:
3738 dpyinfo->faked_key = 0;
3739 reset_modifiers ();
3740 register_hot_keys (hwnd);
3741 goto command;
3742 case WM_KILLFOCUS:
3743 unregister_hot_keys (hwnd);
3744 button_state = 0;
3745 ReleaseCapture ();
3746 /* Relinquish the system caret. */
3747 if (w32_system_caret_hwnd)
3749 w32_visible_system_caret_hwnd = NULL;
3750 w32_system_caret_hwnd = NULL;
3751 DestroyCaret ();
3753 goto command;
3754 case WM_COMMAND:
3755 menubar_in_use = 0;
3756 f = x_window_to_frame (dpyinfo, hwnd);
3757 if (f && HIWORD (wParam) == 0)
3759 if (menu_free_timer)
3761 KillTimer (hwnd, menu_free_timer);
3762 menu_free_timer = 0;
3765 case WM_MOVE:
3766 case WM_SIZE:
3767 command:
3768 wmsg.dwModifiers = w32_get_modifiers ();
3769 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3770 goto dflt;
3772 case WM_DESTROY:
3773 CoUninitialize ();
3774 return 0;
3776 case WM_CLOSE:
3777 wmsg.dwModifiers = w32_get_modifiers ();
3778 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
3779 return 0;
3781 case WM_WINDOWPOSCHANGING:
3782 /* Don't restrict the sizing of tip frames. */
3783 if (frame_resize_pixelwise || hwnd == tip_window)
3784 return 0;
3786 /* Don't restrict the sizing of fullscreened frames, allowing them to be
3787 flush with the sides of the screen. */
3788 f = x_window_to_frame (dpyinfo, hwnd);
3789 if (f && FRAME_PREV_FSMODE (f) != FULLSCREEN_NONE)
3790 return 0;
3793 WINDOWPLACEMENT wp;
3794 LPWINDOWPOS lppos = (WINDOWPOS *) lParam;
3796 wp.length = sizeof (WINDOWPLACEMENT);
3797 GetWindowPlacement (hwnd, &wp);
3799 if (wp.showCmd != SW_SHOWMAXIMIZED && wp.showCmd != SW_SHOWMINIMIZED
3800 && (lppos->flags & SWP_NOSIZE) == 0)
3802 RECT rect;
3803 int wdiff;
3804 int hdiff;
3805 DWORD font_width;
3806 DWORD line_height;
3807 DWORD internal_border;
3808 DWORD scrollbar_extra;
3809 RECT wr;
3811 wp.length = sizeof (wp);
3812 GetWindowRect (hwnd, &wr);
3814 enter_crit ();
3816 font_width = GetWindowLong (hwnd, WND_FONTWIDTH_INDEX);
3817 line_height = GetWindowLong (hwnd, WND_LINEHEIGHT_INDEX);
3818 internal_border = GetWindowLong (hwnd, WND_BORDER_INDEX);
3819 scrollbar_extra = GetWindowLong (hwnd, WND_SCROLLBAR_INDEX);
3821 leave_crit ();
3823 memset (&rect, 0, sizeof (rect));
3824 AdjustWindowRect (&rect, GetWindowLong (hwnd, GWL_STYLE),
3825 GetMenu (hwnd) != NULL);
3827 /* Force width and height of client area to be exact
3828 multiples of the character cell dimensions. */
3829 wdiff = (lppos->cx - (rect.right - rect.left)
3830 - 2 * internal_border - scrollbar_extra)
3831 % font_width;
3832 hdiff = (lppos->cy - (rect.bottom - rect.top)
3833 - 2 * internal_border)
3834 % line_height;
3836 if (wdiff || hdiff)
3838 /* For right/bottom sizing we can just fix the sizes.
3839 However for top/left sizing we will need to fix the X
3840 and Y positions as well. */
3842 int cx_mintrack = GetSystemMetrics (SM_CXMINTRACK);
3843 int cy_mintrack = GetSystemMetrics (SM_CYMINTRACK);
3845 lppos->cx = max (lppos->cx - wdiff, cx_mintrack);
3846 lppos->cy = max (lppos->cy - hdiff, cy_mintrack);
3848 if (wp.showCmd != SW_SHOWMAXIMIZED
3849 && (lppos->flags & SWP_NOMOVE) == 0)
3851 if (lppos->x != wr.left || lppos->y != wr.top)
3853 lppos->x += wdiff;
3854 lppos->y += hdiff;
3856 else
3858 lppos->flags |= SWP_NOMOVE;
3862 return 0;
3867 goto dflt;
3869 case WM_GETMINMAXINFO:
3870 /* Hack to allow resizing the Emacs frame above the screen size.
3871 Note that Windows 9x limits coordinates to 16-bits. */
3872 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.x = 32767;
3873 ((LPMINMAXINFO) lParam)->ptMaxTrackSize.y = 32767;
3874 return 0;
3876 case WM_SETCURSOR:
3877 if (LOWORD (lParam) == HTCLIENT)
3879 f = x_window_to_frame (dpyinfo, hwnd);
3880 if (f && f->output_data.w32->hourglass_p
3881 && !menubar_in_use && !current_popup_menu)
3882 SetCursor (f->output_data.w32->hourglass_cursor);
3883 else if (f)
3884 SetCursor (f->output_data.w32->current_cursor);
3885 return 0;
3887 goto dflt;
3889 case WM_EMACS_SETCURSOR:
3891 Cursor cursor = (Cursor) wParam;
3892 f = x_window_to_frame (dpyinfo, hwnd);
3893 if (f && cursor)
3895 f->output_data.w32->current_cursor = cursor;
3896 if (!f->output_data.w32->hourglass_p)
3897 SetCursor (cursor);
3899 return 0;
3902 case WM_EMACS_CREATESCROLLBAR:
3903 return (LRESULT) w32_createscrollbar ((struct frame *) wParam,
3904 (struct scroll_bar *) lParam);
3906 case WM_EMACS_SHOWWINDOW:
3907 return ShowWindow ((HWND) wParam, (WPARAM) lParam);
3909 case WM_EMACS_BRINGTOTOP:
3910 case WM_EMACS_SETFOREGROUND:
3912 HWND foreground_window;
3913 DWORD foreground_thread, retval;
3915 /* On NT 5.0, and apparently Windows 98, it is necessary to
3916 attach to the thread that currently has focus in order to
3917 pull the focus away from it. */
3918 foreground_window = GetForegroundWindow ();
3919 foreground_thread = GetWindowThreadProcessId (foreground_window, NULL);
3920 if (!foreground_window
3921 || foreground_thread == GetCurrentThreadId ()
3922 || !AttachThreadInput (GetCurrentThreadId (),
3923 foreground_thread, TRUE))
3924 foreground_thread = 0;
3926 retval = SetForegroundWindow ((HWND) wParam);
3927 if (msg == WM_EMACS_BRINGTOTOP)
3928 retval = BringWindowToTop ((HWND) wParam);
3930 /* Detach from the previous foreground thread. */
3931 if (foreground_thread)
3932 AttachThreadInput (GetCurrentThreadId (),
3933 foreground_thread, FALSE);
3935 return retval;
3938 case WM_EMACS_SETWINDOWPOS:
3940 WINDOWPOS * pos = (WINDOWPOS *) wParam;
3941 return SetWindowPos (hwnd, pos->hwndInsertAfter,
3942 pos->x, pos->y, pos->cx, pos->cy, pos->flags);
3945 case WM_EMACS_DESTROYWINDOW:
3946 DragAcceptFiles ((HWND) wParam, FALSE);
3947 return DestroyWindow ((HWND) wParam);
3949 case WM_EMACS_HIDE_CARET:
3950 return HideCaret (hwnd);
3952 case WM_EMACS_SHOW_CARET:
3953 return ShowCaret (hwnd);
3955 case WM_EMACS_DESTROY_CARET:
3956 w32_system_caret_hwnd = NULL;
3957 w32_visible_system_caret_hwnd = NULL;
3958 return DestroyCaret ();
3960 case WM_EMACS_TRACK_CARET:
3961 /* If there is currently no system caret, create one. */
3962 if (w32_system_caret_hwnd == NULL)
3964 /* Use the default caret width, and avoid changing it
3965 unnecessarily, as it confuses screen reader software. */
3966 w32_system_caret_hwnd = hwnd;
3967 CreateCaret (hwnd, NULL, 0,
3968 w32_system_caret_height);
3971 if (!SetCaretPos (w32_system_caret_x, w32_system_caret_y))
3972 return 0;
3973 /* Ensure visible caret gets turned on when requested. */
3974 else if (w32_use_visible_system_caret
3975 && w32_visible_system_caret_hwnd != hwnd)
3977 w32_visible_system_caret_hwnd = hwnd;
3978 return ShowCaret (hwnd);
3980 /* Ensure visible caret gets turned off when requested. */
3981 else if (!w32_use_visible_system_caret
3982 && w32_visible_system_caret_hwnd)
3984 w32_visible_system_caret_hwnd = NULL;
3985 return HideCaret (hwnd);
3987 else
3988 return 1;
3990 case WM_EMACS_TRACKPOPUPMENU:
3992 UINT flags;
3993 POINT *pos;
3994 int retval;
3995 pos = (POINT *)lParam;
3996 flags = TPM_CENTERALIGN;
3997 if (button_state & LMOUSE)
3998 flags |= TPM_LEFTBUTTON;
3999 else if (button_state & RMOUSE)
4000 flags |= TPM_RIGHTBUTTON;
4002 /* Remember we did a SetCapture on the initial mouse down event,
4003 so for safety, we make sure the capture is canceled now. */
4004 ReleaseCapture ();
4005 button_state = 0;
4007 /* Use menubar_active to indicate that WM_INITMENU is from
4008 TrackPopupMenu below, and should be ignored. */
4009 f = x_window_to_frame (dpyinfo, hwnd);
4010 if (f)
4011 f->output_data.w32->menubar_active = 1;
4013 if (TrackPopupMenu ((HMENU)wParam, flags, pos->x, pos->y,
4014 0, hwnd, NULL))
4016 MSG amsg;
4017 /* Eat any mouse messages during popupmenu */
4018 while (PeekMessage (&amsg, hwnd, WM_MOUSEFIRST, WM_MOUSELAST,
4019 PM_REMOVE));
4020 /* Get the menu selection, if any */
4021 if (PeekMessage (&amsg, hwnd, WM_COMMAND, WM_COMMAND, PM_REMOVE))
4023 retval = LOWORD (amsg.wParam);
4025 else
4027 retval = 0;
4030 else
4032 retval = -1;
4035 return retval;
4037 case WM_EMACS_FILENOTIFY:
4038 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4039 return 1;
4041 default:
4042 /* Check for messages registered at runtime. */
4043 if (msg == msh_mousewheel)
4045 wmsg.dwModifiers = w32_get_modifiers ();
4046 my_post_msg (&wmsg, hwnd, msg, wParam, lParam);
4047 signal_user_input ();
4048 return 0;
4051 dflt:
4052 return (w32_unicode_gui ? DefWindowProcW : DefWindowProcA) (hwnd, msg, wParam, lParam);
4055 /* The most common default return code for handled messages is 0. */
4056 return 0;
4059 static void
4060 my_create_window (struct frame * f)
4062 MSG msg;
4064 if (!PostThreadMessage (dwWindowsThreadId, WM_EMACS_CREATEWINDOW, (WPARAM)f, 0))
4065 emacs_abort ();
4066 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
4070 /* Create a tooltip window. Unlike my_create_window, we do not do this
4071 indirectly via the Window thread, as we do not need to process Window
4072 messages for the tooltip. Creating tooltips indirectly also creates
4073 deadlocks when tooltips are created for menu items. */
4074 static void
4075 my_create_tip_window (struct frame *f)
4077 RECT rect;
4079 rect.left = rect.top = 0;
4080 rect.right = FRAME_PIXEL_WIDTH (f);
4081 rect.bottom = FRAME_PIXEL_HEIGHT (f);
4083 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
4084 FRAME_EXTERNAL_MENU_BAR (f));
4086 tip_window = FRAME_W32_WINDOW (f)
4087 = CreateWindow (EMACS_CLASS,
4088 f->namebuf,
4089 f->output_data.w32->dwStyle,
4090 f->left_pos,
4091 f->top_pos,
4092 rect.right - rect.left,
4093 rect.bottom - rect.top,
4094 FRAME_W32_WINDOW (SELECTED_FRAME ()), /* owner */
4095 NULL,
4096 hinst,
4097 NULL);
4099 if (tip_window)
4101 SetWindowLong (tip_window, WND_FONTWIDTH_INDEX, FRAME_COLUMN_WIDTH (f));
4102 SetWindowLong (tip_window, WND_LINEHEIGHT_INDEX, FRAME_LINE_HEIGHT (f));
4103 SetWindowLong (tip_window, WND_BORDER_INDEX, FRAME_INTERNAL_BORDER_WIDTH (f));
4104 SetWindowLong (tip_window, WND_BACKGROUND_INDEX, FRAME_BACKGROUND_PIXEL (f));
4106 /* Tip frames have no scrollbars. */
4107 SetWindowLong (tip_window, WND_SCROLLBAR_INDEX, 0);
4109 /* Do this to discard the default setting specified by our parent. */
4110 ShowWindow (tip_window, SW_HIDE);
4115 /* Create and set up the w32 window for frame F. */
4117 static void
4118 w32_window (struct frame *f, long window_prompting, int minibuffer_only)
4120 block_input ();
4122 /* Use the resource name as the top-level window name
4123 for looking up resources. Make a non-Lisp copy
4124 for the window manager, so GC relocation won't bother it.
4126 Elsewhere we specify the window name for the window manager. */
4127 f->namebuf = xstrdup (SSDATA (Vx_resource_name));
4129 my_create_window (f);
4131 validate_x_resource_name ();
4133 /* x_set_name normally ignores requests to set the name if the
4134 requested name is the same as the current name. This is the one
4135 place where that assumption isn't correct; f->name is set, but
4136 the server hasn't been told. */
4138 Lisp_Object name;
4139 int explicit = f->explicit_name;
4141 f->explicit_name = 0;
4142 name = f->name;
4143 fset_name (f, Qnil);
4144 x_set_name (f, name, explicit);
4147 unblock_input ();
4149 if (!minibuffer_only && FRAME_EXTERNAL_MENU_BAR (f))
4150 initialize_frame_menubar (f);
4152 if (FRAME_W32_WINDOW (f) == 0)
4153 error ("Unable to create window");
4156 /* Handle the icon stuff for this window. Perhaps later we might
4157 want an x_set_icon_position which can be called interactively as
4158 well. */
4160 static void
4161 x_icon (struct frame *f, Lisp_Object parms)
4163 Lisp_Object icon_x, icon_y;
4164 struct w32_display_info *dpyinfo = &one_w32_display_info;
4166 /* Set the position of the icon. Note that Windows 95 groups all
4167 icons in the tray. */
4168 icon_x = x_get_arg (dpyinfo, parms, Qicon_left, 0, 0, RES_TYPE_NUMBER);
4169 icon_y = x_get_arg (dpyinfo, parms, Qicon_top, 0, 0, RES_TYPE_NUMBER);
4170 if (!EQ (icon_x, Qunbound) && !EQ (icon_y, Qunbound))
4172 CHECK_NUMBER (icon_x);
4173 CHECK_NUMBER (icon_y);
4175 else if (!EQ (icon_x, Qunbound) || !EQ (icon_y, Qunbound))
4176 error ("Both left and top icon corners of icon must be specified");
4178 block_input ();
4180 #if 0 /* TODO */
4181 /* Start up iconic or window? */
4182 x_wm_set_window_state
4183 (f, (EQ (x_get_arg (dpyinfo, parms, Qvisibility, 0, 0, RES_TYPE_SYMBOL), Qicon)
4184 ? IconicState
4185 : NormalState));
4187 x_text_icon (f, SSDATA ((!NILP (f->icon_name)
4188 ? f->icon_name
4189 : f->name)));
4190 #endif
4192 unblock_input ();
4196 static void
4197 x_make_gc (struct frame *f)
4199 XGCValues gc_values;
4201 block_input ();
4203 /* Create the GC's of this frame.
4204 Note that many default values are used. */
4206 /* Normal video */
4207 gc_values.font = FRAME_FONT (f);
4209 /* Cursor has cursor-color background, background-color foreground. */
4210 gc_values.foreground = FRAME_BACKGROUND_PIXEL (f);
4211 gc_values.background = f->output_data.w32->cursor_pixel;
4212 f->output_data.w32->cursor_gc
4213 = XCreateGC (NULL, FRAME_W32_WINDOW (f),
4214 (GCFont | GCForeground | GCBackground),
4215 &gc_values);
4217 /* Reliefs. */
4218 f->output_data.w32->white_relief.gc = 0;
4219 f->output_data.w32->black_relief.gc = 0;
4221 unblock_input ();
4225 /* Handler for signals raised during x_create_frame and
4226 x_create_tip_frame. FRAME is the frame which is partially
4227 constructed. */
4229 static Lisp_Object
4230 unwind_create_frame (Lisp_Object frame)
4232 struct frame *f = XFRAME (frame);
4234 /* If frame is ``official'', nothing to do. */
4235 if (NILP (Fmemq (frame, Vframe_list)))
4237 #ifdef GLYPH_DEBUG
4238 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4240 /* If the frame's image cache refcount is still the same as our
4241 private shadow variable, it means we are unwinding a frame
4242 for which we didn't yet call init_frame_faces, where the
4243 refcount is incremented. Therefore, we increment it here, so
4244 that free_frame_faces, called in x_free_frame_resources
4245 below, will not mistakenly decrement the counter that was not
4246 incremented yet to account for this new frame. */
4247 if (FRAME_IMAGE_CACHE (f) != NULL
4248 && FRAME_IMAGE_CACHE (f)->refcount == image_cache_refcount)
4249 FRAME_IMAGE_CACHE (f)->refcount++;
4250 #endif
4252 x_free_frame_resources (f);
4253 free_glyphs (f);
4255 #ifdef GLYPH_DEBUG
4256 /* Check that reference counts are indeed correct. */
4257 eassert (dpyinfo->reference_count == dpyinfo_refcount);
4258 eassert ((dpyinfo->terminal->image_cache == NULL
4259 && image_cache_refcount == 0)
4260 || (dpyinfo->terminal->image_cache != NULL
4261 && dpyinfo->terminal->image_cache->refcount == image_cache_refcount));
4262 #endif
4263 return Qt;
4266 return Qnil;
4269 static void
4270 do_unwind_create_frame (Lisp_Object frame)
4272 unwind_create_frame (frame);
4275 static void
4276 unwind_create_frame_1 (Lisp_Object val)
4278 inhibit_lisp_code = val;
4281 static void
4282 x_default_font_parameter (struct frame *f, Lisp_Object parms)
4284 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (f);
4285 Lisp_Object font_param = x_get_arg (dpyinfo, parms, Qfont, NULL, NULL,
4286 RES_TYPE_STRING);
4287 Lisp_Object font;
4288 if (EQ (font_param, Qunbound))
4289 font_param = Qnil;
4290 font = !NILP (font_param) ? font_param
4291 : x_get_arg (dpyinfo, parms, Qfont, "font", "Font", RES_TYPE_STRING);
4293 if (!STRINGP (font))
4295 int i;
4296 static char *names[]
4297 = { "Courier New-10",
4298 "-*-Courier-normal-r-*-*-13-*-*-*-c-*-iso8859-1",
4299 "-*-Fixedsys-normal-r-*-*-12-*-*-*-c-*-iso8859-1",
4300 "Fixedsys",
4301 NULL };
4303 for (i = 0; names[i]; i++)
4305 font = font_open_by_name (f, build_unibyte_string (names[i]));
4306 if (! NILP (font))
4307 break;
4309 if (NILP (font))
4310 error ("No suitable font was found");
4312 else if (!NILP (font_param))
4314 /* Remember the explicit font parameter, so we can re-apply it after
4315 we've applied the `default' face settings. */
4316 x_set_frame_parameters (f, Fcons (Fcons (Qfont_param, font_param), Qnil));
4318 x_default_parameter (f, parms, Qfont, font, "font", "Font", RES_TYPE_STRING);
4321 DEFUN ("x-create-frame", Fx_create_frame, Sx_create_frame,
4322 1, 1, 0,
4323 doc: /* Make a new window, which is called a \"frame\" in Emacs terms.
4324 Return an Emacs frame object.
4325 PARAMETERS is an alist of frame parameters.
4326 If the parameters specify that the frame should not have a minibuffer,
4327 and do not specify a specific minibuffer window to use,
4328 then `default-minibuffer-frame' must be a frame whose minibuffer can
4329 be shared by the new frame.
4331 This function is an internal primitive--use `make-frame' instead. */)
4332 (Lisp_Object parameters)
4334 struct frame *f;
4335 Lisp_Object frame, tem;
4336 Lisp_Object name;
4337 int minibuffer_only = 0;
4338 long window_prompting = 0;
4339 int width, height;
4340 ptrdiff_t count = SPECPDL_INDEX ();
4341 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
4342 Lisp_Object display;
4343 struct w32_display_info *dpyinfo = NULL;
4344 Lisp_Object parent;
4345 struct kboard *kb;
4347 if (!FRAME_W32_P (SELECTED_FRAME ())
4348 && !FRAME_INITIAL_P (SELECTED_FRAME ()))
4349 error ("Cannot create a GUI frame in a -nw session");
4351 /* Make copy of frame parameters because the original is in pure
4352 storage now. */
4353 parameters = Fcopy_alist (parameters);
4355 /* Use this general default value to start with
4356 until we know if this frame has a specified name. */
4357 Vx_resource_name = Vinvocation_name;
4359 display = x_get_arg (dpyinfo, parameters, Qterminal, 0, 0, RES_TYPE_NUMBER);
4360 if (EQ (display, Qunbound))
4361 display = x_get_arg (dpyinfo, parameters, Qdisplay, 0, 0, RES_TYPE_STRING);
4362 if (EQ (display, Qunbound))
4363 display = Qnil;
4364 dpyinfo = check_x_display_info (display);
4365 kb = dpyinfo->terminal->kboard;
4367 if (!dpyinfo->terminal->name)
4368 error ("Terminal is not live, can't create new frames on it");
4370 name = x_get_arg (dpyinfo, parameters, Qname, "name", "Name", RES_TYPE_STRING);
4371 if (!STRINGP (name)
4372 && ! EQ (name, Qunbound)
4373 && ! NILP (name))
4374 error ("Invalid frame name--not a string or nil");
4376 if (STRINGP (name))
4377 Vx_resource_name = name;
4379 /* See if parent window is specified. */
4380 parent = x_get_arg (dpyinfo, parameters, Qparent_id, NULL, NULL, RES_TYPE_NUMBER);
4381 if (EQ (parent, Qunbound))
4382 parent = Qnil;
4383 if (! NILP (parent))
4384 CHECK_NUMBER (parent);
4386 /* make_frame_without_minibuffer can run Lisp code and garbage collect. */
4387 /* No need to protect DISPLAY because that's not used after passing
4388 it to make_frame_without_minibuffer. */
4389 frame = Qnil;
4390 GCPRO4 (parameters, parent, name, frame);
4391 tem = x_get_arg (dpyinfo, parameters, Qminibuffer, "minibuffer", "Minibuffer",
4392 RES_TYPE_SYMBOL);
4393 if (EQ (tem, Qnone) || NILP (tem))
4394 f = make_frame_without_minibuffer (Qnil, kb, display);
4395 else if (EQ (tem, Qonly))
4397 f = make_minibuffer_frame ();
4398 minibuffer_only = 1;
4400 else if (WINDOWP (tem))
4401 f = make_frame_without_minibuffer (tem, kb, display);
4402 else
4403 f = make_frame (1);
4405 XSETFRAME (frame, f);
4407 /* By default, make scrollbars the system standard width. */
4408 x_set_scroll_bar_default_width (f);
4410 f->terminal = dpyinfo->terminal;
4412 f->output_method = output_w32;
4413 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
4414 FRAME_FONTSET (f) = -1;
4416 fset_icon_name
4417 (f, x_get_arg (dpyinfo, parameters, Qicon_name, "iconName", "Title",
4418 RES_TYPE_STRING));
4419 if (! STRINGP (f->icon_name))
4420 fset_icon_name (f, Qnil);
4422 /* FRAME_DISPLAY_INFO (f) = dpyinfo; */
4424 /* With FRAME_DISPLAY_INFO set up, this unwind-protect is safe. */
4425 record_unwind_protect (do_unwind_create_frame, frame);
4427 #ifdef GLYPH_DEBUG
4428 image_cache_refcount =
4429 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
4430 dpyinfo_refcount = dpyinfo->reference_count;
4431 #endif /* GLYPH_DEBUG */
4433 /* Specify the parent under which to make this window. */
4435 if (!NILP (parent))
4437 f->output_data.w32->parent_desc = (Window) XFASTINT (parent);
4438 f->output_data.w32->explicit_parent = 1;
4440 else
4442 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4443 f->output_data.w32->explicit_parent = 0;
4446 /* Set the name; the functions to which we pass f expect the name to
4447 be set. */
4448 if (EQ (name, Qunbound) || NILP (name))
4450 fset_name (f, build_string (dpyinfo->w32_id_name));
4451 f->explicit_name = 0;
4453 else
4455 fset_name (f, name);
4456 f->explicit_name = 1;
4457 /* use the frame's title when getting resources for this frame. */
4458 specbind (Qx_resource_name, name);
4461 if (uniscribe_available)
4462 register_font_driver (&uniscribe_font_driver, f);
4463 register_font_driver (&w32font_driver, f);
4465 x_default_parameter (f, parameters, Qfont_backend, Qnil,
4466 "fontBackend", "FontBackend", RES_TYPE_STRING);
4467 /* Extract the window parameters from the supplied values
4468 that are needed to determine window geometry. */
4469 x_default_font_parameter (f, parameters);
4470 x_default_parameter (f, parameters, Qborder_width, make_number (2),
4471 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
4473 /* We recognize either internalBorderWidth or internalBorder
4474 (which is what xterm calls it). */
4475 if (NILP (Fassq (Qinternal_border_width, parameters)))
4477 Lisp_Object value;
4479 value = x_get_arg (dpyinfo, parameters, Qinternal_border_width,
4480 "internalBorder", "InternalBorder", RES_TYPE_NUMBER);
4481 if (! EQ (value, Qunbound))
4482 parameters = Fcons (Fcons (Qinternal_border_width, value),
4483 parameters);
4485 /* Default internalBorderWidth to 0 on Windows to match other programs. */
4486 x_default_parameter (f, parameters, Qinternal_border_width, make_number (0),
4487 "internalBorderWidth", "InternalBorder", RES_TYPE_NUMBER);
4488 x_default_parameter (f, parameters, Qright_divider_width, make_number (0),
4489 NULL, NULL, RES_TYPE_NUMBER);
4490 x_default_parameter (f, parameters, Qbottom_divider_width, make_number (0),
4491 NULL, NULL, RES_TYPE_NUMBER);
4492 x_default_parameter (f, parameters, Qvertical_scroll_bars, Qright,
4493 "verticalScrollBars", "ScrollBars", RES_TYPE_SYMBOL);
4495 /* Also do the stuff which must be set before the window exists. */
4496 x_default_parameter (f, parameters, Qforeground_color, build_string ("black"),
4497 "foreground", "Foreground", RES_TYPE_STRING);
4498 x_default_parameter (f, parameters, Qbackground_color, build_string ("white"),
4499 "background", "Background", RES_TYPE_STRING);
4500 x_default_parameter (f, parameters, Qmouse_color, build_string ("black"),
4501 "pointerColor", "Foreground", RES_TYPE_STRING);
4502 x_default_parameter (f, parameters, Qborder_color, build_string ("black"),
4503 "borderColor", "BorderColor", RES_TYPE_STRING);
4504 x_default_parameter (f, parameters, Qscreen_gamma, Qnil,
4505 "screenGamma", "ScreenGamma", RES_TYPE_FLOAT);
4506 x_default_parameter (f, parameters, Qline_spacing, Qnil,
4507 "lineSpacing", "LineSpacing", RES_TYPE_NUMBER);
4508 x_default_parameter (f, parameters, Qleft_fringe, Qnil,
4509 "leftFringe", "LeftFringe", RES_TYPE_NUMBER);
4510 x_default_parameter (f, parameters, Qright_fringe, Qnil,
4511 "rightFringe", "RightFringe", RES_TYPE_NUMBER);
4512 /* Process alpha here (Bug#16619). */
4513 x_default_parameter (f, parameters, Qalpha, Qnil,
4514 "alpha", "Alpha", RES_TYPE_NUMBER);
4516 /* Init faces before x_default_parameter is called for scroll-bar
4517 parameters because that function calls x_set_scroll_bar_width,
4518 which calls change_frame_size, which calls Fset_window_buffer,
4519 which runs hooks, which call Fvertical_motion. At the end, we
4520 end up in init_iterator with a null face cache, which should not
4521 happen. */
4522 init_frame_faces (f);
4524 /* Avoid calling window-configuration-change-hook; otherwise we
4525 could get an infloop in next_frame since the frame is not yet in
4526 Vframe_list. */
4528 ptrdiff_t count2 = SPECPDL_INDEX ();
4530 record_unwind_protect (unwind_create_frame_1, inhibit_lisp_code);
4531 inhibit_lisp_code = Qt;
4533 /* PXW: This is a duplicate from below. We have to do it here since
4534 otherwise x_set_tool_bar_lines will work with the character sizes
4535 installed by init_frame_faces while the frame's pixel size is still
4536 calculated from a character size of 1 and we subsequently hit the
4537 eassert (height >= 0) assertion in window_box_height. The
4538 non-pixelwise code apparently worked around this because it had one
4539 frame line vs one toolbar line which left us with a zero root
4540 window height which was obviously wrong as well ... */
4541 change_frame_size (f, FRAME_COLS (f) * FRAME_COLUMN_WIDTH (f),
4542 FRAME_LINES (f) * FRAME_LINE_HEIGHT (f), 1, 0, 0, 1);
4544 /* The X resources controlling the menu-bar and tool-bar are
4545 processed specially at startup, and reflected in the mode
4546 variables; ignore them here. */
4547 x_default_parameter (f, parameters, Qmenu_bar_lines,
4548 NILP (Vmenu_bar_mode)
4549 ? make_number (0) : make_number (1),
4550 NULL, NULL, RES_TYPE_NUMBER);
4551 x_default_parameter (f, parameters, Qtool_bar_lines,
4552 NILP (Vtool_bar_mode)
4553 ? make_number (0) : make_number (1),
4554 NULL, NULL, RES_TYPE_NUMBER);
4556 unbind_to (count2, Qnil);
4559 x_default_parameter (f, parameters, Qbuffer_predicate, Qnil,
4560 "bufferPredicate", "BufferPredicate", RES_TYPE_SYMBOL);
4561 x_default_parameter (f, parameters, Qtitle, Qnil,
4562 "title", "Title", RES_TYPE_STRING);
4563 x_default_parameter (f, parameters, Qfullscreen, Qnil,
4564 "fullscreen", "Fullscreen", RES_TYPE_SYMBOL);
4566 f->output_data.w32->dwStyle = WS_OVERLAPPEDWINDOW;
4567 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
4569 f->output_data.w32->text_cursor = w32_load_cursor (IDC_IBEAM);
4570 f->output_data.w32->nontext_cursor = w32_load_cursor (IDC_ARROW);
4571 f->output_data.w32->modeline_cursor = w32_load_cursor (IDC_ARROW);
4572 f->output_data.w32->hand_cursor = w32_load_cursor (IDC_HAND);
4573 f->output_data.w32->hourglass_cursor = w32_load_cursor (IDC_WAIT);
4574 f->output_data.w32->horizontal_drag_cursor = w32_load_cursor (IDC_SIZEWE);
4575 f->output_data.w32->vertical_drag_cursor = w32_load_cursor (IDC_SIZENS);
4577 f->output_data.w32->current_cursor = f->output_data.w32->nontext_cursor;
4579 window_prompting = x_figure_window_size (f, parameters, 1);
4581 tem = x_get_arg (dpyinfo, parameters, Qunsplittable, 0, 0, RES_TYPE_BOOLEAN);
4582 f->no_split = minibuffer_only || EQ (tem, Qt);
4584 w32_window (f, window_prompting, minibuffer_only);
4585 x_icon (f, parameters);
4587 x_make_gc (f);
4589 /* Now consider the frame official. */
4590 f->terminal->reference_count++;
4591 FRAME_DISPLAY_INFO (f)->reference_count++;
4592 Vframe_list = Fcons (frame, Vframe_list);
4594 /* We need to do this after creating the window, so that the
4595 icon-creation functions can say whose icon they're describing. */
4596 x_default_parameter (f, parameters, Qicon_type, Qnil,
4597 "bitmapIcon", "BitmapIcon", RES_TYPE_SYMBOL);
4599 x_default_parameter (f, parameters, Qauto_raise, Qnil,
4600 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4601 x_default_parameter (f, parameters, Qauto_lower, Qnil,
4602 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
4603 x_default_parameter (f, parameters, Qcursor_type, Qbox,
4604 "cursorType", "CursorType", RES_TYPE_SYMBOL);
4605 x_default_parameter (f, parameters, Qscroll_bar_width, Qnil,
4606 "scrollBarWidth", "ScrollBarWidth", RES_TYPE_NUMBER);
4608 /* Dimensions, especially FRAME_LINES (f), must be done via change_frame_size.
4609 Change will not be effected unless different from the current
4610 FRAME_LINES (f). */
4611 width = FRAME_TEXT_WIDTH (f);
4612 height = FRAME_TEXT_HEIGHT (f);
4613 FRAME_TEXT_HEIGHT (f) = 0;
4614 SET_FRAME_WIDTH (f, 0);
4615 change_frame_size (f, width, height, 1, 0, 0, 1);
4617 /* Tell the server what size and position, etc, we want, and how
4618 badly we want them. This should be done after we have the menu
4619 bar so that its size can be taken into account. */
4620 block_input ();
4621 x_wm_set_size_hint (f, window_prompting, 0);
4622 unblock_input ();
4624 /* Make the window appear on the frame and enable display, unless
4625 the caller says not to. However, with explicit parent, Emacs
4626 cannot control visibility, so don't try. */
4627 if (! f->output_data.w32->explicit_parent)
4629 Lisp_Object visibility;
4631 visibility = x_get_arg (dpyinfo, parameters, Qvisibility, 0, 0, RES_TYPE_SYMBOL);
4632 if (EQ (visibility, Qunbound))
4633 visibility = Qt;
4635 if (EQ (visibility, Qicon))
4636 x_iconify_frame (f);
4637 else if (! NILP (visibility))
4638 x_make_frame_visible (f);
4639 else
4640 /* Must have been Qnil. */
4644 /* Initialize `default-minibuffer-frame' in case this is the first
4645 frame on this terminal. */
4646 if (FRAME_HAS_MINIBUF_P (f)
4647 && (!FRAMEP (KVAR (kb, Vdefault_minibuffer_frame))
4648 || !FRAME_LIVE_P (XFRAME (KVAR (kb, Vdefault_minibuffer_frame)))))
4649 kset_default_minibuffer_frame (kb, frame);
4651 /* All remaining specified parameters, which have not been "used"
4652 by x_get_arg and friends, now go in the misc. alist of the frame. */
4653 for (tem = parameters; CONSP (tem); tem = XCDR (tem))
4654 if (CONSP (XCAR (tem)) && !NILP (XCAR (XCAR (tem))))
4655 fset_param_alist (f, Fcons (XCAR (tem), f->param_alist));
4657 UNGCPRO;
4659 /* Make sure windows on this frame appear in calls to next-window
4660 and similar functions. */
4661 Vwindow_list = Qnil;
4663 return unbind_to (count, frame);
4666 /* FRAME is used only to get a handle on the X display. We don't pass the
4667 display info directly because we're called from frame.c, which doesn't
4668 know about that structure. */
4669 Lisp_Object
4670 x_get_focus_frame (struct frame *frame)
4672 struct w32_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
4673 Lisp_Object xfocus;
4674 if (! dpyinfo->w32_focus_frame)
4675 return Qnil;
4677 XSETFRAME (xfocus, dpyinfo->w32_focus_frame);
4678 return xfocus;
4681 DEFUN ("xw-color-defined-p", Fxw_color_defined_p, Sxw_color_defined_p, 1, 2, 0,
4682 doc: /* Internal function called by `color-defined-p', which see.
4683 \(Note that the Nextstep version of this function ignores FRAME.) */)
4684 (Lisp_Object color, Lisp_Object frame)
4686 XColor foo;
4687 struct frame *f = decode_window_system_frame (frame);
4689 CHECK_STRING (color);
4691 if (w32_defined_color (f, SDATA (color), &foo, 0))
4692 return Qt;
4693 else
4694 return Qnil;
4697 DEFUN ("xw-color-values", Fxw_color_values, Sxw_color_values, 1, 2, 0,
4698 doc: /* Internal function called by `color-values', which see. */)
4699 (Lisp_Object color, Lisp_Object frame)
4701 XColor foo;
4702 struct frame *f = decode_window_system_frame (frame);
4704 CHECK_STRING (color);
4706 if (w32_defined_color (f, SDATA (color), &foo, 0))
4707 return list3i ((GetRValue (foo.pixel) << 8) | GetRValue (foo.pixel),
4708 (GetGValue (foo.pixel) << 8) | GetGValue (foo.pixel),
4709 (GetBValue (foo.pixel) << 8) | GetBValue (foo.pixel));
4710 else
4711 return Qnil;
4714 DEFUN ("xw-display-color-p", Fxw_display_color_p, Sxw_display_color_p, 0, 1, 0,
4715 doc: /* Internal function called by `display-color-p', which see. */)
4716 (Lisp_Object display)
4718 struct w32_display_info *dpyinfo = check_x_display_info (display);
4720 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 2)
4721 return Qnil;
4723 return Qt;
4726 DEFUN ("x-display-grayscale-p", Fx_display_grayscale_p,
4727 Sx_display_grayscale_p, 0, 1, 0,
4728 doc: /* Return t if DISPLAY supports shades of gray.
4729 Note that color displays do support shades of gray.
4730 The optional argument DISPLAY specifies which display to ask about.
4731 DISPLAY should be either a frame or a display name (a string).
4732 If omitted or nil, that stands for the selected frame's display. */)
4733 (Lisp_Object display)
4735 struct w32_display_info *dpyinfo = check_x_display_info (display);
4737 if ((dpyinfo->n_planes * dpyinfo->n_cbits) <= 1)
4738 return Qnil;
4740 return Qt;
4743 DEFUN ("x-display-pixel-width", Fx_display_pixel_width,
4744 Sx_display_pixel_width, 0, 1, 0,
4745 doc: /* Return the width in pixels of DISPLAY.
4746 The optional argument DISPLAY specifies which display to ask about.
4747 DISPLAY should be either a frame or a display name (a string).
4748 If omitted or nil, that stands for the selected frame's display.
4750 On \"multi-monitor\" setups this refers to the pixel width for all
4751 physical monitors associated with DISPLAY. To get information for
4752 each physical monitor, use `display-monitor-attributes-list'. */)
4753 (Lisp_Object display)
4755 struct w32_display_info *dpyinfo = check_x_display_info (display);
4757 return make_number (x_display_pixel_width (dpyinfo));
4760 DEFUN ("x-display-pixel-height", Fx_display_pixel_height,
4761 Sx_display_pixel_height, 0, 1, 0,
4762 doc: /* Return the height in pixels of DISPLAY.
4763 The optional argument DISPLAY specifies which display to ask about.
4764 DISPLAY should be either a frame or a display name (a string).
4765 If omitted or nil, that stands for the selected frame's display.
4767 On \"multi-monitor\" setups this refers to the pixel height for all
4768 physical monitors associated with DISPLAY. To get information for
4769 each physical monitor, use `display-monitor-attributes-list'. */)
4770 (Lisp_Object display)
4772 struct w32_display_info *dpyinfo = check_x_display_info (display);
4774 return make_number (x_display_pixel_height (dpyinfo));
4777 DEFUN ("x-display-planes", Fx_display_planes, Sx_display_planes,
4778 0, 1, 0,
4779 doc: /* Return the number of bitplanes of DISPLAY.
4780 The optional argument DISPLAY specifies which display to ask about.
4781 DISPLAY should be either a frame or a display name (a string).
4782 If omitted or nil, that stands for the selected frame's display. */)
4783 (Lisp_Object display)
4785 struct w32_display_info *dpyinfo = check_x_display_info (display);
4787 return make_number (dpyinfo->n_planes * dpyinfo->n_cbits);
4790 DEFUN ("x-display-color-cells", Fx_display_color_cells, Sx_display_color_cells,
4791 0, 1, 0,
4792 doc: /* Return the number of color cells of DISPLAY.
4793 The optional argument DISPLAY specifies which display to ask about.
4794 DISPLAY should be either a frame or a display name (a string).
4795 If omitted or nil, that stands for the selected frame's display. */)
4796 (Lisp_Object display)
4798 struct w32_display_info *dpyinfo = check_x_display_info (display);
4799 int cap;
4801 /* Don't use NCOLORS: it returns incorrect results under remote
4802 * desktop. We force 24+ bit depths to 24-bit, both to prevent an
4803 * overflow and because probably is more meaningful on Windows
4804 * anyway. */
4806 cap = 1 << min (dpyinfo->n_planes * dpyinfo->n_cbits, 24);
4807 return make_number (cap);
4810 DEFUN ("x-server-max-request-size", Fx_server_max_request_size,
4811 Sx_server_max_request_size,
4812 0, 1, 0,
4813 doc: /* Return the maximum request size of the server of DISPLAY.
4814 The optional argument DISPLAY specifies which display to ask about.
4815 DISPLAY should be either a frame or a display name (a string).
4816 If omitted or nil, that stands for the selected frame's display. */)
4817 (Lisp_Object display)
4819 return make_number (1);
4822 DEFUN ("x-server-vendor", Fx_server_vendor, Sx_server_vendor, 0, 1, 0,
4823 doc: /* Return the "vendor ID" string of the W32 system (Microsoft).
4824 The optional argument DISPLAY specifies which display to ask about.
4825 DISPLAY should be either a frame or a display name (a string).
4826 If omitted or nil, that stands for the selected frame's display. */)
4827 (Lisp_Object display)
4829 return build_string ("Microsoft Corp.");
4832 DEFUN ("x-server-version", Fx_server_version, Sx_server_version, 0, 1, 0,
4833 doc: /* Return the version numbers of the server of DISPLAY.
4834 The value is a list of three integers: the major and minor
4835 version numbers of the X Protocol in use, and the distributor-specific
4836 release number. See also the function `x-server-vendor'.
4838 The optional argument DISPLAY specifies which display to ask about.
4839 DISPLAY should be either a frame or a display name (a string).
4840 If omitted or nil, that stands for the selected frame's display. */)
4841 (Lisp_Object display)
4843 return list3i (w32_major_version, w32_minor_version, w32_build_number);
4846 DEFUN ("x-display-screens", Fx_display_screens, Sx_display_screens, 0, 1, 0,
4847 doc: /* Return the number of screens on the server of DISPLAY.
4848 The optional argument DISPLAY specifies which display to ask about.
4849 DISPLAY should be either a frame or a display name (a string).
4850 If omitted or nil, that stands for the selected frame's display. */)
4851 (Lisp_Object display)
4853 return make_number (1);
4856 DEFUN ("x-display-mm-height", Fx_display_mm_height,
4857 Sx_display_mm_height, 0, 1, 0,
4858 doc: /* Return the height in millimeters of DISPLAY.
4859 The optional argument DISPLAY specifies which display to ask about.
4860 DISPLAY should be either a frame or a display name (a string).
4861 If omitted or nil, that stands for the selected frame's display.
4863 On \"multi-monitor\" setups this refers to the height in millimeters for
4864 all physical monitors associated with DISPLAY. To get information
4865 for each physical monitor, use `display-monitor-attributes-list'. */)
4866 (Lisp_Object display)
4868 struct w32_display_info *dpyinfo = check_x_display_info (display);
4869 HDC hdc;
4870 double mm_per_pixel;
4872 hdc = GetDC (NULL);
4873 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
4874 / GetDeviceCaps (hdc, VERTRES));
4875 ReleaseDC (NULL, hdc);
4877 return make_number (x_display_pixel_height (dpyinfo) * mm_per_pixel + 0.5);
4880 DEFUN ("x-display-mm-width", Fx_display_mm_width, Sx_display_mm_width, 0, 1, 0,
4881 doc: /* Return the width in millimeters of DISPLAY.
4882 The optional argument DISPLAY specifies which display to ask about.
4883 DISPLAY should be either a frame or a display name (a string).
4884 If omitted or nil, that stands for the selected frame's display.
4886 On \"multi-monitor\" setups this refers to the width in millimeters for
4887 all physical monitors associated with TERMINAL. To get information
4888 for each physical monitor, use `display-monitor-attributes-list'. */)
4889 (Lisp_Object display)
4891 struct w32_display_info *dpyinfo = check_x_display_info (display);
4892 HDC hdc;
4893 double mm_per_pixel;
4895 hdc = GetDC (NULL);
4896 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
4897 / GetDeviceCaps (hdc, HORZRES));
4898 ReleaseDC (NULL, hdc);
4900 return make_number (x_display_pixel_width (dpyinfo) * mm_per_pixel + 0.5);
4903 DEFUN ("x-display-backing-store", Fx_display_backing_store,
4904 Sx_display_backing_store, 0, 1, 0,
4905 doc: /* Return an indication of whether DISPLAY does backing store.
4906 The value may be `always', `when-mapped', or `not-useful'.
4907 The optional argument DISPLAY specifies which display to ask about.
4908 DISPLAY should be either a frame or a display name (a string).
4909 If omitted or nil, that stands for the selected frame's display. */)
4910 (Lisp_Object display)
4912 return intern ("not-useful");
4915 DEFUN ("x-display-visual-class", Fx_display_visual_class,
4916 Sx_display_visual_class, 0, 1, 0,
4917 doc: /* Return the visual class of DISPLAY.
4918 The value is one of the symbols `static-gray', `gray-scale',
4919 `static-color', `pseudo-color', `true-color', or `direct-color'.
4921 The optional argument DISPLAY specifies which display to ask about.
4922 DISPLAY should be either a frame or a display name (a string).
4923 If omitted or nil, that stands for the selected frame's display. */)
4924 (Lisp_Object display)
4926 struct w32_display_info *dpyinfo = check_x_display_info (display);
4927 Lisp_Object result = Qnil;
4929 if (dpyinfo->has_palette)
4930 result = intern ("pseudo-color");
4931 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 1)
4932 result = intern ("static-grey");
4933 else if (dpyinfo->n_planes * dpyinfo->n_cbits == 4)
4934 result = intern ("static-color");
4935 else if (dpyinfo->n_planes * dpyinfo->n_cbits > 8)
4936 result = intern ("true-color");
4938 return result;
4941 DEFUN ("x-display-save-under", Fx_display_save_under,
4942 Sx_display_save_under, 0, 1, 0,
4943 doc: /* Return t if DISPLAY supports the save-under feature.
4944 The optional argument DISPLAY specifies which display to ask about.
4945 DISPLAY should be either a frame or a display name (a string).
4946 If omitted or nil, that stands for the selected frame's display. */)
4947 (Lisp_Object display)
4949 return Qnil;
4952 static BOOL CALLBACK
4953 w32_monitor_enum (HMONITOR monitor, HDC hdc, RECT *rcMonitor, LPARAM dwData)
4955 Lisp_Object *monitor_list = (Lisp_Object *) dwData;
4957 *monitor_list = Fcons (make_save_ptr (monitor), *monitor_list);
4959 return TRUE;
4962 static Lisp_Object
4963 w32_display_monitor_attributes_list (void)
4965 Lisp_Object attributes_list = Qnil, primary_monitor_attributes = Qnil;
4966 Lisp_Object monitor_list = Qnil, monitor_frames, rest, frame;
4967 int i, n_monitors;
4968 HMONITOR *monitors;
4969 struct gcpro gcpro1, gcpro2, gcpro3;
4971 if (!(enum_display_monitors_fn && get_monitor_info_fn
4972 && monitor_from_window_fn))
4973 return Qnil;
4975 if (!enum_display_monitors_fn (NULL, NULL, w32_monitor_enum,
4976 (LPARAM) &monitor_list)
4977 || NILP (monitor_list))
4978 return Qnil;
4980 n_monitors = 0;
4981 for (rest = monitor_list; CONSP (rest); rest = XCDR (rest))
4982 n_monitors++;
4984 monitors = xmalloc (n_monitors * sizeof (*monitors));
4985 for (i = 0; i < n_monitors; i++)
4987 monitors[i] = XSAVE_POINTER (XCAR (monitor_list), 0);
4988 monitor_list = XCDR (monitor_list);
4991 monitor_frames = Fmake_vector (make_number (n_monitors), Qnil);
4992 FOR_EACH_FRAME (rest, frame)
4994 struct frame *f = XFRAME (frame);
4996 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
4998 HMONITOR monitor =
4999 monitor_from_window_fn (FRAME_W32_WINDOW (f),
5000 MONITOR_DEFAULT_TO_NEAREST);
5002 for (i = 0; i < n_monitors; i++)
5003 if (monitors[i] == monitor)
5004 break;
5006 if (i < n_monitors)
5007 ASET (monitor_frames, i, Fcons (frame, AREF (monitor_frames, i)));
5011 GCPRO3 (attributes_list, primary_monitor_attributes, monitor_frames);
5013 for (i = 0; i < n_monitors; i++)
5015 Lisp_Object geometry, workarea, name, attributes = Qnil;
5016 HDC hdc;
5017 int width_mm, height_mm;
5018 struct MONITOR_INFO_EX mi;
5020 mi.cbSize = sizeof (mi);
5021 if (!get_monitor_info_fn (monitors[i], (struct MONITOR_INFO *) &mi))
5022 continue;
5024 hdc = CreateDCA ("DISPLAY", mi.szDevice, NULL, NULL);
5025 if (hdc == NULL)
5026 continue;
5027 width_mm = GetDeviceCaps (hdc, HORZSIZE);
5028 height_mm = GetDeviceCaps (hdc, VERTSIZE);
5029 DeleteDC (hdc);
5031 attributes = Fcons (Fcons (Qframes, AREF (monitor_frames, i)),
5032 attributes);
5034 name = DECODE_SYSTEM (build_unibyte_string (mi.szDevice));
5036 attributes = Fcons (Fcons (Qname, name), attributes);
5038 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5039 attributes);
5041 workarea = list4i (mi.rcWork.left, mi.rcWork.top,
5042 mi.rcWork.right - mi.rcWork.left,
5043 mi.rcWork.bottom - mi.rcWork.top);
5044 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5046 geometry = list4i (mi.rcMonitor.left, mi.rcMonitor.top,
5047 mi.rcMonitor.right - mi.rcMonitor.left,
5048 mi.rcMonitor.bottom - mi.rcMonitor.top);
5049 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5051 if (mi.dwFlags & MONITORINFOF_PRIMARY)
5052 primary_monitor_attributes = attributes;
5053 else
5054 attributes_list = Fcons (attributes, attributes_list);
5057 if (!NILP (primary_monitor_attributes))
5058 attributes_list = Fcons (primary_monitor_attributes, attributes_list);
5060 UNGCPRO;
5062 xfree (monitors);
5064 return attributes_list;
5067 static Lisp_Object
5068 w32_display_monitor_attributes_list_fallback (struct w32_display_info *dpyinfo)
5070 Lisp_Object geometry, workarea, frames, rest, frame, attributes = Qnil;
5071 HDC hdc;
5072 double mm_per_pixel;
5073 int pixel_width, pixel_height, width_mm, height_mm;
5074 RECT workarea_rect;
5076 /* Fallback: treat (possibly) multiple physical monitors as if they
5077 formed a single monitor as a whole. This should provide a
5078 consistent result at least on single monitor environments. */
5079 attributes = Fcons (Fcons (Qname, build_string ("combined screen")),
5080 attributes);
5082 frames = Qnil;
5083 FOR_EACH_FRAME (rest, frame)
5085 struct frame *f = XFRAME (frame);
5087 if (FRAME_W32_P (f) && !EQ (frame, tip_frame))
5088 frames = Fcons (frame, frames);
5090 attributes = Fcons (Fcons (Qframes, frames), attributes);
5092 pixel_width = x_display_pixel_width (dpyinfo);
5093 pixel_height = x_display_pixel_height (dpyinfo);
5095 hdc = GetDC (NULL);
5096 mm_per_pixel = ((double) GetDeviceCaps (hdc, HORZSIZE)
5097 / GetDeviceCaps (hdc, HORZRES));
5098 width_mm = pixel_width * mm_per_pixel + 0.5;
5099 mm_per_pixel = ((double) GetDeviceCaps (hdc, VERTSIZE)
5100 / GetDeviceCaps (hdc, VERTRES));
5101 height_mm = pixel_height * mm_per_pixel + 0.5;
5102 ReleaseDC (NULL, hdc);
5103 attributes = Fcons (Fcons (Qmm_size, list2i (width_mm, height_mm)),
5104 attributes);
5106 /* GetSystemMetrics below may return 0 for Windows 95 or NT 4.0, but
5107 we don't care. */
5108 geometry = list4i (GetSystemMetrics (SM_XVIRTUALSCREEN),
5109 GetSystemMetrics (SM_YVIRTUALSCREEN),
5110 pixel_width, pixel_height);
5111 if (SystemParametersInfo (SPI_GETWORKAREA, 0, &workarea_rect, 0))
5112 workarea = list4i (workarea_rect.left, workarea_rect.top,
5113 workarea_rect.right - workarea_rect.left,
5114 workarea_rect.bottom - workarea_rect.top);
5115 else
5116 workarea = geometry;
5117 attributes = Fcons (Fcons (Qworkarea, workarea), attributes);
5119 attributes = Fcons (Fcons (Qgeometry, geometry), attributes);
5121 return list1 (attributes);
5124 DEFUN ("w32-display-monitor-attributes-list", Fw32_display_monitor_attributes_list,
5125 Sw32_display_monitor_attributes_list,
5126 0, 1, 0,
5127 doc: /* Return a list of physical monitor attributes on the W32 display DISPLAY.
5129 The optional argument DISPLAY specifies which display to ask about.
5130 DISPLAY should be either a frame or a display name (a string).
5131 If omitted or nil, that stands for the selected frame's display.
5133 Internal use only, use `display-monitor-attributes-list' instead. */)
5134 (Lisp_Object display)
5136 struct w32_display_info *dpyinfo = check_x_display_info (display);
5137 Lisp_Object attributes_list;
5139 block_input ();
5140 attributes_list = w32_display_monitor_attributes_list ();
5141 if (NILP (attributes_list))
5142 attributes_list = w32_display_monitor_attributes_list_fallback (dpyinfo);
5143 unblock_input ();
5145 return attributes_list;
5148 DEFUN ("set-message-beep", Fset_message_beep, Sset_message_beep, 1, 1, 0,
5149 doc: /* Set the sound generated when the bell is rung.
5150 SOUND is 'asterisk, 'exclamation, 'hand, 'question, 'ok, or 'silent
5151 to use the corresponding system sound for the bell. The 'silent sound
5152 prevents Emacs from making any sound at all.
5153 SOUND is nil to use the normal beep. */)
5154 (Lisp_Object sound)
5156 CHECK_SYMBOL (sound);
5158 if (NILP (sound))
5159 sound_type = 0xFFFFFFFF;
5160 else if (EQ (sound, intern ("asterisk")))
5161 sound_type = MB_ICONASTERISK;
5162 else if (EQ (sound, intern ("exclamation")))
5163 sound_type = MB_ICONEXCLAMATION;
5164 else if (EQ (sound, intern ("hand")))
5165 sound_type = MB_ICONHAND;
5166 else if (EQ (sound, intern ("question")))
5167 sound_type = MB_ICONQUESTION;
5168 else if (EQ (sound, intern ("ok")))
5169 sound_type = MB_OK;
5170 else if (EQ (sound, intern ("silent")))
5171 sound_type = MB_EMACS_SILENT;
5172 else
5173 sound_type = 0xFFFFFFFF;
5175 return sound;
5179 x_screen_planes (register struct frame *f)
5181 return FRAME_DISPLAY_INFO (f)->n_planes;
5184 /* Return the display structure for the display named NAME.
5185 Open a new connection if necessary. */
5187 struct w32_display_info *
5188 x_display_info_for_name (Lisp_Object name)
5190 struct w32_display_info *dpyinfo;
5192 CHECK_STRING (name);
5194 for (dpyinfo = &one_w32_display_info; dpyinfo; dpyinfo = dpyinfo->next)
5195 if (!NILP (Fstring_equal (XCAR (dpyinfo->name_list_element), name)))
5196 return dpyinfo;
5198 /* Use this general default value to start with. */
5199 Vx_resource_name = Vinvocation_name;
5201 validate_x_resource_name ();
5203 dpyinfo = w32_term_init (name, (unsigned char *)0,
5204 SSDATA (Vx_resource_name));
5206 if (dpyinfo == 0)
5207 error ("Cannot connect to server %s", SDATA (name));
5209 XSETFASTINT (Vwindow_system_version, w32_major_version);
5211 return dpyinfo;
5214 DEFUN ("x-open-connection", Fx_open_connection, Sx_open_connection,
5215 1, 3, 0, doc: /* Open a connection to a display server.
5216 DISPLAY is the name of the display to connect to.
5217 Optional second arg XRM-STRING is a string of resources in xrdb format.
5218 If the optional third arg MUST-SUCCEED is non-nil,
5219 terminate Emacs if we can't open the connection.
5220 \(In the Nextstep version, the last two arguments are currently ignored.) */)
5221 (Lisp_Object display, Lisp_Object xrm_string, Lisp_Object must_succeed)
5223 unsigned char *xrm_option;
5224 struct w32_display_info *dpyinfo;
5226 CHECK_STRING (display);
5228 /* Signal an error in order to encourage correct use from callers.
5229 * If we ever support multiple window systems in the same Emacs,
5230 * we'll need callers to be precise about what window system they
5231 * want. */
5233 if (strcmp (SSDATA (display), "w32") != 0)
5234 error ("The name of the display in this Emacs must be \"w32\"");
5236 /* If initialization has already been done, return now to avoid
5237 overwriting critical parts of one_w32_display_info. */
5238 if (window_system_available (NULL))
5239 return Qnil;
5241 if (! NILP (xrm_string))
5242 CHECK_STRING (xrm_string);
5244 /* Allow color mapping to be defined externally; first look in user's
5245 HOME directory, then in Emacs etc dir for a file called rgb.txt. */
5247 Lisp_Object color_file;
5248 struct gcpro gcpro1;
5250 color_file = build_string ("~/rgb.txt");
5252 GCPRO1 (color_file);
5254 if (NILP (Ffile_readable_p (color_file)))
5255 color_file =
5256 Fexpand_file_name (build_string ("rgb.txt"),
5257 Fsymbol_value (intern ("data-directory")));
5259 Vw32_color_map = Fx_load_color_file (color_file);
5261 UNGCPRO;
5263 if (NILP (Vw32_color_map))
5264 Vw32_color_map = w32_default_color_map ();
5266 /* Merge in system logical colors. */
5267 add_system_logical_colors_to_map (&Vw32_color_map);
5269 if (! NILP (xrm_string))
5270 xrm_option = SDATA (xrm_string);
5271 else
5272 xrm_option = (unsigned char *) 0;
5274 /* Use this general default value to start with. */
5275 /* First remove .exe suffix from invocation-name - it looks ugly. */
5277 char basename[ MAX_PATH ], *str;
5279 strcpy (basename, SDATA (Vinvocation_name));
5280 str = strrchr (basename, '.');
5281 if (str) *str = 0;
5282 Vinvocation_name = build_string (basename);
5284 Vx_resource_name = Vinvocation_name;
5286 validate_x_resource_name ();
5288 /* This is what opens the connection and sets x_current_display.
5289 This also initializes many symbols, such as those used for input. */
5290 dpyinfo = w32_term_init (display, xrm_option,
5291 SSDATA (Vx_resource_name));
5293 if (dpyinfo == 0)
5295 if (!NILP (must_succeed))
5296 fatal ("Cannot connect to server %s.\n",
5297 SDATA (display));
5298 else
5299 error ("Cannot connect to server %s", SDATA (display));
5302 XSETFASTINT (Vwindow_system_version, w32_major_version);
5303 return Qnil;
5306 DEFUN ("x-close-connection", Fx_close_connection,
5307 Sx_close_connection, 1, 1, 0,
5308 doc: /* Close the connection to DISPLAY's server.
5309 For DISPLAY, specify either a frame or a display name (a string).
5310 If DISPLAY is nil, that stands for the selected frame's display. */)
5311 (Lisp_Object display)
5313 struct w32_display_info *dpyinfo = check_x_display_info (display);
5315 if (dpyinfo->reference_count > 0)
5316 error ("Display still has frames on it");
5318 block_input ();
5319 x_destroy_all_bitmaps (dpyinfo);
5321 x_delete_display (dpyinfo);
5322 unblock_input ();
5324 return Qnil;
5327 DEFUN ("x-display-list", Fx_display_list, Sx_display_list, 0, 0, 0,
5328 doc: /* Return the list of display names that Emacs has connections to. */)
5329 (void)
5331 Lisp_Object result = Qnil;
5332 struct w32_display_info *wdi;
5334 for (wdi = x_display_list; wdi; wdi = wdi->next)
5335 result = Fcons (XCAR (wdi->name_list_element), result);
5337 return result;
5340 DEFUN ("x-synchronize", Fx_synchronize, Sx_synchronize, 1, 2, 0,
5341 doc: /* If ON is non-nil, report X errors as soon as the erring request is made.
5342 This function only has an effect on X Windows. With MS Windows, it is
5343 defined but does nothing.
5345 If ON is nil, allow buffering of requests.
5346 Turning on synchronization prohibits the Xlib routines from buffering
5347 requests and seriously degrades performance, but makes debugging much
5348 easier.
5349 The optional second argument TERMINAL specifies which display to act on.
5350 TERMINAL should be a terminal object, a frame or a display name (a string).
5351 If TERMINAL is omitted or nil, that stands for the selected frame's display. */)
5352 (Lisp_Object on, Lisp_Object display)
5354 return Qnil;
5359 /***********************************************************************
5360 Window properties
5361 ***********************************************************************/
5363 #if 0 /* TODO : port window properties to W32 */
5365 DEFUN ("x-change-window-property", Fx_change_window_property,
5366 Sx_change_window_property, 2, 6, 0,
5367 doc: /* Change window property PROP to VALUE on the X window of FRAME.
5368 PROP must be a string. VALUE may be a string or a list of conses,
5369 numbers and/or strings. If an element in the list is a string, it is
5370 converted to an atom and the value of the Atom is used. If an element
5371 is a cons, it is converted to a 32 bit number where the car is the 16
5372 top bits and the cdr is the lower 16 bits.
5374 FRAME nil or omitted means use the selected frame.
5375 If TYPE is given and non-nil, it is the name of the type of VALUE.
5376 If TYPE is not given or nil, the type is STRING.
5377 FORMAT gives the size in bits of each element if VALUE is a list.
5378 It must be one of 8, 16 or 32.
5379 If VALUE is a string or FORMAT is nil or not given, FORMAT defaults to 8.
5380 If OUTER-P is non-nil, the property is changed for the outer X window of
5381 FRAME. Default is to change on the edit X window. */)
5382 (Lisp_Object prop, Lisp_Object value, Lisp_Object frame,
5383 Lisp_Object type, Lisp_Object format, Lisp_Object outer_p)
5385 struct frame *f = decode_window_system_frame (frame);
5386 Atom prop_atom;
5388 CHECK_STRING (prop);
5389 CHECK_STRING (value);
5391 block_input ();
5392 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5393 XChangeProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5394 prop_atom, XA_STRING, 8, PropModeReplace,
5395 SDATA (value), SCHARS (value));
5397 /* Make sure the property is set when we return. */
5398 XFlush (FRAME_W32_DISPLAY (f));
5399 unblock_input ();
5401 return value;
5405 DEFUN ("x-delete-window-property", Fx_delete_window_property,
5406 Sx_delete_window_property, 1, 2, 0,
5407 doc: /* Remove window property PROP from X window of FRAME.
5408 FRAME nil or omitted means use the selected frame. Value is PROP. */)
5409 (Lisp_Object prop, Lisp_Object frame)
5411 struct frame *f = decode_window_system_frame (frame);
5412 Atom prop_atom;
5414 CHECK_STRING (prop);
5415 block_input ();
5416 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5417 XDeleteProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f), prop_atom);
5419 /* Make sure the property is removed when we return. */
5420 XFlush (FRAME_W32_DISPLAY (f));
5421 unblock_input ();
5423 return prop;
5427 DEFUN ("x-window-property", Fx_window_property, Sx_window_property,
5428 1, 6, 0,
5429 doc: /* Value is the value of window property PROP on FRAME.
5430 If FRAME is nil or omitted, use the selected frame.
5432 On X Windows, the following optional arguments are also accepted:
5433 If TYPE is nil or omitted, get the property as a string.
5434 Otherwise TYPE is the name of the atom that denotes the type expected.
5435 If SOURCE is non-nil, get the property on that window instead of from
5436 FRAME. The number 0 denotes the root window.
5437 If DELETE-P is non-nil, delete the property after retrieving it.
5438 If VECTOR-RET-P is non-nil, don't return a string but a vector of values.
5440 On MS Windows, this function accepts but ignores those optional arguments.
5442 Value is nil if FRAME hasn't a property with name PROP or if PROP has
5443 no value of TYPE (always string in the MS Windows case). */)
5444 (Lisp_Object prop, Lisp_Object frame, Lisp_Object type,
5445 Lisp_Object source, Lisp_Object delete_p, Lisp_Object vector_ret_p)
5447 struct frame *f = decode_window_system_frame (frame);
5448 Atom prop_atom;
5449 int rc;
5450 Lisp_Object prop_value = Qnil;
5451 char *tmp_data = NULL;
5452 Atom actual_type;
5453 int actual_format;
5454 unsigned long actual_size, bytes_remaining;
5456 CHECK_STRING (prop);
5457 block_input ();
5458 prop_atom = XInternAtom (FRAME_W32_DISPLAY (f), SDATA (prop), False);
5459 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5460 prop_atom, 0, 0, False, XA_STRING,
5461 &actual_type, &actual_format, &actual_size,
5462 &bytes_remaining, (unsigned char **) &tmp_data);
5463 if (rc == Success)
5465 int size = bytes_remaining;
5467 XFree (tmp_data);
5468 tmp_data = NULL;
5470 rc = XGetWindowProperty (FRAME_W32_DISPLAY (f), FRAME_W32_WINDOW (f),
5471 prop_atom, 0, bytes_remaining,
5472 False, XA_STRING,
5473 &actual_type, &actual_format,
5474 &actual_size, &bytes_remaining,
5475 (unsigned char **) &tmp_data);
5476 if (rc == Success)
5477 prop_value = make_string (tmp_data, size);
5479 XFree (tmp_data);
5482 unblock_input ();
5484 return prop_value;
5486 return Qnil;
5489 #endif /* TODO */
5492 /***********************************************************************
5493 Busy cursor
5494 ***********************************************************************/
5496 /* Display an hourglass cursor. Set the hourglass_p flag in display info
5497 to indicate that an hourglass cursor is shown. */
5499 void
5500 show_hourglass (struct atimer *timer)
5502 hourglass_atimer = NULL;
5504 if (!hourglass_shown_p)
5506 Lisp_Object tail, frame;
5508 block_input ();
5509 FOR_EACH_FRAME (tail, frame)
5511 struct frame *f = XFRAME (frame);
5513 if (FRAME_W32_P (f) && !menubar_in_use && !current_popup_menu)
5515 f->output_data.w32->hourglass_p = 1;
5516 SetCursor (f->output_data.w32->hourglass_cursor);
5519 unblock_input ();
5520 hourglass_shown_p = 1;
5524 /* Hide the hourglass cursor on all frames, if it is currently shown. */
5526 void
5527 hide_hourglass (void)
5529 if (hourglass_shown_p)
5531 Lisp_Object tail, frame;
5533 block_input ();
5534 FOR_EACH_FRAME (tail, frame)
5536 struct frame *f = XFRAME (frame);
5538 if (FRAME_W32_P (f))
5540 f->output_data.w32->hourglass_p = 0;
5541 SetCursor (f->output_data.w32->current_cursor);
5543 else
5544 /* No cursors on non GUI frames - restore to stock arrow cursor. */
5545 SetCursor (w32_load_cursor (IDC_ARROW));
5547 unblock_input ();
5548 hourglass_shown_p = 0;
5552 /***********************************************************************
5553 Tool tips
5554 ***********************************************************************/
5556 static Lisp_Object x_create_tip_frame (struct w32_display_info *,
5557 Lisp_Object, Lisp_Object);
5558 static void compute_tip_xy (struct frame *, Lisp_Object, Lisp_Object,
5559 Lisp_Object, int, int, int *, int *);
5561 /* The frame of a currently visible tooltip. */
5563 Lisp_Object tip_frame;
5565 /* If non-nil, a timer started that hides the last tooltip when it
5566 fires. */
5568 Lisp_Object tip_timer;
5569 Window tip_window;
5571 /* If non-nil, a vector of 3 elements containing the last args
5572 with which x-show-tip was called. See there. */
5574 Lisp_Object last_show_tip_args;
5577 static void
5578 unwind_create_tip_frame (Lisp_Object frame)
5580 Lisp_Object deleted;
5582 deleted = unwind_create_frame (frame);
5583 if (EQ (deleted, Qt))
5585 tip_window = NULL;
5586 tip_frame = Qnil;
5591 /* Create a frame for a tooltip on the display described by DPYINFO.
5592 PARMS is a list of frame parameters. TEXT is the string to
5593 display in the tip frame. Value is the frame.
5595 Note that functions called here, esp. x_default_parameter can
5596 signal errors, for instance when a specified color name is
5597 undefined. We have to make sure that we're in a consistent state
5598 when this happens. */
5600 static Lisp_Object
5601 x_create_tip_frame (struct w32_display_info *dpyinfo,
5602 Lisp_Object parms, Lisp_Object text)
5604 struct frame *f;
5605 Lisp_Object frame;
5606 Lisp_Object name;
5607 long window_prompting = 0;
5608 int width, height;
5609 ptrdiff_t count = SPECPDL_INDEX ();
5610 struct gcpro gcpro1, gcpro2, gcpro3;
5611 struct kboard *kb;
5612 int face_change_count_before = face_change_count;
5613 Lisp_Object buffer;
5614 struct buffer *old_buffer;
5616 /* Use this general default value to start with until we know if
5617 this frame has a specified name. */
5618 Vx_resource_name = Vinvocation_name;
5620 kb = dpyinfo->terminal->kboard;
5622 /* The calls to x_get_arg remove elements from PARMS, so copy it to
5623 avoid destructive changes behind our caller's back. */
5624 parms = Fcopy_alist (parms);
5626 /* Get the name of the frame to use for resource lookup. */
5627 name = x_get_arg (dpyinfo, parms, Qname, "name", "Name", RES_TYPE_STRING);
5628 if (!STRINGP (name)
5629 && !EQ (name, Qunbound)
5630 && !NILP (name))
5631 error ("Invalid frame name--not a string or nil");
5632 Vx_resource_name = name;
5634 frame = Qnil;
5635 GCPRO3 (parms, name, frame);
5636 /* Make a frame without minibuffer nor mode-line. */
5637 f = make_frame (0);
5638 f->wants_modeline = 0;
5639 XSETFRAME (frame, f);
5641 buffer = Fget_buffer_create (build_string (" *tip*"));
5642 /* Use set_window_buffer instead of Fset_window_buffer (see
5643 discussion of bug#11984, bug#12025, bug#12026). */
5644 set_window_buffer (FRAME_ROOT_WINDOW (f), buffer, 0, 0);
5645 old_buffer = current_buffer;
5646 set_buffer_internal_1 (XBUFFER (buffer));
5647 bset_truncate_lines (current_buffer, Qnil);
5648 specbind (Qinhibit_read_only, Qt);
5649 specbind (Qinhibit_modification_hooks, Qt);
5650 Ferase_buffer ();
5651 Finsert (1, &text);
5652 set_buffer_internal_1 (old_buffer);
5654 record_unwind_protect (unwind_create_tip_frame, frame);
5656 /* By setting the output method, we're essentially saying that
5657 the frame is live, as per FRAME_LIVE_P. If we get a signal
5658 from this point on, x_destroy_window might screw up reference
5659 counts etc. */
5660 f->terminal = dpyinfo->terminal;
5661 f->output_method = output_w32;
5662 f->output_data.w32 = xzalloc (sizeof (struct w32_output));
5664 FRAME_FONTSET (f) = -1;
5665 fset_icon_name (f, Qnil);
5667 #ifdef GLYPH_DEBUG
5668 image_cache_refcount =
5669 FRAME_IMAGE_CACHE (f) ? FRAME_IMAGE_CACHE (f)->refcount : 0;
5670 dpyinfo_refcount = dpyinfo->reference_count;
5671 #endif /* GLYPH_DEBUG */
5672 FRAME_KBOARD (f) = kb;
5673 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5674 f->output_data.w32->explicit_parent = 0;
5676 /* Set the name; the functions to which we pass f expect the name to
5677 be set. */
5678 if (EQ (name, Qunbound) || NILP (name))
5680 fset_name (f, build_string (dpyinfo->w32_id_name));
5681 f->explicit_name = 0;
5683 else
5685 fset_name (f, name);
5686 f->explicit_name = 1;
5687 /* use the frame's title when getting resources for this frame. */
5688 specbind (Qx_resource_name, name);
5691 if (uniscribe_available)
5692 register_font_driver (&uniscribe_font_driver, f);
5693 register_font_driver (&w32font_driver, f);
5695 x_default_parameter (f, parms, Qfont_backend, Qnil,
5696 "fontBackend", "FontBackend", RES_TYPE_STRING);
5698 /* Extract the window parameters from the supplied values
5699 that are needed to determine window geometry. */
5700 x_default_font_parameter (f, parms);
5702 x_default_parameter (f, parms, Qborder_width, make_number (2),
5703 "borderWidth", "BorderWidth", RES_TYPE_NUMBER);
5704 /* This defaults to 2 in order to match xterm. We recognize either
5705 internalBorderWidth or internalBorder (which is what xterm calls
5706 it). */
5707 if (NILP (Fassq (Qinternal_border_width, parms)))
5709 Lisp_Object value;
5711 value = x_get_arg (dpyinfo, parms, Qinternal_border_width,
5712 "internalBorder", "internalBorder", RES_TYPE_NUMBER);
5713 if (! EQ (value, Qunbound))
5714 parms = Fcons (Fcons (Qinternal_border_width, value),
5715 parms);
5717 x_default_parameter (f, parms, Qinternal_border_width, make_number (1),
5718 "internalBorderWidth", "internalBorderWidth",
5719 RES_TYPE_NUMBER);
5720 x_default_parameter (f, parms, Qright_divider_width, make_number (0),
5721 NULL, NULL, RES_TYPE_NUMBER);
5722 x_default_parameter (f, parms, Qbottom_divider_width, make_number (0),
5723 NULL, NULL, RES_TYPE_NUMBER);
5725 /* Also do the stuff which must be set before the window exists. */
5726 x_default_parameter (f, parms, Qforeground_color, build_string ("black"),
5727 "foreground", "Foreground", RES_TYPE_STRING);
5728 x_default_parameter (f, parms, Qbackground_color, build_string ("white"),
5729 "background", "Background", RES_TYPE_STRING);
5730 x_default_parameter (f, parms, Qmouse_color, build_string ("black"),
5731 "pointerColor", "Foreground", RES_TYPE_STRING);
5732 x_default_parameter (f, parms, Qcursor_color, build_string ("black"),
5733 "cursorColor", "Foreground", RES_TYPE_STRING);
5734 x_default_parameter (f, parms, Qborder_color, build_string ("black"),
5735 "borderColor", "BorderColor", RES_TYPE_STRING);
5737 /* Init faces before x_default_parameter is called for scroll-bar
5738 parameters because that function calls x_set_scroll_bar_width,
5739 which calls change_frame_size, which calls Fset_window_buffer,
5740 which runs hooks, which call Fvertical_motion. At the end, we
5741 end up in init_iterator with a null face cache, which should not
5742 happen. */
5743 init_frame_faces (f);
5745 f->output_data.w32->dwStyle = WS_BORDER | WS_POPUP | WS_DISABLED;
5746 f->output_data.w32->parent_desc = FRAME_DISPLAY_INFO (f)->root_window;
5748 window_prompting = x_figure_window_size (f, parms, 0);
5750 /* No fringes on tip frame. */
5751 f->fringe_cols = 0;
5752 f->left_fringe_width = 0;
5753 f->right_fringe_width = 0;
5755 block_input ();
5756 my_create_tip_window (f);
5757 unblock_input ();
5759 x_make_gc (f);
5761 x_default_parameter (f, parms, Qauto_raise, Qnil,
5762 "autoRaise", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5763 x_default_parameter (f, parms, Qauto_lower, Qnil,
5764 "autoLower", "AutoRaiseLower", RES_TYPE_BOOLEAN);
5765 x_default_parameter (f, parms, Qcursor_type, Qbox,
5766 "cursorType", "CursorType", RES_TYPE_SYMBOL);
5768 /* Dimensions, especially FRAME_LINES (f), must be done via
5769 change_frame_size. Change will not be effected unless different
5770 from the current FRAME_LINES (f). */
5771 width = FRAME_COLS (f);
5772 height = FRAME_LINES (f);
5773 FRAME_LINES (f) = 0;
5774 SET_FRAME_COLS (f, 0);
5775 change_frame_size (f, width, height, 1, 0, 0, 0);
5777 /* Add `tooltip' frame parameter's default value. */
5778 if (NILP (Fframe_parameter (frame, Qtooltip)))
5779 Fmodify_frame_parameters (frame, Fcons (Fcons (Qtooltip, Qt), Qnil));
5781 /* Set up faces after all frame parameters are known. This call
5782 also merges in face attributes specified for new frames.
5784 Frame parameters may be changed if .Xdefaults contains
5785 specifications for the default font. For example, if there is an
5786 `Emacs.default.attributeBackground: pink', the `background-color'
5787 attribute of the frame get's set, which let's the internal border
5788 of the tooltip frame appear in pink. Prevent this. */
5790 Lisp_Object bg = Fframe_parameter (frame, Qbackground_color);
5791 Lisp_Object fg = Fframe_parameter (frame, Qforeground_color);
5792 Lisp_Object colors = Qnil;
5794 /* Set tip_frame here, so that */
5795 tip_frame = frame;
5796 call2 (Qface_set_after_frame_default, frame, Qnil);
5798 if (!EQ (bg, Fframe_parameter (frame, Qbackground_color)))
5799 colors = Fcons (Fcons (Qbackground_color, bg), colors);
5800 if (!EQ (fg, Fframe_parameter (frame, Qforeground_color)))
5801 colors = Fcons (Fcons (Qforeground_color, fg), colors);
5803 if (!NILP (colors))
5804 Fmodify_frame_parameters (frame, colors);
5807 f->no_split = 1;
5809 UNGCPRO;
5811 /* Now that the frame is official, it counts as a reference to
5812 its display. */
5813 FRAME_DISPLAY_INFO (f)->reference_count++;
5814 f->terminal->reference_count++;
5816 /* It is now ok to make the frame official even if we get an error
5817 below. And the frame needs to be on Vframe_list or making it
5818 visible won't work. */
5819 Vframe_list = Fcons (frame, Vframe_list);
5821 /* Setting attributes of faces of the tooltip frame from resources
5822 and similar will increment face_change_count, which leads to the
5823 clearing of all current matrices. Since this isn't necessary
5824 here, avoid it by resetting face_change_count to the value it
5825 had before we created the tip frame. */
5826 face_change_count = face_change_count_before;
5828 /* Discard the unwind_protect. */
5829 return unbind_to (count, frame);
5833 /* Compute where to display tip frame F. PARMS is the list of frame
5834 parameters for F. DX and DY are specified offsets from the current
5835 location of the mouse. WIDTH and HEIGHT are the width and height
5836 of the tooltip. Return coordinates relative to the root window of
5837 the display in *ROOT_X, and *ROOT_Y. */
5839 static void
5840 compute_tip_xy (struct frame *f,
5841 Lisp_Object parms, Lisp_Object dx, Lisp_Object dy,
5842 int width, int height, int *root_x, int *root_y)
5844 Lisp_Object left, top;
5845 int min_x, min_y, max_x, max_y;
5847 /* User-specified position? */
5848 left = Fcdr (Fassq (Qleft, parms));
5849 top = Fcdr (Fassq (Qtop, parms));
5851 /* Move the tooltip window where the mouse pointer is. Resize and
5852 show it. */
5853 if (!INTEGERP (left) || !INTEGERP (top))
5855 POINT pt;
5857 /* Default min and max values. */
5858 min_x = 0;
5859 min_y = 0;
5860 max_x = x_display_pixel_width (FRAME_DISPLAY_INFO (f));
5861 max_y = x_display_pixel_height (FRAME_DISPLAY_INFO (f));
5863 block_input ();
5864 GetCursorPos (&pt);
5865 *root_x = pt.x;
5866 *root_y = pt.y;
5867 unblock_input ();
5869 /* If multiple monitor support is available, constrain the tip onto
5870 the current monitor. This improves the above by allowing negative
5871 co-ordinates if monitor positions are such that they are valid, and
5872 snaps a tooltip onto a single monitor if we are close to the edge
5873 where it would otherwise flow onto the other monitor (or into
5874 nothingness if there is a gap in the overlap). */
5875 if (monitor_from_point_fn && get_monitor_info_fn)
5877 struct MONITOR_INFO info;
5878 HMONITOR monitor
5879 = monitor_from_point_fn (pt, MONITOR_DEFAULT_TO_NEAREST);
5880 info.cbSize = sizeof (info);
5882 if (get_monitor_info_fn (monitor, &info))
5884 min_x = info.rcWork.left;
5885 min_y = info.rcWork.top;
5886 max_x = info.rcWork.right;
5887 max_y = info.rcWork.bottom;
5892 if (INTEGERP (top))
5893 *root_y = XINT (top);
5894 else if (*root_y + XINT (dy) <= min_y)
5895 *root_y = min_y; /* Can happen for negative dy */
5896 else if (*root_y + XINT (dy) + height <= max_y)
5897 /* It fits below the pointer */
5898 *root_y += XINT (dy);
5899 else if (height + XINT (dy) + min_y <= *root_y)
5900 /* It fits above the pointer. */
5901 *root_y -= height + XINT (dy);
5902 else
5903 /* Put it on the top. */
5904 *root_y = min_y;
5906 if (INTEGERP (left))
5907 *root_x = XINT (left);
5908 else if (*root_x + XINT (dx) <= min_x)
5909 *root_x = 0; /* Can happen for negative dx */
5910 else if (*root_x + XINT (dx) + width <= max_x)
5911 /* It fits to the right of the pointer. */
5912 *root_x += XINT (dx);
5913 else if (width + XINT (dx) + min_x <= *root_x)
5914 /* It fits to the left of the pointer. */
5915 *root_x -= width + XINT (dx);
5916 else
5917 /* Put it left justified on the screen -- it ought to fit that way. */
5918 *root_x = min_x;
5922 DEFUN ("x-show-tip", Fx_show_tip, Sx_show_tip, 1, 6, 0,
5923 doc: /* Show STRING in a \"tooltip\" window on frame FRAME.
5924 A tooltip window is a small window displaying a string.
5926 This is an internal function; Lisp code should call `tooltip-show'.
5928 FRAME nil or omitted means use the selected frame.
5930 PARMS is an optional list of frame parameters which can be
5931 used to change the tooltip's appearance.
5933 Automatically hide the tooltip after TIMEOUT seconds. TIMEOUT nil
5934 means use the default timeout of 5 seconds.
5936 If the list of frame parameters PARMS contains a `left' parameter,
5937 the tooltip is displayed at that x-position. Otherwise it is
5938 displayed at the mouse position, with offset DX added (default is 5 if
5939 DX isn't specified). Likewise for the y-position; if a `top' frame
5940 parameter is specified, it determines the y-position of the tooltip
5941 window, otherwise it is displayed at the mouse position, with offset
5942 DY added (default is -10).
5944 A tooltip's maximum size is specified by `x-max-tooltip-size'.
5945 Text larger than the specified size is clipped. */)
5946 (Lisp_Object string, Lisp_Object frame, Lisp_Object parms, Lisp_Object timeout, Lisp_Object dx, Lisp_Object dy)
5948 struct frame *f;
5949 struct window *w;
5950 int root_x, root_y;
5951 struct buffer *old_buffer;
5952 struct text_pos pos;
5953 int i, width, height, seen_reversed_p;
5954 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;
5955 int old_windows_or_buffers_changed = windows_or_buffers_changed;
5956 ptrdiff_t count = SPECPDL_INDEX ();
5958 specbind (Qinhibit_redisplay, Qt);
5960 GCPRO4 (string, parms, frame, timeout);
5962 CHECK_STRING (string);
5963 f = decode_window_system_frame (frame);
5964 if (NILP (timeout))
5965 timeout = make_number (5);
5966 else
5967 CHECK_NATNUM (timeout);
5969 if (NILP (dx))
5970 dx = make_number (5);
5971 else
5972 CHECK_NUMBER (dx);
5974 if (NILP (dy))
5975 dy = make_number (-10);
5976 else
5977 CHECK_NUMBER (dy);
5979 if (NILP (last_show_tip_args))
5980 last_show_tip_args = Fmake_vector (make_number (3), Qnil);
5982 if (!NILP (tip_frame))
5984 Lisp_Object last_string = AREF (last_show_tip_args, 0);
5985 Lisp_Object last_frame = AREF (last_show_tip_args, 1);
5986 Lisp_Object last_parms = AREF (last_show_tip_args, 2);
5988 if (EQ (frame, last_frame)
5989 && !NILP (Fequal (last_string, string))
5990 && !NILP (Fequal (last_parms, parms)))
5992 struct frame *f = XFRAME (tip_frame);
5994 /* Only DX and DY have changed. */
5995 if (!NILP (tip_timer))
5997 Lisp_Object timer = tip_timer;
5998 tip_timer = Qnil;
5999 call1 (Qcancel_timer, timer);
6002 block_input ();
6003 compute_tip_xy (f, parms, dx, dy, FRAME_PIXEL_WIDTH (f),
6004 FRAME_PIXEL_HEIGHT (f), &root_x, &root_y);
6006 /* Put tooltip in topmost group and in position. */
6007 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6008 root_x, root_y, 0, 0,
6009 SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6011 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6012 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6013 0, 0, 0, 0,
6014 SWP_NOMOVE | SWP_NOSIZE
6015 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6017 unblock_input ();
6018 goto start_timer;
6022 /* Hide a previous tip, if any. */
6023 Fx_hide_tip ();
6025 ASET (last_show_tip_args, 0, string);
6026 ASET (last_show_tip_args, 1, frame);
6027 ASET (last_show_tip_args, 2, parms);
6029 /* Add default values to frame parameters. */
6030 if (NILP (Fassq (Qname, parms)))
6031 parms = Fcons (Fcons (Qname, build_string ("tooltip")), parms);
6032 if (NILP (Fassq (Qinternal_border_width, parms)))
6033 parms = Fcons (Fcons (Qinternal_border_width, make_number (3)), parms);
6034 if (NILP (Fassq (Qright_divider_width, parms)))
6035 parms = Fcons (Fcons (Qright_divider_width, make_number (0)), parms);
6036 if (NILP (Fassq (Qbottom_divider_width, parms)))
6037 parms = Fcons (Fcons (Qbottom_divider_width, make_number (0)), parms);
6038 if (NILP (Fassq (Qborder_width, parms)))
6039 parms = Fcons (Fcons (Qborder_width, make_number (1)), parms);
6040 if (NILP (Fassq (Qborder_color, parms)))
6041 parms = Fcons (Fcons (Qborder_color, build_string ("lightyellow")), parms);
6042 if (NILP (Fassq (Qbackground_color, parms)))
6043 parms = Fcons (Fcons (Qbackground_color, build_string ("lightyellow")),
6044 parms);
6046 /* Block input until the tip has been fully drawn, to avoid crashes
6047 when drawing tips in menus. */
6048 block_input ();
6050 /* Create a frame for the tooltip, and record it in the global
6051 variable tip_frame. */
6052 frame = x_create_tip_frame (FRAME_DISPLAY_INFO (f), parms, string);
6053 f = XFRAME (frame);
6055 /* Set up the frame's root window. */
6056 w = XWINDOW (FRAME_ROOT_WINDOW (f));
6057 w->left_col = 0;
6058 w->top_line = 0;
6059 w->pixel_left = 0;
6060 w->pixel_top = 0;
6062 if (CONSP (Vx_max_tooltip_size)
6063 && INTEGERP (XCAR (Vx_max_tooltip_size))
6064 && XINT (XCAR (Vx_max_tooltip_size)) > 0
6065 && INTEGERP (XCDR (Vx_max_tooltip_size))
6066 && XINT (XCDR (Vx_max_tooltip_size)) > 0)
6068 w->total_cols = XFASTINT (XCAR (Vx_max_tooltip_size));
6069 w->total_lines = XFASTINT (XCDR (Vx_max_tooltip_size));
6071 else
6073 w->total_cols = 80;
6074 w->total_lines = 40;
6077 w->pixel_width = w->total_cols * FRAME_COLUMN_WIDTH (f);
6078 w->pixel_height = w->total_lines * FRAME_LINE_HEIGHT (f);
6080 FRAME_TOTAL_COLS (f) = WINDOW_TOTAL_COLS (w);
6081 adjust_frame_glyphs (f);
6082 w->pseudo_window_p = 1;
6084 /* Display the tooltip text in a temporary buffer. */
6085 old_buffer = current_buffer;
6086 set_buffer_internal_1 (XBUFFER (XWINDOW (FRAME_ROOT_WINDOW (f))->contents));
6087 bset_truncate_lines (current_buffer, Qnil);
6088 clear_glyph_matrix (w->desired_matrix);
6089 clear_glyph_matrix (w->current_matrix);
6090 SET_TEXT_POS (pos, BEGV, BEGV_BYTE);
6091 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6093 /* Compute width and height of the tooltip. */
6094 width = height = seen_reversed_p = 0;
6095 for (i = 0; i < w->desired_matrix->nrows; ++i)
6097 struct glyph_row *row = &w->desired_matrix->rows[i];
6098 struct glyph *last;
6099 int row_width;
6101 /* Stop at the first empty row at the end. */
6102 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6103 break;
6105 /* Let the row go over the full width of the frame. */
6106 row->full_width_p = 1;
6108 row_width = row->pixel_width;
6109 if (row->used[TEXT_AREA])
6111 if (!row->reversed_p)
6113 /* There's a glyph at the end of rows that is used to
6114 place the cursor there. Don't include the width of
6115 this glyph. */
6116 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6117 if (INTEGERP (last->object))
6118 row_width -= last->pixel_width;
6120 else
6122 /* There could be a stretch glyph at the beginning of R2L
6123 rows that is produced by extend_face_to_end_of_line.
6124 Don't count that glyph. */
6125 struct glyph *g = row->glyphs[TEXT_AREA];
6127 if (g->type == STRETCH_GLYPH && INTEGERP (g->object))
6129 row_width -= g->pixel_width;
6130 seen_reversed_p = 1;
6135 height += row->height;
6136 width = max (width, row_width);
6139 /* If we've seen partial-length R2L rows, we need to re-adjust the
6140 tool-tip frame width and redisplay it again, to avoid over-wide
6141 tips due to the stretch glyph that extends R2L lines to full
6142 width of the frame. */
6143 if (seen_reversed_p)
6145 /* PXW: Why do we do the pixel-to-cols conversion only if
6146 seen_reversed_p holds? Don't we have to set other fields of
6147 the window/frame structure?
6149 w->total_cols and FRAME_TOTAL_COLS want the width in columns,
6150 not in pixels. */
6151 w->pixel_width = width;
6152 width /= WINDOW_FRAME_COLUMN_WIDTH (w);
6153 w->total_cols = width;
6154 FRAME_TOTAL_COLS (f) = width;
6155 SET_FRAME_WIDTH (f, width);
6156 adjust_frame_glyphs (f);
6157 w->pseudo_window_p = 1;
6158 clear_glyph_matrix (w->desired_matrix);
6159 clear_glyph_matrix (w->current_matrix);
6160 try_window (FRAME_ROOT_WINDOW (f), pos, TRY_WINDOW_IGNORE_FONTS_CHANGE);
6161 width = height = 0;
6162 /* Recompute width and height of the tooltip. */
6163 for (i = 0; i < w->desired_matrix->nrows; ++i)
6165 struct glyph_row *row = &w->desired_matrix->rows[i];
6166 struct glyph *last;
6167 int row_width;
6169 if (!row->enabled_p || !MATRIX_ROW_DISPLAYS_TEXT_P (row))
6170 break;
6171 row->full_width_p = 1;
6172 row_width = row->pixel_width;
6173 if (row->used[TEXT_AREA] && !row->reversed_p)
6175 last = &row->glyphs[TEXT_AREA][row->used[TEXT_AREA] - 1];
6176 if (INTEGERP (last->object))
6177 row_width -= last->pixel_width;
6180 height += row->height;
6181 width = max (width, row_width);
6185 /* Add the frame's internal border to the width and height the w32
6186 window should have. */
6187 height += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6188 width += 2 * FRAME_INTERNAL_BORDER_WIDTH (f);
6190 /* Move the tooltip window where the mouse pointer is. Resize and
6191 show it.
6193 PXW: This should use the frame's pixel coordinates. */
6194 compute_tip_xy (f, parms, dx, dy, width, height, &root_x, &root_y);
6197 /* Adjust Window size to take border into account. */
6198 RECT rect;
6199 rect.left = rect.top = 0;
6200 rect.right = width;
6201 rect.bottom = height;
6202 AdjustWindowRect (&rect, f->output_data.w32->dwStyle,
6203 FRAME_EXTERNAL_MENU_BAR (f));
6205 /* Position and size tooltip, and put it in the topmost group.
6206 The add-on of FRAME_COLUMN_WIDTH to the 5th argument is a
6207 peculiarity of w32 display: without it, some fonts cause the
6208 last character of the tip to be truncated or wrapped around to
6209 the next line. */
6210 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOPMOST,
6211 root_x, root_y,
6212 rect.right - rect.left + FRAME_COLUMN_WIDTH (f),
6213 rect.bottom - rect.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6215 /* Ensure tooltip is on top of other topmost windows (eg menus). */
6216 SetWindowPos (FRAME_W32_WINDOW (f), HWND_TOP,
6217 0, 0, 0, 0,
6218 SWP_NOMOVE | SWP_NOSIZE
6219 | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
6221 /* Let redisplay know that we have made the frame visible already. */
6222 SET_FRAME_VISIBLE (f, 1);
6224 ShowWindow (FRAME_W32_WINDOW (f), SW_SHOWNOACTIVATE);
6227 /* Draw into the window. */
6228 w->must_be_updated_p = 1;
6229 update_single_window (w, 1);
6231 unblock_input ();
6233 /* Restore original current buffer. */
6234 set_buffer_internal_1 (old_buffer);
6235 windows_or_buffers_changed = old_windows_or_buffers_changed;
6237 start_timer:
6238 /* Let the tip disappear after timeout seconds. */
6239 tip_timer = call3 (intern ("run-at-time"), timeout, Qnil,
6240 intern ("x-hide-tip"));
6242 UNGCPRO;
6243 return unbind_to (count, Qnil);
6247 DEFUN ("x-hide-tip", Fx_hide_tip, Sx_hide_tip, 0, 0, 0,
6248 doc: /* Hide the current tooltip window, if there is any.
6249 Value is t if tooltip was open, nil otherwise. */)
6250 (void)
6252 ptrdiff_t count;
6253 Lisp_Object deleted, frame, timer;
6254 struct gcpro gcpro1, gcpro2;
6256 /* Return quickly if nothing to do. */
6257 if (NILP (tip_timer) && NILP (tip_frame))
6258 return Qnil;
6260 frame = tip_frame;
6261 timer = tip_timer;
6262 GCPRO2 (frame, timer);
6263 tip_frame = tip_timer = deleted = Qnil;
6265 count = SPECPDL_INDEX ();
6266 specbind (Qinhibit_redisplay, Qt);
6267 specbind (Qinhibit_quit, Qt);
6269 if (!NILP (timer))
6270 call1 (Qcancel_timer, timer);
6272 if (FRAMEP (frame))
6274 delete_frame (frame, Qnil);
6275 deleted = Qt;
6278 UNGCPRO;
6279 return unbind_to (count, deleted);
6282 /***********************************************************************
6283 File selection dialog
6284 ***********************************************************************/
6286 #define FILE_NAME_TEXT_FIELD edt1
6287 #define FILE_NAME_COMBO_BOX cmb13
6288 #define FILE_NAME_LIST lst1
6290 /* Callback for altering the behavior of the Open File dialog.
6291 Makes the Filename text field contain "Current Directory" and be
6292 read-only when "Directories" is selected in the filter. This
6293 allows us to work around the fact that the standard Open File
6294 dialog does not support directories. */
6295 static UINT_PTR CALLBACK
6296 file_dialog_callback (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
6298 if (msg == WM_NOTIFY)
6300 OFNOTIFYW * notify_w = (OFNOTIFYW *)lParam;
6301 OFNOTIFYA * notify_a = (OFNOTIFYA *)lParam;
6302 int dropdown_changed;
6303 int dir_index;
6304 #ifdef NTGUI_UNICODE
6305 const int use_unicode = 1;
6306 #else /* !NTGUI_UNICODE */
6307 int use_unicode = w32_unicode_filenames;
6308 #endif /* NTGUI_UNICODE */
6310 /* Detect when the Filter dropdown is changed. */
6311 if (use_unicode)
6312 dropdown_changed =
6313 notify_w->hdr.code == CDN_TYPECHANGE
6314 || notify_w->hdr.code == CDN_INITDONE;
6315 else
6316 dropdown_changed =
6317 notify_a->hdr.code == CDN_TYPECHANGE
6318 || notify_a->hdr.code == CDN_INITDONE;
6319 if (dropdown_changed)
6321 HWND dialog = GetParent (hwnd);
6322 HWND edit_control = GetDlgItem (dialog, FILE_NAME_TEXT_FIELD);
6323 HWND list = GetDlgItem (dialog, FILE_NAME_LIST);
6324 int hdr_code;
6326 /* At least on Windows 7, the above attempt to get the window handle
6327 to the File Name Text Field fails. The following code does the
6328 job though. Note that this code is based on my examination of the
6329 window hierarchy using Microsoft Spy++. bk */
6330 if (edit_control == NULL)
6332 HWND tmp = GetDlgItem (dialog, FILE_NAME_COMBO_BOX);
6333 if (tmp)
6335 tmp = GetWindow (tmp, GW_CHILD);
6336 if (tmp)
6337 edit_control = GetWindow (tmp, GW_CHILD);
6341 /* Directories is in index 2. */
6342 if (use_unicode)
6344 dir_index = notify_w->lpOFN->nFilterIndex;
6345 hdr_code = notify_w->hdr.code;
6347 else
6349 dir_index = notify_a->lpOFN->nFilterIndex;
6350 hdr_code = notify_a->hdr.code;
6352 if (dir_index == 2)
6354 if (use_unicode)
6355 SendMessageW (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6356 (LPARAM)L"Current Directory");
6357 else
6358 SendMessageA (dialog, CDM_SETCONTROLTEXT, FILE_NAME_TEXT_FIELD,
6359 (LPARAM)"Current Directory");
6360 EnableWindow (edit_control, FALSE);
6361 /* Note that at least on Windows 7, the above call to EnableWindow
6362 disables the window that would ordinarily have focus. If we
6363 do not set focus to some other window here, focus will land in
6364 no man's land and the user will be unable to tab through the
6365 dialog box (pressing tab will only result in a beep).
6366 Avoid that problem by setting focus to the list here. */
6367 if (hdr_code == CDN_INITDONE)
6368 SetFocus (list);
6370 else
6372 /* Don't override default filename on init done. */
6373 if (hdr_code == CDN_TYPECHANGE)
6375 if (use_unicode)
6376 SendMessageW (dialog, CDM_SETCONTROLTEXT,
6377 FILE_NAME_TEXT_FIELD, (LPARAM)L"");
6378 else
6379 SendMessageA (dialog, CDM_SETCONTROLTEXT,
6380 FILE_NAME_TEXT_FIELD, (LPARAM)"");
6382 EnableWindow (edit_control, TRUE);
6386 return 0;
6389 DEFUN ("x-file-dialog", Fx_file_dialog, Sx_file_dialog, 2, 5, 0,
6390 doc: /* Read file name, prompting with PROMPT in directory DIR.
6391 Use a file selection dialog. Select DEFAULT-FILENAME in the dialog's file
6392 selection box, if specified. If MUSTMATCH is non-nil, the returned file
6393 or directory must exist.
6395 This function is only defined on NS, MS Windows, and X Windows with the
6396 Motif or Gtk toolkits. With the Motif toolkit, ONLY-DIR-P is ignored.
6397 Otherwise, if ONLY-DIR-P is non-nil, the user can only select directories.
6398 On Windows 7 and later, the file selection dialog "remembers" the last
6399 directory where the user selected a file, and will open that directory
6400 instead of DIR on subsequent invocations of this function with the same
6401 value of DIR as in previous invocations; this is standard Windows behavior. */)
6402 (Lisp_Object prompt, Lisp_Object dir, Lisp_Object default_filename, Lisp_Object mustmatch, Lisp_Object only_dir_p)
6404 /* Filter index: 1: All Files, 2: Directories only */
6405 static const wchar_t filter_w[] = L"All Files (*.*)\0*.*\0Directories\0*|*\0";
6406 static const char filter_a[] = "All Files (*.*)\0*.*\0Directories\0*|*\0";
6408 Lisp_Object filename = default_filename;
6409 struct frame *f = SELECTED_FRAME ();
6410 BOOL file_opened = FALSE;
6411 Lisp_Object orig_dir = dir;
6412 Lisp_Object orig_prompt = prompt;
6414 /* If we compile with _WIN32_WINNT set to 0x0400 (for NT4
6415 compatibility) we end up with the old file dialogs. Define a big
6416 enough struct for the new dialog to trick GetOpenFileName into
6417 giving us the new dialogs on newer versions of Windows. */
6418 struct {
6419 OPENFILENAMEW details;
6420 #if _WIN32_WINNT < 0x500 /* < win2k */
6421 PVOID pvReserved;
6422 DWORD dwReserved;
6423 DWORD FlagsEx;
6424 #endif /* < win2k */
6425 } new_file_details_w;
6427 #ifdef NTGUI_UNICODE
6428 wchar_t filename_buf_w[32*1024 + 1]; // NT kernel maximum
6429 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6430 const int use_unicode = 1;
6431 #else /* not NTGUI_UNICODE */
6432 struct {
6433 OPENFILENAMEA details;
6434 #if _WIN32_WINNT < 0x500 /* < win2k */
6435 PVOID pvReserved;
6436 DWORD dwReserved;
6437 DWORD FlagsEx;
6438 #endif /* < win2k */
6439 } new_file_details_a;
6440 wchar_t filename_buf_w[MAX_PATH + 1], dir_w[MAX_PATH];
6441 char filename_buf_a[MAX_PATH + 1], dir_a[MAX_PATH];
6442 OPENFILENAMEW * file_details_w = &new_file_details_w.details;
6443 OPENFILENAMEA * file_details_a = &new_file_details_a.details;
6444 int use_unicode = w32_unicode_filenames;
6445 wchar_t *prompt_w;
6446 char *prompt_a;
6447 int len;
6448 char fname_ret[MAX_UTF8_PATH];
6449 #endif /* NTGUI_UNICODE */
6451 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5, gcpro6;
6452 GCPRO6 (prompt, dir, default_filename, mustmatch, only_dir_p, filename);
6455 struct gcpro gcpro1, gcpro2;
6456 GCPRO2 (orig_dir, orig_prompt); /* There is no GCPRON, N>6. */
6458 /* Note: under NTGUI_UNICODE, we do _NOT_ use ENCODE_FILE: the
6459 system file encoding expected by the platform APIs (e.g. Cygwin's
6460 POSIX implementation) may not be the same as the encoding expected
6461 by the Windows "ANSI" APIs! */
6463 CHECK_STRING (prompt);
6464 CHECK_STRING (dir);
6466 dir = Fexpand_file_name (dir, Qnil);
6468 if (STRINGP (filename))
6469 filename = Ffile_name_nondirectory (filename);
6470 else
6471 filename = empty_unibyte_string;
6473 #ifdef CYGWIN
6474 dir = Fcygwin_convert_file_name_to_windows (dir, Qt);
6475 if (SCHARS (filename) > 0)
6476 filename = Fcygwin_convert_file_name_to_windows (filename, Qnil);
6477 #endif
6479 CHECK_STRING (dir);
6480 CHECK_STRING (filename);
6482 /* The code in file_dialog_callback that attempts to set the text
6483 of the file name edit window when handling the CDN_INITDONE
6484 WM_NOTIFY message does not work. Setting filename to "Current
6485 Directory" in the only_dir_p case here does work however. */
6486 if (SCHARS (filename) == 0 && ! NILP (only_dir_p))
6487 filename = build_string ("Current Directory");
6489 /* Convert the values we've computed so far to system form. */
6490 #ifdef NTGUI_UNICODE
6491 to_unicode (prompt, &prompt);
6492 to_unicode (dir, &dir);
6493 to_unicode (filename, &filename);
6494 if (SBYTES (filename) + 1 > sizeof (filename_buf_w))
6495 report_file_error ("filename too long", default_filename);
6497 memcpy (filename_buf_w, SDATA (filename), SBYTES (filename) + 1);
6498 #else /* !NTGUI_UNICODE */
6499 prompt = ENCODE_FILE (prompt);
6500 dir = ENCODE_FILE (dir);
6501 filename = ENCODE_FILE (filename);
6503 /* We modify these in-place, so make copies for safety. */
6504 dir = Fcopy_sequence (dir);
6505 unixtodos_filename (SDATA (dir));
6506 filename = Fcopy_sequence (filename);
6507 unixtodos_filename (SDATA (filename));
6508 if (SBYTES (filename) >= MAX_UTF8_PATH)
6509 report_file_error ("filename too long", default_filename);
6510 if (w32_unicode_filenames)
6512 filename_to_utf16 (SSDATA (dir), dir_w);
6513 if (filename_to_utf16 (SSDATA (filename), filename_buf_w) != 0)
6515 /* filename_to_utf16 sets errno to ENOENT when the file
6516 name is too long or cannot be converted to UTF-16. */
6517 if (errno == ENOENT && filename_buf_w[MAX_PATH - 1] != 0)
6518 report_file_error ("filename too long", default_filename);
6520 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6521 SSDATA (prompt), -1, NULL, 0);
6522 if (len > 32768)
6523 len = 32768;
6524 prompt_w = alloca (len * sizeof (wchar_t));
6525 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6526 SSDATA (prompt), -1, prompt_w, len);
6528 else
6530 filename_to_ansi (SSDATA (dir), dir_a);
6531 if (filename_to_ansi (SSDATA (filename), filename_buf_a) != '\0')
6533 /* filename_to_ansi sets errno to ENOENT when the file
6534 name is too long or cannot be converted to UTF-16. */
6535 if (errno == ENOENT && filename_buf_a[MAX_PATH - 1] != 0)
6536 report_file_error ("filename too long", default_filename);
6538 len = pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6539 SSDATA (prompt), -1, NULL, 0);
6540 if (len > 32768)
6541 len = 32768;
6542 prompt_w = alloca (len * sizeof (wchar_t));
6543 pMultiByteToWideChar (CP_UTF8, MB_ERR_INVALID_CHARS,
6544 SSDATA (prompt), -1, prompt_w, len);
6545 len = pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, NULL, 0, NULL, NULL);
6546 if (len > 32768)
6547 len = 32768;
6548 prompt_a = alloca (len);
6549 pWideCharToMultiByte (CP_ACP, 0, prompt_w, -1, prompt_a, len, NULL, NULL);
6551 #endif /* NTGUI_UNICODE */
6553 /* Fill in the structure for the call to GetOpenFileName below.
6554 For NTGUI_UNICODE builds (which run only on NT), we just use
6555 the actual size of the structure. For non-NTGUI_UNICODE
6556 builds, we tell the OS we're using an old version of the
6557 structure if the OS isn't new enough to support the newer
6558 version. */
6559 if (use_unicode)
6561 memset (&new_file_details_w, 0, sizeof (new_file_details_w));
6562 if (w32_major_version > 4 && w32_major_version < 95)
6563 file_details_w->lStructSize = sizeof (new_file_details_w);
6564 else
6565 file_details_w->lStructSize = sizeof (*file_details_w);
6566 /* Set up the inout parameter for the selected file name. */
6567 file_details_w->lpstrFile = filename_buf_w;
6568 file_details_w->nMaxFile =
6569 sizeof (filename_buf_w) / sizeof (*filename_buf_w);
6570 file_details_w->hwndOwner = FRAME_W32_WINDOW (f);
6571 /* Undocumented Bug in Common File Dialog:
6572 If a filter is not specified, shell links are not resolved. */
6573 file_details_w->lpstrFilter = filter_w;
6574 #ifdef NTGUI_UNICODE
6575 file_details_w->lpstrInitialDir = (wchar_t*) SDATA (dir);
6576 file_details_w->lpstrTitle = (guichar_t*) SDATA (prompt);
6577 #else
6578 file_details_w->lpstrInitialDir = dir_w;
6579 file_details_w->lpstrTitle = prompt_w;
6580 #endif
6581 file_details_w->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6582 file_details_w->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6583 | OFN_EXPLORER | OFN_ENABLEHOOK);
6584 if (!NILP (mustmatch))
6586 /* Require that the path to the parent directory exists. */
6587 file_details_w->Flags |= OFN_PATHMUSTEXIST;
6588 /* If we are looking for a file, require that it exists. */
6589 if (NILP (only_dir_p))
6590 file_details_w->Flags |= OFN_FILEMUSTEXIST;
6593 #ifndef NTGUI_UNICODE
6594 else
6596 memset (&new_file_details_a, 0, sizeof (new_file_details_a));
6597 if (w32_major_version > 4 && w32_major_version < 95)
6598 file_details_a->lStructSize = sizeof (new_file_details_a);
6599 else
6600 file_details_a->lStructSize = sizeof (*file_details_a);
6601 file_details_a->lpstrFile = filename_buf_a;
6602 file_details_a->nMaxFile =
6603 sizeof (filename_buf_a) / sizeof (*filename_buf_a);
6604 file_details_a->hwndOwner = FRAME_W32_WINDOW (f);
6605 file_details_a->lpstrFilter = filter_a;
6606 file_details_a->lpstrInitialDir = dir_a;
6607 file_details_a->lpstrTitle = prompt_a;
6608 file_details_a->nFilterIndex = NILP (only_dir_p) ? 1 : 2;
6609 file_details_a->Flags = (OFN_HIDEREADONLY | OFN_NOCHANGEDIR
6610 | OFN_EXPLORER | OFN_ENABLEHOOK);
6611 if (!NILP (mustmatch))
6613 /* Require that the path to the parent directory exists. */
6614 file_details_a->Flags |= OFN_PATHMUSTEXIST;
6615 /* If we are looking for a file, require that it exists. */
6616 if (NILP (only_dir_p))
6617 file_details_a->Flags |= OFN_FILEMUSTEXIST;
6620 #endif /* !NTGUI_UNICODE */
6623 int count = SPECPDL_INDEX ();
6624 /* Prevent redisplay. */
6625 specbind (Qinhibit_redisplay, Qt);
6626 block_input ();
6627 if (use_unicode)
6629 file_details_w->lpfnHook = file_dialog_callback;
6631 file_opened = GetOpenFileNameW (file_details_w);
6633 #ifndef NTGUI_UNICODE
6634 else
6636 file_details_a->lpfnHook = file_dialog_callback;
6638 file_opened = GetOpenFileNameA (file_details_a);
6640 #endif /* !NTGUI_UNICODE */
6641 unblock_input ();
6642 unbind_to (count, Qnil);
6645 if (file_opened)
6647 /* Get an Emacs string from the value Windows gave us. */
6648 #ifdef NTGUI_UNICODE
6649 filename = from_unicode_buffer (filename_buf_w);
6650 #else /* !NTGUI_UNICODE */
6651 if (use_unicode)
6652 filename_from_utf16 (filename_buf_w, fname_ret);
6653 else
6654 filename_from_ansi (filename_buf_a, fname_ret);
6655 dostounix_filename (fname_ret);
6656 filename = DECODE_FILE (build_unibyte_string (fname_ret));
6657 #endif /* NTGUI_UNICODE */
6659 #ifdef CYGWIN
6660 filename = Fcygwin_convert_file_name_from_windows (filename, Qt);
6661 #endif /* CYGWIN */
6663 /* Strip the dummy filename off the end of the string if we
6664 added it to select a directory. */
6665 if ((use_unicode && file_details_w->nFilterIndex == 2)
6666 #ifndef NTGUI_UNICODE
6667 || (!use_unicode && file_details_a->nFilterIndex == 2)
6668 #endif
6670 filename = Ffile_name_directory (filename);
6672 /* User canceled the dialog without making a selection. */
6673 else if (!CommDlgExtendedError ())
6674 filename = Qnil;
6675 /* An error occurred, fallback on reading from the mini-buffer. */
6676 else
6677 filename = Fcompleting_read (
6678 orig_prompt,
6679 intern ("read-file-name-internal"),
6680 orig_dir,
6681 mustmatch,
6682 orig_dir,
6683 Qfile_name_history,
6684 default_filename,
6685 Qnil);
6687 UNGCPRO;
6690 /* Make "Cancel" equivalent to C-g. */
6691 if (NILP (filename))
6692 Fsignal (Qquit, Qnil);
6694 RETURN_UNGCPRO (filename);
6698 #ifdef WINDOWSNT
6699 /* Moving files to the system recycle bin.
6700 Used by `move-file-to-trash' instead of the default moving to ~/.Trash */
6701 DEFUN ("system-move-file-to-trash", Fsystem_move_file_to_trash,
6702 Ssystem_move_file_to_trash, 1, 1, 0,
6703 doc: /* Move file or directory named FILENAME to the recycle bin. */)
6704 (Lisp_Object filename)
6706 Lisp_Object handler;
6707 Lisp_Object encoded_file;
6708 Lisp_Object operation;
6710 operation = Qdelete_file;
6711 if (!NILP (Ffile_directory_p (filename))
6712 && NILP (Ffile_symlink_p (filename)))
6714 operation = intern ("delete-directory");
6715 filename = Fdirectory_file_name (filename);
6718 /* Must have fully qualified file names for moving files to Recycle
6719 Bin. */
6720 filename = Fexpand_file_name (filename, Qnil);
6722 handler = Ffind_file_name_handler (filename, operation);
6723 if (!NILP (handler))
6724 return call2 (handler, operation, filename);
6725 else
6727 const char * path;
6728 int result;
6730 encoded_file = ENCODE_FILE (filename);
6732 path = map_w32_filename (SDATA (encoded_file), NULL);
6734 /* The Unicode version of SHFileOperation is not supported on
6735 Windows 9X. */
6736 if (w32_unicode_filenames && os_subtype != OS_9X)
6738 SHFILEOPSTRUCTW file_op_w;
6739 /* We need one more element beyond MAX_PATH because this is
6740 a list of file names, with the last element double-null
6741 terminated. */
6742 wchar_t tmp_path_w[MAX_PATH + 1];
6744 memset (tmp_path_w, 0, sizeof (tmp_path_w));
6745 filename_to_utf16 (path, tmp_path_w);
6747 /* On Windows, write permission is required to delete/move files. */
6748 _wchmod (tmp_path_w, 0666);
6750 memset (&file_op_w, 0, sizeof (file_op_w));
6751 file_op_w.hwnd = HWND_DESKTOP;
6752 file_op_w.wFunc = FO_DELETE;
6753 file_op_w.pFrom = tmp_path_w;
6754 file_op_w.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6755 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6756 file_op_w.fAnyOperationsAborted = FALSE;
6758 result = SHFileOperationW (&file_op_w);
6760 else
6762 SHFILEOPSTRUCTA file_op_a;
6763 char tmp_path_a[MAX_PATH + 1];
6765 memset (tmp_path_a, 0, sizeof (tmp_path_a));
6766 filename_to_ansi (path, tmp_path_a);
6768 /* If a file cannot be represented in ANSI codepage, don't
6769 let them inadvertently delete other files because some
6770 characters are interpreted as a wildcards. */
6771 if (_mbspbrk (tmp_path_a, "?*"))
6772 result = ERROR_FILE_NOT_FOUND;
6773 else
6775 _chmod (tmp_path_a, 0666);
6777 memset (&file_op_a, 0, sizeof (file_op_a));
6778 file_op_a.hwnd = HWND_DESKTOP;
6779 file_op_a.wFunc = FO_DELETE;
6780 file_op_a.pFrom = tmp_path_a;
6781 file_op_a.fFlags = FOF_SILENT | FOF_NOCONFIRMATION | FOF_ALLOWUNDO
6782 | FOF_NOERRORUI | FOF_NO_CONNECTED_ELEMENTS;
6783 file_op_a.fAnyOperationsAborted = FALSE;
6785 result = SHFileOperationA (&file_op_a);
6788 if (result != 0)
6789 report_file_error ("Removing old name", list1 (filename));
6791 return Qnil;
6794 #endif /* WINDOWSNT */
6797 /***********************************************************************
6798 w32 specialized functions
6799 ***********************************************************************/
6801 DEFUN ("w32-send-sys-command", Fw32_send_sys_command,
6802 Sw32_send_sys_command, 1, 2, 0,
6803 doc: /* Send frame a Windows WM_SYSCOMMAND message of type COMMAND.
6804 Some useful values for COMMAND are #xf030 to maximize frame (#xf020
6805 to minimize), #xf120 to restore frame to original size, and #xf100
6806 to activate the menubar for keyboard access. #xf140 activates the
6807 screen saver if defined.
6809 If optional parameter FRAME is not specified, use selected frame. */)
6810 (Lisp_Object command, Lisp_Object frame)
6812 struct frame *f = decode_window_system_frame (frame);
6814 CHECK_NUMBER (command);
6816 PostMessage (FRAME_W32_WINDOW (f), WM_SYSCOMMAND, XINT (command), 0);
6818 return Qnil;
6821 DEFUN ("w32-shell-execute", Fw32_shell_execute, Sw32_shell_execute, 2, 4, 0,
6822 doc: /* Get Windows to perform OPERATION on DOCUMENT.
6823 This is a wrapper around the ShellExecute system function, which
6824 invokes the application registered to handle OPERATION for DOCUMENT.
6826 OPERATION is either nil or a string that names a supported operation.
6827 What operations can be used depends on the particular DOCUMENT and its
6828 handler application, but typically it is one of the following common
6829 operations:
6831 \"open\" - open DOCUMENT, which could be a file, a directory, or an
6832 executable program (application). If it is an application,
6833 that application is launched in the current buffer's default
6834 directory. Otherwise, the application associated with
6835 DOCUMENT is launched in the buffer's default directory.
6836 \"opennew\" - like \"open\", but instruct the application to open
6837 DOCUMENT in a new window.
6838 \"openas\" - open the \"Open With\" dialog for DOCUMENT.
6839 \"print\" - print DOCUMENT, which must be a file.
6840 \"printto\" - print DOCUMENT, which must be a file, to a specified printer.
6841 The printer should be provided in PARAMETERS, see below.
6842 \"explore\" - start the Windows Explorer on DOCUMENT.
6843 \"edit\" - launch an editor and open DOCUMENT for editing; which
6844 editor is launched depends on the association for the
6845 specified DOCUMENT.
6846 \"find\" - initiate search starting from DOCUMENT, which must specify
6847 a directory.
6848 \"delete\" - move DOCUMENT, a file or a directory, to Recycle Bin.
6849 \"copy\" - copy DOCUMENT, which must be a file or a directory, into
6850 the clipboard.
6851 \"cut\" - move DOCUMENT, a file or a directory, into the clipboard.
6852 \"paste\" - paste the file whose name is in the clipboard into DOCUMENT,
6853 which must be a directory.
6854 \"pastelink\"
6855 - create a shortcut in DOCUMENT (which must be a directory)
6856 the file or directory whose name is in the clipboard.
6857 \"runas\" - run DOCUMENT, which must be an excutable file, with
6858 elevated privileges (a.k.a. \"as Administrator\").
6859 \"properties\"
6860 - open the property sheet dialog for DOCUMENT.
6861 nil - invoke the default OPERATION, or \"open\" if default is
6862 not defined or unavailable.
6864 DOCUMENT is typically the name of a document file or a URL, but can
6865 also be an executable program to run, or a directory to open in the
6866 Windows Explorer. If it is a file or a directory, it must be a local
6867 one; this function does not support remote file names.
6869 If DOCUMENT is an executable program, the optional third arg PARAMETERS
6870 can be a string containing command line parameters, separated by blanks,
6871 that will be passed to the program. Some values of OPERATION also require
6872 parameters (e.g., \"printto\" requires the printer address). Otherwise,
6873 PARAMETERS should be nil or unspecified. Note that double quote characters
6874 in PARAMETERS must each be enclosed in 2 additional quotes, as in \"\"\".
6876 Optional fourth argument SHOW-FLAG can be used to control how the
6877 application will be displayed when it is invoked. If SHOW-FLAG is nil
6878 or unspecified, the application is displayed as if SHOW-FLAG of 10 was
6879 specified, otherwise it is an integer between 0 and 11 representing
6880 a ShowWindow flag:
6882 0 - start hidden
6883 1 - start as normal-size window
6884 3 - start in a maximized window
6885 6 - start in a minimized window
6886 10 - start as the application itself specifies; this is the default. */)
6887 (Lisp_Object operation, Lisp_Object document, Lisp_Object parameters, Lisp_Object show_flag)
6889 char *errstr;
6890 Lisp_Object current_dir = BVAR (current_buffer, directory);;
6891 wchar_t *doc_w = NULL, *params_w = NULL, *ops_w = NULL;
6892 #ifdef CYGWIN
6893 intptr_t result;
6894 #else
6895 int use_unicode = w32_unicode_filenames;
6896 char *doc_a = NULL, *params_a = NULL, *ops_a = NULL;
6897 Lisp_Object absdoc, handler;
6898 BOOL success;
6899 struct gcpro gcpro1;
6900 #endif
6902 CHECK_STRING (document);
6904 #ifdef CYGWIN
6905 current_dir = Fcygwin_convert_file_name_to_windows (current_dir, Qt);
6906 document = Fcygwin_convert_file_name_to_windows (document, Qt);
6908 /* Encode filename, current directory and parameters. */
6909 current_dir = GUI_ENCODE_FILE (current_dir);
6910 document = GUI_ENCODE_FILE (document);
6911 doc_w = GUI_SDATA (document);
6912 if (STRINGP (parameters))
6914 parameters = GUI_ENCODE_SYSTEM (parameters);
6915 params_w = GUI_SDATA (parameters);
6917 if (STRINGP (operation))
6919 operation = GUI_ENCODE_SYSTEM (operation);
6920 ops_w = GUI_SDATA (operation);
6922 result = (intptr_t) ShellExecuteW (NULL, ops_w, doc_w, params_w,
6923 GUI_SDATA (current_dir),
6924 (INTEGERP (show_flag)
6925 ? XINT (show_flag) : SW_SHOWDEFAULT));
6927 if (result > 32)
6928 return Qt;
6930 switch (result)
6932 case SE_ERR_ACCESSDENIED:
6933 errstr = w32_strerror (ERROR_ACCESS_DENIED);
6934 break;
6935 case SE_ERR_ASSOCINCOMPLETE:
6936 case SE_ERR_NOASSOC:
6937 errstr = w32_strerror (ERROR_NO_ASSOCIATION);
6938 break;
6939 case SE_ERR_DDEBUSY:
6940 case SE_ERR_DDEFAIL:
6941 errstr = w32_strerror (ERROR_DDE_FAIL);
6942 break;
6943 case SE_ERR_DDETIMEOUT:
6944 errstr = w32_strerror (ERROR_TIMEOUT);
6945 break;
6946 case SE_ERR_DLLNOTFOUND:
6947 errstr = w32_strerror (ERROR_DLL_NOT_FOUND);
6948 break;
6949 case SE_ERR_FNF:
6950 errstr = w32_strerror (ERROR_FILE_NOT_FOUND);
6951 break;
6952 case SE_ERR_OOM:
6953 errstr = w32_strerror (ERROR_NOT_ENOUGH_MEMORY);
6954 break;
6955 case SE_ERR_PNF:
6956 errstr = w32_strerror (ERROR_PATH_NOT_FOUND);
6957 break;
6958 case SE_ERR_SHARE:
6959 errstr = w32_strerror (ERROR_SHARING_VIOLATION);
6960 break;
6961 default:
6962 errstr = w32_strerror (0);
6963 break;
6966 #else /* !CYGWIN */
6968 current_dir = ENCODE_FILE (current_dir);
6969 /* We have a situation here. If DOCUMENT is a relative file name,
6970 but its name includes leading directories, i.e. it lives not in
6971 CURRENT_DIR, but in its subdirectory, then ShellExecute below
6972 will fail to find it. So we need to make the file name is
6973 absolute. But DOCUMENT does not have to be a file, it can be a
6974 URL, for example. So we make it absolute only if it is an
6975 existing file; if it is a file that does not exist, tough. */
6976 GCPRO1 (absdoc);
6977 absdoc = Fexpand_file_name (document, Qnil);
6978 /* Don't call file handlers for file-exists-p, since they might
6979 attempt to access the file, which could fail or produce undesired
6980 consequences, see bug#16558 for an example. */
6981 handler = Ffind_file_name_handler (absdoc, Qfile_exists_p);
6982 if (NILP (handler))
6984 Lisp_Object absdoc_encoded = ENCODE_FILE (absdoc);
6986 if (faccessat (AT_FDCWD, SSDATA (absdoc_encoded), F_OK, AT_EACCESS) == 0)
6987 document = absdoc_encoded;
6988 else
6989 document = ENCODE_FILE (document);
6991 else
6992 document = ENCODE_FILE (document);
6993 UNGCPRO;
6994 if (use_unicode)
6996 wchar_t document_w[MAX_PATH], current_dir_w[MAX_PATH];
6997 SHELLEXECUTEINFOW shexinfo_w;
6999 /* Encode filename, current directory and parameters, and
7000 convert operation to UTF-16. */
7001 filename_to_utf16 (SSDATA (current_dir), current_dir_w);
7002 filename_to_utf16 (SSDATA (document), document_w);
7003 doc_w = document_w;
7004 if (STRINGP (parameters))
7006 int len;
7008 parameters = ENCODE_SYSTEM (parameters);
7009 len = pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7010 SSDATA (parameters), -1, NULL, 0);
7011 if (len > 32768)
7012 len = 32768;
7013 params_w = alloca (len * sizeof (wchar_t));
7014 pMultiByteToWideChar (CP_ACP, MB_ERR_INVALID_CHARS,
7015 SSDATA (parameters), -1, params_w, len);
7017 if (STRINGP (operation))
7019 /* Assume OPERATION is pure ASCII. */
7020 const char *s = SSDATA (operation);
7021 wchar_t *d;
7022 int len = SBYTES (operation) + 1;
7024 if (len > 32768)
7025 len = 32768;
7026 d = ops_w = alloca (len * sizeof (wchar_t));
7027 while (d < ops_w + len - 1)
7028 *d++ = *s++;
7029 *d = 0;
7032 /* Using ShellExecuteEx and setting the SEE_MASK_INVOKEIDLIST
7033 flag succeeds with more OPERATIONs (a.k.a. "verbs"), as it is
7034 able to invoke verbs from shortcut menu extensions, not just
7035 static verbs listed in the Registry. */
7036 memset (&shexinfo_w, 0, sizeof (shexinfo_w));
7037 shexinfo_w.cbSize = sizeof (shexinfo_w);
7038 shexinfo_w.fMask =
7039 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7040 shexinfo_w.hwnd = NULL;
7041 shexinfo_w.lpVerb = ops_w;
7042 shexinfo_w.lpFile = doc_w;
7043 shexinfo_w.lpParameters = params_w;
7044 shexinfo_w.lpDirectory = current_dir_w;
7045 shexinfo_w.nShow =
7046 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7047 success = ShellExecuteExW (&shexinfo_w);
7049 else
7051 char document_a[MAX_PATH], current_dir_a[MAX_PATH];
7052 SHELLEXECUTEINFOA shexinfo_a;
7054 filename_to_ansi (SSDATA (current_dir), current_dir_a);
7055 filename_to_ansi (SSDATA (document), document_a);
7056 doc_a = document_a;
7057 if (STRINGP (parameters))
7059 parameters = ENCODE_SYSTEM (parameters);
7060 params_a = SSDATA (parameters);
7062 if (STRINGP (operation))
7064 /* Assume OPERATION is pure ASCII. */
7065 ops_a = SSDATA (operation);
7067 memset (&shexinfo_a, 0, sizeof (shexinfo_a));
7068 shexinfo_a.cbSize = sizeof (shexinfo_a);
7069 shexinfo_a.fMask =
7070 SEE_MASK_INVOKEIDLIST | SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
7071 shexinfo_a.hwnd = NULL;
7072 shexinfo_a.lpVerb = ops_a;
7073 shexinfo_a.lpFile = doc_a;
7074 shexinfo_a.lpParameters = params_a;
7075 shexinfo_a.lpDirectory = current_dir_a;
7076 shexinfo_a.nShow =
7077 (INTEGERP (show_flag) ? XINT (show_flag) : SW_SHOWDEFAULT);
7078 success = ShellExecuteExA (&shexinfo_a);
7081 if (success)
7082 return Qt;
7084 errstr = w32_strerror (0);
7086 #endif /* !CYGWIN */
7088 /* The error string might be encoded in the locale's encoding. */
7089 if (!NILP (Vlocale_coding_system))
7091 Lisp_Object decoded =
7092 code_convert_string_norecord (build_unibyte_string (errstr),
7093 Vlocale_coding_system, 0);
7094 errstr = SSDATA (decoded);
7096 error ("ShellExecute failed: %s", errstr);
7099 /* Lookup virtual keycode from string representing the name of a
7100 non-ascii keystroke into the corresponding virtual key, using
7101 lispy_function_keys. */
7102 static int
7103 lookup_vk_code (char *key)
7105 int i;
7107 for (i = 0; i < 256; i++)
7108 if (lispy_function_keys[i]
7109 && strcmp (lispy_function_keys[i], key) == 0)
7110 return i;
7112 return -1;
7115 /* Convert a one-element vector style key sequence to a hot key
7116 definition. */
7117 static Lisp_Object
7118 w32_parse_hot_key (Lisp_Object key)
7120 /* Copied from Fdefine_key and store_in_keymap. */
7121 register Lisp_Object c;
7122 int vk_code;
7123 int lisp_modifiers;
7124 int w32_modifiers;
7125 struct gcpro gcpro1;
7127 CHECK_VECTOR (key);
7129 if (ASIZE (key) != 1)
7130 return Qnil;
7132 GCPRO1 (key);
7134 c = AREF (key, 0);
7136 if (CONSP (c) && lucid_event_type_list_p (c))
7137 c = Fevent_convert_list (c);
7139 UNGCPRO;
7141 if (! INTEGERP (c) && ! SYMBOLP (c))
7142 error ("Key definition is invalid");
7144 /* Work out the base key and the modifiers. */
7145 if (SYMBOLP (c))
7147 c = parse_modifiers (c);
7148 lisp_modifiers = XINT (Fcar (Fcdr (c)));
7149 c = Fcar (c);
7150 if (!SYMBOLP (c))
7151 emacs_abort ();
7152 vk_code = lookup_vk_code (SDATA (SYMBOL_NAME (c)));
7154 else if (INTEGERP (c))
7156 lisp_modifiers = XINT (c) & ~CHARACTERBITS;
7157 /* Many ascii characters are their own virtual key code. */
7158 vk_code = XINT (c) & CHARACTERBITS;
7161 if (vk_code < 0 || vk_code > 255)
7162 return Qnil;
7164 if ((lisp_modifiers & meta_modifier) != 0
7165 && !NILP (Vw32_alt_is_meta))
7166 lisp_modifiers |= alt_modifier;
7168 /* Supply defs missing from mingw32. */
7169 #ifndef MOD_ALT
7170 #define MOD_ALT 0x0001
7171 #define MOD_CONTROL 0x0002
7172 #define MOD_SHIFT 0x0004
7173 #define MOD_WIN 0x0008
7174 #endif
7176 /* Convert lisp modifiers to Windows hot-key form. */
7177 w32_modifiers = (lisp_modifiers & hyper_modifier) ? MOD_WIN : 0;
7178 w32_modifiers |= (lisp_modifiers & alt_modifier) ? MOD_ALT : 0;
7179 w32_modifiers |= (lisp_modifiers & ctrl_modifier) ? MOD_CONTROL : 0;
7180 w32_modifiers |= (lisp_modifiers & shift_modifier) ? MOD_SHIFT : 0;
7182 return HOTKEY (vk_code, w32_modifiers);
7185 DEFUN ("w32-register-hot-key", Fw32_register_hot_key,
7186 Sw32_register_hot_key, 1, 1, 0,
7187 doc: /* Register KEY as a hot-key combination.
7188 Certain key combinations like Alt-Tab are reserved for system use on
7189 Windows, and therefore are normally intercepted by the system. However,
7190 most of these key combinations can be received by registering them as
7191 hot-keys, overriding their special meaning.
7193 KEY must be a one element key definition in vector form that would be
7194 acceptable to `define-key' (e.g. [A-tab] for Alt-Tab). The meta
7195 modifier is interpreted as Alt if `w32-alt-is-meta' is t, and hyper
7196 is always interpreted as the Windows modifier keys.
7198 The return value is the hotkey-id if registered, otherwise nil. */)
7199 (Lisp_Object key)
7201 key = w32_parse_hot_key (key);
7203 if (!NILP (key) && NILP (Fmemq (key, w32_grabbed_keys)))
7205 /* Reuse an empty slot if possible. */
7206 Lisp_Object item = Fmemq (Qnil, w32_grabbed_keys);
7208 /* Safe to add new key to list, even if we have focus. */
7209 if (NILP (item))
7210 w32_grabbed_keys = Fcons (key, w32_grabbed_keys);
7211 else
7212 XSETCAR (item, key);
7214 /* Notify input thread about new hot-key definition, so that it
7215 takes effect without needing to switch focus. */
7216 PostThreadMessage (dwWindowsThreadId, WM_EMACS_REGISTER_HOT_KEY,
7217 (WPARAM) XLI (key), 0);
7220 return key;
7223 DEFUN ("w32-unregister-hot-key", Fw32_unregister_hot_key,
7224 Sw32_unregister_hot_key, 1, 1, 0,
7225 doc: /* Unregister KEY as a hot-key combination. */)
7226 (Lisp_Object key)
7228 Lisp_Object item;
7230 if (!INTEGERP (key))
7231 key = w32_parse_hot_key (key);
7233 item = Fmemq (key, w32_grabbed_keys);
7235 if (!NILP (item))
7237 /* Notify input thread about hot-key definition being removed, so
7238 that it takes effect without needing focus switch. */
7239 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_UNREGISTER_HOT_KEY,
7240 (WPARAM) XINT (XCAR (item)), (LPARAM) XLI (item)))
7242 MSG msg;
7243 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7245 return Qt;
7247 return Qnil;
7250 DEFUN ("w32-registered-hot-keys", Fw32_registered_hot_keys,
7251 Sw32_registered_hot_keys, 0, 0, 0,
7252 doc: /* Return list of registered hot-key IDs. */)
7253 (void)
7255 return Fdelq (Qnil, Fcopy_sequence (w32_grabbed_keys));
7258 DEFUN ("w32-reconstruct-hot-key", Fw32_reconstruct_hot_key,
7259 Sw32_reconstruct_hot_key, 1, 1, 0,
7260 doc: /* Convert hot-key ID to a lisp key combination.
7261 usage: (w32-reconstruct-hot-key ID) */)
7262 (Lisp_Object hotkeyid)
7264 int vk_code, w32_modifiers;
7265 Lisp_Object key;
7267 CHECK_NUMBER (hotkeyid);
7269 vk_code = HOTKEY_VK_CODE (hotkeyid);
7270 w32_modifiers = HOTKEY_MODIFIERS (hotkeyid);
7272 if (vk_code < 256 && lispy_function_keys[vk_code])
7273 key = intern (lispy_function_keys[vk_code]);
7274 else
7275 key = make_number (vk_code);
7277 key = Fcons (key, Qnil);
7278 if (w32_modifiers & MOD_SHIFT)
7279 key = Fcons (Qshift, key);
7280 if (w32_modifiers & MOD_CONTROL)
7281 key = Fcons (Qctrl, key);
7282 if (w32_modifiers & MOD_ALT)
7283 key = Fcons (NILP (Vw32_alt_is_meta) ? Qalt : Qmeta, key);
7284 if (w32_modifiers & MOD_WIN)
7285 key = Fcons (Qhyper, key);
7287 return key;
7290 DEFUN ("w32-toggle-lock-key", Fw32_toggle_lock_key,
7291 Sw32_toggle_lock_key, 1, 2, 0,
7292 doc: /* Toggle the state of the lock key KEY.
7293 KEY can be `capslock', `kp-numlock', or `scroll'.
7294 If the optional parameter NEW-STATE is a number, then the state of KEY
7295 is set to off if the low bit of NEW-STATE is zero, otherwise on. */)
7296 (Lisp_Object key, Lisp_Object new_state)
7298 int vk_code;
7300 if (EQ (key, intern ("capslock")))
7301 vk_code = VK_CAPITAL;
7302 else if (EQ (key, intern ("kp-numlock")))
7303 vk_code = VK_NUMLOCK;
7304 else if (EQ (key, intern ("scroll")))
7305 vk_code = VK_SCROLL;
7306 else
7307 return Qnil;
7309 if (!dwWindowsThreadId)
7310 return make_number (w32_console_toggle_lock_key (vk_code, new_state));
7312 if (PostThreadMessage (dwWindowsThreadId, WM_EMACS_TOGGLE_LOCK_KEY,
7313 (WPARAM) vk_code, (LPARAM) XLI (new_state)))
7315 MSG msg;
7316 GetMessage (&msg, NULL, WM_EMACS_DONE, WM_EMACS_DONE);
7317 return make_number (msg.wParam);
7319 return Qnil;
7322 DEFUN ("w32-window-exists-p", Fw32_window_exists_p, Sw32_window_exists_p,
7323 2, 2, 0,
7324 doc: /* Return non-nil if a window exists with the specified CLASS and NAME.
7326 This is a direct interface to the Windows API FindWindow function. */)
7327 (Lisp_Object class, Lisp_Object name)
7329 HWND hnd;
7331 if (!NILP (class))
7332 CHECK_STRING (class);
7333 if (!NILP (name))
7334 CHECK_STRING (name);
7336 hnd = FindWindow (STRINGP (class) ? ((LPCTSTR) SDATA (class)) : NULL,
7337 STRINGP (name) ? ((LPCTSTR) SDATA (name)) : NULL);
7338 if (!hnd)
7339 return Qnil;
7340 return Qt;
7343 DEFUN ("w32-frame-rect", Fw32_frame_rect, Sw32_frame_rect, 0, 2, 0,
7344 doc: /* Return boundary rectangle of FRAME in screen coordinates.
7345 FRAME must be a live frame and defaults to the selected one.
7347 The boundary rectangle is a list of four elements, specifying the left,
7348 top, right and bottom screen coordinates of FRAME including menu and
7349 title bar and decorations. Optional argument CLIENT non-nil means to
7350 return the boundaries of the client rectangle which excludes menu and
7351 title bar and decorations. */)
7352 (Lisp_Object frame, Lisp_Object client)
7354 struct frame *f = decode_live_frame (frame);
7355 RECT rect;
7357 if (!NILP (client))
7358 GetClientRect (FRAME_W32_WINDOW (f), &rect);
7359 else
7360 GetWindowRect (FRAME_W32_WINDOW (f), &rect);
7362 return list4 (make_number (rect.left), make_number (rect.top),
7363 make_number (rect.right), make_number (rect.bottom));
7366 DEFUN ("w32-battery-status", Fw32_battery_status, Sw32_battery_status, 0, 0, 0,
7367 doc: /* Get power status information from Windows system.
7369 The following %-sequences are provided:
7370 %L AC line status (verbose)
7371 %B Battery status (verbose)
7372 %b Battery status, empty means high, `-' means low,
7373 `!' means critical, and `+' means charging
7374 %p Battery load percentage
7375 %s Remaining time (to charge or discharge) in seconds
7376 %m Remaining time (to charge or discharge) in minutes
7377 %h Remaining time (to charge or discharge) in hours
7378 %t Remaining time (to charge or discharge) in the form `h:min' */)
7379 (void)
7381 Lisp_Object status = Qnil;
7383 SYSTEM_POWER_STATUS system_status;
7384 if (GetSystemPowerStatus (&system_status))
7386 Lisp_Object line_status, battery_status, battery_status_symbol;
7387 Lisp_Object load_percentage, seconds, minutes, hours, remain;
7389 long seconds_left = (long) system_status.BatteryLifeTime;
7391 if (system_status.ACLineStatus == 0)
7392 line_status = build_string ("off-line");
7393 else if (system_status.ACLineStatus == 1)
7394 line_status = build_string ("on-line");
7395 else
7396 line_status = build_string ("N/A");
7398 if (system_status.BatteryFlag & 128)
7400 battery_status = build_string ("N/A");
7401 battery_status_symbol = empty_unibyte_string;
7403 else if (system_status.BatteryFlag & 8)
7405 battery_status = build_string ("charging");
7406 battery_status_symbol = build_string ("+");
7407 if (system_status.BatteryFullLifeTime != -1L)
7408 seconds_left = system_status.BatteryFullLifeTime - seconds_left;
7410 else if (system_status.BatteryFlag & 4)
7412 battery_status = build_string ("critical");
7413 battery_status_symbol = build_string ("!");
7415 else if (system_status.BatteryFlag & 2)
7417 battery_status = build_string ("low");
7418 battery_status_symbol = build_string ("-");
7420 else if (system_status.BatteryFlag & 1)
7422 battery_status = build_string ("high");
7423 battery_status_symbol = empty_unibyte_string;
7425 else
7427 battery_status = build_string ("medium");
7428 battery_status_symbol = empty_unibyte_string;
7431 if (system_status.BatteryLifePercent > 100)
7432 load_percentage = build_string ("N/A");
7433 else
7435 char buffer[16];
7436 snprintf (buffer, 16, "%d", system_status.BatteryLifePercent);
7437 load_percentage = build_string (buffer);
7440 if (seconds_left < 0)
7441 seconds = minutes = hours = remain = build_string ("N/A");
7442 else
7444 long m;
7445 float h;
7446 char buffer[16];
7447 snprintf (buffer, 16, "%ld", seconds_left);
7448 seconds = build_string (buffer);
7450 m = seconds_left / 60;
7451 snprintf (buffer, 16, "%ld", m);
7452 minutes = build_string (buffer);
7454 h = seconds_left / 3600.0;
7455 snprintf (buffer, 16, "%3.1f", h);
7456 hours = build_string (buffer);
7458 snprintf (buffer, 16, "%ld:%02ld", m / 60, m % 60);
7459 remain = build_string (buffer);
7462 status = listn (CONSTYPE_HEAP, 8,
7463 Fcons (make_number ('L'), line_status),
7464 Fcons (make_number ('B'), battery_status),
7465 Fcons (make_number ('b'), battery_status_symbol),
7466 Fcons (make_number ('p'), load_percentage),
7467 Fcons (make_number ('s'), seconds),
7468 Fcons (make_number ('m'), minutes),
7469 Fcons (make_number ('h'), hours),
7470 Fcons (make_number ('t'), remain));
7472 return status;
7476 #ifdef WINDOWSNT
7477 DEFUN ("file-system-info", Ffile_system_info, Sfile_system_info, 1, 1, 0,
7478 doc: /* Return storage information about the file system FILENAME is on.
7479 Value is a list of floats (TOTAL FREE AVAIL), where TOTAL is the total
7480 storage of the file system, FREE is the free storage, and AVAIL is the
7481 storage available to a non-superuser. All 3 numbers are in bytes.
7482 If the underlying system call fails, value is nil. */)
7483 (Lisp_Object filename)
7485 Lisp_Object encoded, value;
7487 CHECK_STRING (filename);
7488 filename = Fexpand_file_name (filename, Qnil);
7489 encoded = ENCODE_FILE (filename);
7491 value = Qnil;
7493 /* Determining the required information on Windows turns out, sadly,
7494 to be more involved than one would hope. The original Windows API
7495 call for this will return bogus information on some systems, but we
7496 must dynamically probe for the replacement api, since that was
7497 added rather late on. */
7499 HMODULE hKernel = GetModuleHandle ("kernel32");
7500 BOOL (WINAPI *pfn_GetDiskFreeSpaceExW)
7501 (wchar_t *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7502 = GetProcAddress (hKernel, "GetDiskFreeSpaceExW");
7503 BOOL (WINAPI *pfn_GetDiskFreeSpaceExA)
7504 (char *, PULARGE_INTEGER, PULARGE_INTEGER, PULARGE_INTEGER)
7505 = GetProcAddress (hKernel, "GetDiskFreeSpaceExA");
7506 bool have_pfn_GetDiskFreeSpaceEx =
7507 ((w32_unicode_filenames && pfn_GetDiskFreeSpaceExW)
7508 || (!w32_unicode_filenames && pfn_GetDiskFreeSpaceExA));
7510 /* On Windows, we may need to specify the root directory of the
7511 volume holding FILENAME. */
7512 char rootname[MAX_UTF8_PATH];
7513 wchar_t rootname_w[MAX_PATH];
7514 char rootname_a[MAX_PATH];
7515 char *name = SDATA (encoded);
7516 BOOL result;
7518 /* find the root name of the volume if given */
7519 if (isalpha (name[0]) && name[1] == ':')
7521 rootname[0] = name[0];
7522 rootname[1] = name[1];
7523 rootname[2] = '\\';
7524 rootname[3] = 0;
7526 else if (IS_DIRECTORY_SEP (name[0]) && IS_DIRECTORY_SEP (name[1]))
7528 char *str = rootname;
7529 int slashes = 4;
7532 if (IS_DIRECTORY_SEP (*name) && --slashes == 0)
7533 break;
7534 *str++ = *name++;
7536 while ( *name );
7538 *str++ = '\\';
7539 *str = 0;
7542 if (w32_unicode_filenames)
7543 filename_to_utf16 (rootname, rootname_w);
7544 else
7545 filename_to_ansi (rootname, rootname_a);
7547 if (have_pfn_GetDiskFreeSpaceEx)
7549 /* Unsigned large integers cannot be cast to double, so
7550 use signed ones instead. */
7551 LARGE_INTEGER availbytes;
7552 LARGE_INTEGER freebytes;
7553 LARGE_INTEGER totalbytes;
7555 if (w32_unicode_filenames)
7556 result = pfn_GetDiskFreeSpaceExW (rootname_w,
7557 (ULARGE_INTEGER *)&availbytes,
7558 (ULARGE_INTEGER *)&totalbytes,
7559 (ULARGE_INTEGER *)&freebytes);
7560 else
7561 result = pfn_GetDiskFreeSpaceExA (rootname_a,
7562 (ULARGE_INTEGER *)&availbytes,
7563 (ULARGE_INTEGER *)&totalbytes,
7564 (ULARGE_INTEGER *)&freebytes);
7565 if (result)
7566 value = list3 (make_float ((double) totalbytes.QuadPart),
7567 make_float ((double) freebytes.QuadPart),
7568 make_float ((double) availbytes.QuadPart));
7570 else
7572 DWORD sectors_per_cluster;
7573 DWORD bytes_per_sector;
7574 DWORD free_clusters;
7575 DWORD total_clusters;
7577 if (w32_unicode_filenames)
7578 result = GetDiskFreeSpaceW (rootname_w,
7579 &sectors_per_cluster,
7580 &bytes_per_sector,
7581 &free_clusters,
7582 &total_clusters);
7583 else
7584 result = GetDiskFreeSpaceA (rootname_a,
7585 &sectors_per_cluster,
7586 &bytes_per_sector,
7587 &free_clusters,
7588 &total_clusters);
7589 if (result)
7590 value = list3 (make_float ((double) total_clusters
7591 * sectors_per_cluster * bytes_per_sector),
7592 make_float ((double) free_clusters
7593 * sectors_per_cluster * bytes_per_sector),
7594 make_float ((double) free_clusters
7595 * sectors_per_cluster * bytes_per_sector));
7599 return value;
7601 #endif /* WINDOWSNT */
7604 #ifdef WINDOWSNT
7605 DEFUN ("default-printer-name", Fdefault_printer_name, Sdefault_printer_name,
7606 0, 0, 0, doc: /* Return the name of Windows default printer device. */)
7607 (void)
7609 static char pname_buf[256];
7610 int err;
7611 HANDLE hPrn;
7612 PRINTER_INFO_2W *ppi2w = NULL;
7613 PRINTER_INFO_2A *ppi2a = NULL;
7614 DWORD dwNeeded = 0, dwReturned = 0;
7615 char server_name[MAX_UTF8_PATH], share_name[MAX_UTF8_PATH];
7616 char port_name[MAX_UTF8_PATH];
7618 /* Retrieve the default string from Win.ini (the registry).
7619 * String will be in form "printername,drivername,portname".
7620 * This is the most portable way to get the default printer. */
7621 if (GetProfileString ("windows", "device", ",,", pname_buf, sizeof (pname_buf)) <= 0)
7622 return Qnil;
7623 /* printername precedes first "," character */
7624 strtok (pname_buf, ",");
7625 /* We want to know more than the printer name */
7626 if (!OpenPrinter (pname_buf, &hPrn, NULL))
7627 return Qnil;
7628 /* GetPrinterW is not supported by unicows.dll. */
7629 if (w32_unicode_filenames && os_subtype != OS_9X)
7630 GetPrinterW (hPrn, 2, NULL, 0, &dwNeeded);
7631 else
7632 GetPrinterA (hPrn, 2, NULL, 0, &dwNeeded);
7633 if (dwNeeded == 0)
7635 ClosePrinter (hPrn);
7636 return Qnil;
7638 /* Call GetPrinter again with big enough memory block. */
7639 if (w32_unicode_filenames && os_subtype != OS_9X)
7641 /* Allocate memory for the PRINTER_INFO_2 struct. */
7642 ppi2w = xmalloc (dwNeeded);
7643 err = GetPrinterW (hPrn, 2, (LPBYTE)ppi2w, dwNeeded, &dwReturned);
7644 ClosePrinter (hPrn);
7645 if (!err)
7647 xfree (ppi2w);
7648 return Qnil;
7651 if ((ppi2w->Attributes & PRINTER_ATTRIBUTE_SHARED)
7652 && ppi2w->pServerName)
7654 filename_from_utf16 (ppi2w->pServerName, server_name);
7655 filename_from_utf16 (ppi2w->pShareName, share_name);
7657 else
7659 server_name[0] = '\0';
7660 filename_from_utf16 (ppi2w->pPortName, port_name);
7663 else
7665 ppi2a = xmalloc (dwNeeded);
7666 err = GetPrinterA (hPrn, 2, (LPBYTE)ppi2a, dwNeeded, &dwReturned);
7667 ClosePrinter (hPrn);
7668 if (!err)
7670 xfree (ppi2a);
7671 return Qnil;
7674 if ((ppi2a->Attributes & PRINTER_ATTRIBUTE_SHARED)
7675 && ppi2a->pServerName)
7677 filename_from_ansi (ppi2a->pServerName, server_name);
7678 filename_from_ansi (ppi2a->pShareName, share_name);
7680 else
7682 server_name[0] = '\0';
7683 filename_from_ansi (ppi2a->pPortName, port_name);
7687 if (server_name[0])
7689 /* a remote printer */
7690 if (server_name[0] == '\\')
7691 snprintf (pname_buf, sizeof (pname_buf), "%s\\%s", server_name,
7692 share_name);
7693 else
7694 snprintf (pname_buf, sizeof (pname_buf), "\\\\%s\\%s", server_name,
7695 share_name);
7696 pname_buf[sizeof (pname_buf) - 1] = '\0';
7698 else
7700 /* a local printer */
7701 strncpy (pname_buf, port_name, sizeof (pname_buf));
7702 pname_buf[sizeof (pname_buf) - 1] = '\0';
7703 /* `pPortName' can include several ports, delimited by ','.
7704 * we only use the first one. */
7705 strtok (pname_buf, ",");
7708 return DECODE_FILE (build_unibyte_string (pname_buf));
7710 #endif /* WINDOWSNT */
7713 /* Equivalent of strerror for W32 error codes. */
7714 char *
7715 w32_strerror (int error_no)
7717 static char buf[500];
7718 DWORD ret;
7720 if (error_no == 0)
7721 error_no = GetLastError ();
7723 ret = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM |
7724 FORMAT_MESSAGE_IGNORE_INSERTS,
7725 NULL,
7726 error_no,
7727 0, /* choose most suitable language */
7728 buf, sizeof (buf), NULL);
7730 while (ret > 0 && (buf[ret - 1] == '\n' ||
7731 buf[ret - 1] == '\r' ))
7732 --ret;
7733 buf[ret] = '\0';
7734 if (!ret)
7735 sprintf (buf, "w32 error %u", error_no);
7737 return buf;
7740 /* For convenience when debugging. (You cannot call GetLastError
7741 directly from GDB: it will crash, because it uses the __stdcall
7742 calling convention, not the _cdecl convention assumed by GDB.) */
7743 DWORD
7744 w32_last_error (void)
7746 return GetLastError ();
7749 /* Cache information describing the NT system for later use. */
7750 void
7751 cache_system_info (void)
7753 union
7755 struct info
7757 char major;
7758 char minor;
7759 short platform;
7760 } info;
7761 DWORD data;
7762 } version;
7764 /* Cache the module handle of Emacs itself. */
7765 hinst = GetModuleHandle (NULL);
7767 /* Cache the version of the operating system. */
7768 version.data = GetVersion ();
7769 w32_major_version = version.info.major;
7770 w32_minor_version = version.info.minor;
7772 if (version.info.platform & 0x8000)
7773 os_subtype = OS_9X;
7774 else
7775 os_subtype = OS_NT;
7777 /* Cache page size, allocation unit, processor type, etc. */
7778 GetSystemInfo (&sysinfo_cache);
7779 syspage_mask = (DWORD_PTR)sysinfo_cache.dwPageSize - 1;
7781 /* Cache os info. */
7782 osinfo_cache.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
7783 GetVersionEx (&osinfo_cache);
7785 w32_build_number = osinfo_cache.dwBuildNumber;
7786 if (os_subtype == OS_9X)
7787 w32_build_number &= 0xffff;
7789 w32_num_mouse_buttons = GetSystemMetrics (SM_CMOUSEBUTTONS);
7792 #ifdef EMACSDEBUG
7793 void
7794 _DebPrint (const char *fmt, ...)
7796 char buf[1024];
7797 va_list args;
7799 va_start (args, fmt);
7800 vsprintf (buf, fmt, args);
7801 va_end (args);
7802 #if CYGWIN
7803 fprintf (stderr, "%s", buf);
7804 #endif
7805 OutputDebugString (buf);
7807 #endif
7810 w32_console_toggle_lock_key (int vk_code, Lisp_Object new_state)
7812 int cur_state = (GetKeyState (vk_code) & 1);
7814 if (NILP (new_state)
7815 || (NUMBERP (new_state)
7816 && ((XUINT (new_state)) & 1) != cur_state))
7818 #ifdef WINDOWSNT
7819 faked_key = vk_code;
7820 #endif /* WINDOWSNT */
7822 keybd_event ((BYTE) vk_code,
7823 (BYTE) MapVirtualKey (vk_code, 0),
7824 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7825 keybd_event ((BYTE) vk_code,
7826 (BYTE) MapVirtualKey (vk_code, 0),
7827 KEYEVENTF_EXTENDEDKEY | 0, 0);
7828 keybd_event ((BYTE) vk_code,
7829 (BYTE) MapVirtualKey (vk_code, 0),
7830 KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
7831 cur_state = !cur_state;
7834 return cur_state;
7837 /* Translate console modifiers to emacs modifiers.
7838 German keyboard support (Kai Morgan Zeise 2/18/95). */
7840 w32_kbd_mods_to_emacs (DWORD mods, WORD key)
7842 int retval = 0;
7844 /* If we recognize right-alt and left-ctrl as AltGr, and it has been
7845 pressed, first remove those modifiers. */
7846 if (!NILP (Vw32_recognize_altgr)
7847 && (mods & (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7848 == (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED))
7849 mods &= ~ (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED);
7851 if (mods & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
7852 retval = ((NILP (Vw32_alt_is_meta)) ? alt_modifier : meta_modifier);
7854 if (mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7856 retval |= ctrl_modifier;
7857 if ((mods & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7858 == (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
7859 retval |= meta_modifier;
7862 if (mods & LEFT_WIN_PRESSED)
7863 retval |= w32_key_to_modifier (VK_LWIN);
7864 if (mods & RIGHT_WIN_PRESSED)
7865 retval |= w32_key_to_modifier (VK_RWIN);
7866 if (mods & APPS_PRESSED)
7867 retval |= w32_key_to_modifier (VK_APPS);
7868 if (mods & SCROLLLOCK_ON)
7869 retval |= w32_key_to_modifier (VK_SCROLL);
7871 /* Just in case someone wanted the original behavior, make it
7872 optional by setting w32-capslock-is-shiftlock to t. */
7873 if (NILP (Vw32_capslock_is_shiftlock)
7874 /* Keys that should _not_ be affected by CapsLock. */
7875 && ( (key == VK_BACK)
7876 || (key == VK_TAB)
7877 || (key == VK_CLEAR)
7878 || (key == VK_RETURN)
7879 || (key == VK_ESCAPE)
7880 || ((key >= VK_SPACE) && (key <= VK_HELP))
7881 || ((key >= VK_NUMPAD0) && (key <= VK_F24))
7882 || ((key >= VK_NUMPAD_CLEAR) && (key <= VK_NUMPAD_DELETE))
7885 /* Only consider shift state. */
7886 if ((mods & SHIFT_PRESSED) != 0)
7887 retval |= shift_modifier;
7889 else
7891 /* Ignore CapsLock state if not enabled. */
7892 if (NILP (Vw32_enable_caps_lock))
7893 mods &= ~CAPSLOCK_ON;
7894 if ((mods & (SHIFT_PRESSED | CAPSLOCK_ON)) != 0)
7895 retval |= shift_modifier;
7898 return retval;
7901 /* The return code indicates key code size. cpID is the codepage to
7902 use for translation to Unicode; -1 means use the current console
7903 input codepage. */
7905 w32_kbd_patch_key (KEY_EVENT_RECORD *event, int cpId)
7907 unsigned int key_code = event->wVirtualKeyCode;
7908 unsigned int mods = event->dwControlKeyState;
7909 BYTE keystate[256];
7910 static BYTE ansi_code[4];
7911 static int isdead = 0;
7913 if (isdead == 2)
7915 event->uChar.AsciiChar = ansi_code[2];
7916 isdead = 0;
7917 return 1;
7919 if (event->uChar.AsciiChar != 0)
7920 return 1;
7922 memset (keystate, 0, sizeof (keystate));
7923 keystate[key_code] = 0x80;
7924 if (mods & SHIFT_PRESSED)
7925 keystate[VK_SHIFT] = 0x80;
7926 if (mods & CAPSLOCK_ON)
7927 keystate[VK_CAPITAL] = 1;
7928 /* If we recognize right-alt and left-ctrl as AltGr, set the key
7929 states accordingly before invoking ToAscii. */
7930 if (!NILP (Vw32_recognize_altgr)
7931 && (mods & LEFT_CTRL_PRESSED) && (mods & RIGHT_ALT_PRESSED))
7933 keystate[VK_CONTROL] = 0x80;
7934 keystate[VK_LCONTROL] = 0x80;
7935 keystate[VK_MENU] = 0x80;
7936 keystate[VK_RMENU] = 0x80;
7939 #if 0
7940 /* Because of an OS bug, ToAscii corrupts the stack when called to
7941 convert a dead key in console mode on NT4. Unfortunately, trying
7942 to check for dead keys using MapVirtualKey doesn't work either -
7943 these functions apparently use internal information about keyboard
7944 layout which doesn't get properly updated in console programs when
7945 changing layout (though apparently it gets partly updated,
7946 otherwise ToAscii wouldn't crash). */
7947 if (is_dead_key (event->wVirtualKeyCode))
7948 return 0;
7949 #endif
7951 /* On NT, call ToUnicode instead and then convert to the current
7952 console input codepage. */
7953 if (os_subtype == OS_NT)
7955 WCHAR buf[128];
7957 isdead = ToUnicode (event->wVirtualKeyCode, event->wVirtualScanCode,
7958 keystate, buf, 128, 0);
7959 if (isdead > 0)
7961 /* When we are called from the GUI message processing code,
7962 we are passed the current keyboard codepage, a positive
7963 number, to use below. */
7964 if (cpId == -1)
7965 cpId = GetConsoleCP ();
7967 event->uChar.UnicodeChar = buf[isdead - 1];
7968 isdead = WideCharToMultiByte (cpId, 0, buf, isdead,
7969 ansi_code, 4, NULL, NULL);
7971 else
7972 isdead = 0;
7974 else
7976 isdead = ToAscii (event->wVirtualKeyCode, event->wVirtualScanCode,
7977 keystate, (LPWORD) ansi_code, 0);
7980 if (isdead == 0)
7981 return 0;
7982 event->uChar.AsciiChar = ansi_code[0];
7983 return isdead;
7987 void
7988 w32_sys_ring_bell (struct frame *f)
7990 if (sound_type == 0xFFFFFFFF)
7992 Beep (666, 100);
7994 else if (sound_type == MB_EMACS_SILENT)
7996 /* Do nothing. */
7998 else
7999 MessageBeep (sound_type);
8003 /***********************************************************************
8004 Initialization
8005 ***********************************************************************/
8007 /* Keep this list in the same order as frame_parms in frame.c.
8008 Use 0 for unsupported frame parameters. */
8010 frame_parm_handler w32_frame_parm_handlers[] =
8012 x_set_autoraise,
8013 x_set_autolower,
8014 x_set_background_color,
8015 x_set_border_color,
8016 x_set_border_width,
8017 x_set_cursor_color,
8018 x_set_cursor_type,
8019 x_set_font,
8020 x_set_foreground_color,
8021 x_set_icon_name,
8022 x_set_icon_type,
8023 x_set_internal_border_width,
8024 x_set_right_divider_width,
8025 x_set_bottom_divider_width,
8026 x_set_menu_bar_lines,
8027 x_set_mouse_color,
8028 x_explicitly_set_name,
8029 x_set_scroll_bar_width,
8030 x_set_title,
8031 x_set_unsplittable,
8032 x_set_vertical_scroll_bars,
8033 x_set_visibility,
8034 x_set_tool_bar_lines,
8035 0, /* x_set_scroll_bar_foreground, */
8036 0, /* x_set_scroll_bar_background, */
8037 x_set_screen_gamma,
8038 x_set_line_spacing,
8039 x_set_fringe_width,
8040 x_set_fringe_width,
8041 0, /* x_set_wait_for_wm, */
8042 x_set_fullscreen,
8043 x_set_font_backend,
8044 x_set_alpha,
8045 0, /* x_set_sticky */
8046 0, /* x_set_tool_bar_position */
8049 void
8050 syms_of_w32fns (void)
8052 globals_of_w32fns ();
8053 track_mouse_window = NULL;
8055 w32_visible_system_caret_hwnd = NULL;
8057 DEFSYM (Qundefined_color, "undefined-color");
8058 DEFSYM (Qcancel_timer, "cancel-timer");
8059 DEFSYM (Qhyper, "hyper");
8060 DEFSYM (Qsuper, "super");
8061 DEFSYM (Qmeta, "meta");
8062 DEFSYM (Qalt, "alt");
8063 DEFSYM (Qctrl, "ctrl");
8064 DEFSYM (Qcontrol, "control");
8065 DEFSYM (Qshift, "shift");
8066 DEFSYM (Qfont_param, "font-parameter");
8067 DEFSYM (Qgeometry, "geometry");
8068 DEFSYM (Qworkarea, "workarea");
8069 DEFSYM (Qmm_size, "mm-size");
8070 DEFSYM (Qframes, "frames");
8072 Fput (Qundefined_color, Qerror_conditions,
8073 listn (CONSTYPE_PURE, 2, Qundefined_color, Qerror));
8074 Fput (Qundefined_color, Qerror_message,
8075 build_pure_c_string ("Undefined color"));
8077 staticpro (&w32_grabbed_keys);
8078 w32_grabbed_keys = Qnil;
8080 DEFVAR_LISP ("w32-color-map", Vw32_color_map,
8081 doc: /* An array of color name mappings for Windows. */);
8082 Vw32_color_map = Qnil;
8084 DEFVAR_LISP ("w32-pass-alt-to-system", Vw32_pass_alt_to_system,
8085 doc: /* Non-nil if Alt key presses are passed on to Windows.
8086 When non-nil, for example, Alt pressed and released and then space will
8087 open the System menu. When nil, Emacs processes the Alt key events, and
8088 then silently swallows them. */);
8089 Vw32_pass_alt_to_system = Qnil;
8091 DEFVAR_LISP ("w32-alt-is-meta", Vw32_alt_is_meta,
8092 doc: /* Non-nil if the Alt key is to be considered the same as the META key.
8093 When nil, Emacs will translate the Alt key to the ALT modifier, not to META. */);
8094 Vw32_alt_is_meta = Qt;
8096 DEFVAR_INT ("w32-quit-key", w32_quit_key,
8097 doc: /* If non-zero, the virtual key code for an alternative quit key. */);
8098 w32_quit_key = 0;
8100 DEFVAR_LISP ("w32-pass-lwindow-to-system",
8101 Vw32_pass_lwindow_to_system,
8102 doc: /* If non-nil, the left \"Windows\" key is passed on to Windows.
8104 When non-nil, the Start menu is opened by tapping the key.
8105 If you set this to nil, the left \"Windows\" key is processed by Emacs
8106 according to the value of `w32-lwindow-modifier', which see.
8108 Note that some combinations of the left \"Windows\" key with other keys are
8109 caught by Windows at low level, and so binding them in Emacs will have no
8110 effect. For example, <lwindow>-r always pops up the Windows Run dialog,
8111 <lwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8112 the doc string of `w32-phantom-key-code'. */);
8113 Vw32_pass_lwindow_to_system = Qt;
8115 DEFVAR_LISP ("w32-pass-rwindow-to-system",
8116 Vw32_pass_rwindow_to_system,
8117 doc: /* If non-nil, the right \"Windows\" key is passed on to Windows.
8119 When non-nil, the Start menu is opened by tapping the key.
8120 If you set this to nil, the right \"Windows\" key is processed by Emacs
8121 according to the value of `w32-rwindow-modifier', which see.
8123 Note that some combinations of the right \"Windows\" key with other keys are
8124 caught by Windows at low level, and so binding them in Emacs will have no
8125 effect. For example, <rwindow>-r always pops up the Windows Run dialog,
8126 <rwindow>-<Pause> pops up the "System Properties" dialog, etc. However, see
8127 the doc string of `w32-phantom-key-code'. */);
8128 Vw32_pass_rwindow_to_system = Qt;
8130 DEFVAR_LISP ("w32-phantom-key-code",
8131 Vw32_phantom_key_code,
8132 doc: /* Virtual key code used to generate \"phantom\" key presses.
8133 Value is a number between 0 and 255.
8135 Phantom key presses are generated in order to stop the system from
8136 acting on \"Windows\" key events when `w32-pass-lwindow-to-system' or
8137 `w32-pass-rwindow-to-system' is nil. */);
8138 /* Although 255 is technically not a valid key code, it works and
8139 means that this hack won't interfere with any real key code. */
8140 XSETINT (Vw32_phantom_key_code, 255);
8142 DEFVAR_LISP ("w32-enable-num-lock",
8143 Vw32_enable_num_lock,
8144 doc: /* If non-nil, the Num Lock key acts normally.
8145 Set to nil to handle Num Lock as the `kp-numlock' key. */);
8146 Vw32_enable_num_lock = Qt;
8148 DEFVAR_LISP ("w32-enable-caps-lock",
8149 Vw32_enable_caps_lock,
8150 doc: /* If non-nil, the Caps Lock key acts normally.
8151 Set to nil to handle Caps Lock as the `capslock' key. */);
8152 Vw32_enable_caps_lock = Qt;
8154 DEFVAR_LISP ("w32-scroll-lock-modifier",
8155 Vw32_scroll_lock_modifier,
8156 doc: /* Modifier to use for the Scroll Lock ON state.
8157 The value can be hyper, super, meta, alt, control or shift for the
8158 respective modifier, or nil to handle Scroll Lock as the `scroll' key.
8159 Any other value will cause the Scroll Lock key to be ignored. */);
8160 Vw32_scroll_lock_modifier = Qnil;
8162 DEFVAR_LISP ("w32-lwindow-modifier",
8163 Vw32_lwindow_modifier,
8164 doc: /* Modifier to use for the left \"Windows\" key.
8165 The value can be hyper, super, meta, alt, control or shift for the
8166 respective modifier, or nil to appear as the `lwindow' key.
8167 Any other value will cause the key to be ignored. */);
8168 Vw32_lwindow_modifier = Qnil;
8170 DEFVAR_LISP ("w32-rwindow-modifier",
8171 Vw32_rwindow_modifier,
8172 doc: /* Modifier to use for the right \"Windows\" key.
8173 The value can be hyper, super, meta, alt, control or shift for the
8174 respective modifier, or nil to appear as the `rwindow' key.
8175 Any other value will cause the key to be ignored. */);
8176 Vw32_rwindow_modifier = Qnil;
8178 DEFVAR_LISP ("w32-apps-modifier",
8179 Vw32_apps_modifier,
8180 doc: /* Modifier to use for the \"Apps\" key.
8181 The value can be hyper, super, meta, alt, control or shift for the
8182 respective modifier, or nil to appear as the `apps' key.
8183 Any other value will cause the key to be ignored. */);
8184 Vw32_apps_modifier = Qnil;
8186 DEFVAR_BOOL ("w32-enable-synthesized-fonts", w32_enable_synthesized_fonts,
8187 doc: /* Non-nil enables selection of artificially italicized and bold fonts. */);
8188 w32_enable_synthesized_fonts = 0;
8190 DEFVAR_LISP ("w32-enable-palette", Vw32_enable_palette,
8191 doc: /* Non-nil enables Windows palette management to map colors exactly. */);
8192 Vw32_enable_palette = Qt;
8194 DEFVAR_INT ("w32-mouse-button-tolerance",
8195 w32_mouse_button_tolerance,
8196 doc: /* Analogue of double click interval for faking middle mouse events.
8197 The value is the minimum time in milliseconds that must elapse between
8198 left and right button down events before they are considered distinct events.
8199 If both mouse buttons are depressed within this interval, a middle mouse
8200 button down event is generated instead. */);
8201 w32_mouse_button_tolerance = GetDoubleClickTime () / 2;
8203 DEFVAR_INT ("w32-mouse-move-interval",
8204 w32_mouse_move_interval,
8205 doc: /* Minimum interval between mouse move events.
8206 The value is the minimum time in milliseconds that must elapse between
8207 successive mouse move (or scroll bar drag) events before they are
8208 reported as lisp events. */);
8209 w32_mouse_move_interval = 0;
8211 DEFVAR_BOOL ("w32-pass-extra-mouse-buttons-to-system",
8212 w32_pass_extra_mouse_buttons_to_system,
8213 doc: /* If non-nil, the fourth and fifth mouse buttons are passed to Windows.
8214 Recent versions of Windows support mice with up to five buttons.
8215 Since most applications don't support these extra buttons, most mouse
8216 drivers will allow you to map them to functions at the system level.
8217 If this variable is non-nil, Emacs will pass them on, allowing the
8218 system to handle them. */);
8219 w32_pass_extra_mouse_buttons_to_system = 0;
8221 DEFVAR_BOOL ("w32-pass-multimedia-buttons-to-system",
8222 w32_pass_multimedia_buttons_to_system,
8223 doc: /* If non-nil, media buttons are passed to Windows.
8224 Some modern keyboards contain buttons for controlling media players, web
8225 browsers and other applications. Generally these buttons are handled on a
8226 system wide basis, but by setting this to nil they are made available
8227 to Emacs for binding. Depending on your keyboard, additional keys that
8228 may be available are:
8230 browser-back, browser-forward, browser-refresh, browser-stop,
8231 browser-search, browser-favorites, browser-home,
8232 mail, mail-reply, mail-forward, mail-send,
8233 app-1, app-2,
8234 help, find, new, open, close, save, print, undo, redo, copy, cut, paste,
8235 spell-check, correction-list, toggle-dictate-command,
8236 media-next, media-previous, media-stop, media-play-pause, media-select,
8237 media-play, media-pause, media-record, media-fast-forward, media-rewind,
8238 media-channel-up, media-channel-down,
8239 volume-mute, volume-up, volume-down,
8240 mic-volume-mute, mic-volume-down, mic-volume-up, mic-toggle,
8241 bass-down, bass-boost, bass-up, treble-down, treble-up */);
8242 w32_pass_multimedia_buttons_to_system = 1;
8244 #if 0 /* TODO: Mouse cursor customization. */
8245 DEFVAR_LISP ("x-pointer-shape", Vx_pointer_shape,
8246 doc: /* The shape of the pointer when over text.
8247 Changing the value does not affect existing frames
8248 unless you set the mouse color. */);
8249 Vx_pointer_shape = Qnil;
8251 Vx_nontext_pointer_shape = Qnil;
8253 Vx_mode_pointer_shape = Qnil;
8255 DEFVAR_LISP ("x-hourglass-pointer-shape", Vx_hourglass_pointer_shape,
8256 doc: /* The shape of the pointer when Emacs is busy.
8257 This variable takes effect when you create a new frame
8258 or when you set the mouse color. */);
8259 Vx_hourglass_pointer_shape = Qnil;
8261 DEFVAR_LISP ("x-sensitive-text-pointer-shape",
8262 Vx_sensitive_text_pointer_shape,
8263 doc: /* The shape of the pointer when over mouse-sensitive text.
8264 This variable takes effect when you create a new frame
8265 or when you set the mouse color. */);
8266 Vx_sensitive_text_pointer_shape = Qnil;
8268 DEFVAR_LISP ("x-window-horizontal-drag-cursor",
8269 Vx_window_horizontal_drag_shape,
8270 doc: /* Pointer shape to use for indicating a window can be dragged horizontally.
8271 This variable takes effect when you create a new frame
8272 or when you set the mouse color. */);
8273 Vx_window_horizontal_drag_shape = Qnil;
8275 DEFVAR_LISP ("x-window-vertical-drag-cursor",
8276 Vx_window_vertical_drag_shape,
8277 doc: /* Pointer shape to use for indicating a window can be dragged vertically.
8278 This variable takes effect when you create a new frame
8279 or when you set the mouse color. */);
8280 Vx_window_vertical_drag_shape = Qnil;
8281 #endif
8283 DEFVAR_LISP ("x-cursor-fore-pixel", Vx_cursor_fore_pixel,
8284 doc: /* A string indicating the foreground color of the cursor box. */);
8285 Vx_cursor_fore_pixel = Qnil;
8287 DEFVAR_LISP ("x-max-tooltip-size", Vx_max_tooltip_size,
8288 doc: /* Maximum size for tooltips.
8289 Value is a pair (COLUMNS . ROWS). Text larger than this is clipped. */);
8290 Vx_max_tooltip_size = Fcons (make_number (80), make_number (40));
8292 DEFVAR_LISP ("x-no-window-manager", Vx_no_window_manager,
8293 doc: /* Non-nil if no window manager is in use.
8294 Emacs doesn't try to figure this out; this is always nil
8295 unless you set it to something else. */);
8296 /* We don't have any way to find this out, so set it to nil
8297 and maybe the user would like to set it to t. */
8298 Vx_no_window_manager = Qnil;
8300 DEFVAR_LISP ("x-pixel-size-width-font-regexp",
8301 Vx_pixel_size_width_font_regexp,
8302 doc: /* Regexp matching a font name whose width is the same as `PIXEL_SIZE'.
8304 Since Emacs gets width of a font matching with this regexp from
8305 PIXEL_SIZE field of the name, font finding mechanism gets faster for
8306 such a font. This is especially effective for such large fonts as
8307 Chinese, Japanese, and Korean. */);
8308 Vx_pixel_size_width_font_regexp = Qnil;
8310 DEFVAR_LISP ("w32-bdf-filename-alist",
8311 Vw32_bdf_filename_alist,
8312 doc: /* List of bdf fonts and their corresponding filenames. */);
8313 Vw32_bdf_filename_alist = Qnil;
8315 DEFVAR_BOOL ("w32-strict-fontnames",
8316 w32_strict_fontnames,
8317 doc: /* Non-nil means only use fonts that are exact matches for those requested.
8318 Default is nil, which allows old fontnames that are not XLFD compliant,
8319 and allows third-party CJK display to work by specifying false charset
8320 fields to trick Emacs into translating to Big5, SJIS etc.
8321 Setting this to t will prevent wrong fonts being selected when
8322 fontsets are automatically created. */);
8323 w32_strict_fontnames = 0;
8325 DEFVAR_BOOL ("w32-strict-painting",
8326 w32_strict_painting,
8327 doc: /* Non-nil means use strict rules for repainting frames.
8328 Set this to nil to get the old behavior for repainting; this should
8329 only be necessary if the default setting causes problems. */);
8330 w32_strict_painting = 1;
8332 #if 0 /* TODO: Port to W32 */
8333 defsubr (&Sx_change_window_property);
8334 defsubr (&Sx_delete_window_property);
8335 defsubr (&Sx_window_property);
8336 #endif
8337 defsubr (&Sxw_display_color_p);
8338 defsubr (&Sx_display_grayscale_p);
8339 defsubr (&Sxw_color_defined_p);
8340 defsubr (&Sxw_color_values);
8341 defsubr (&Sx_server_max_request_size);
8342 defsubr (&Sx_server_vendor);
8343 defsubr (&Sx_server_version);
8344 defsubr (&Sx_display_pixel_width);
8345 defsubr (&Sx_display_pixel_height);
8346 defsubr (&Sx_display_mm_width);
8347 defsubr (&Sx_display_mm_height);
8348 defsubr (&Sx_display_screens);
8349 defsubr (&Sx_display_planes);
8350 defsubr (&Sx_display_color_cells);
8351 defsubr (&Sx_display_visual_class);
8352 defsubr (&Sx_display_backing_store);
8353 defsubr (&Sx_display_save_under);
8354 defsubr (&Sx_create_frame);
8355 defsubr (&Sx_open_connection);
8356 defsubr (&Sx_close_connection);
8357 defsubr (&Sx_display_list);
8358 defsubr (&Sx_synchronize);
8360 /* W32 specific functions */
8362 defsubr (&Sw32_define_rgb_color);
8363 defsubr (&Sw32_default_color_map);
8364 defsubr (&Sw32_display_monitor_attributes_list);
8365 defsubr (&Sw32_send_sys_command);
8366 defsubr (&Sw32_shell_execute);
8367 defsubr (&Sw32_register_hot_key);
8368 defsubr (&Sw32_unregister_hot_key);
8369 defsubr (&Sw32_registered_hot_keys);
8370 defsubr (&Sw32_reconstruct_hot_key);
8371 defsubr (&Sw32_toggle_lock_key);
8372 defsubr (&Sw32_window_exists_p);
8373 defsubr (&Sw32_frame_rect);
8374 defsubr (&Sw32_battery_status);
8376 #ifdef WINDOWSNT
8377 defsubr (&Sfile_system_info);
8378 defsubr (&Sdefault_printer_name);
8379 #endif
8381 defsubr (&Sset_message_beep);
8382 defsubr (&Sx_show_tip);
8383 defsubr (&Sx_hide_tip);
8384 tip_timer = Qnil;
8385 staticpro (&tip_timer);
8386 tip_frame = Qnil;
8387 staticpro (&tip_frame);
8389 last_show_tip_args = Qnil;
8390 staticpro (&last_show_tip_args);
8392 defsubr (&Sx_file_dialog);
8393 #ifdef WINDOWSNT
8394 defsubr (&Ssystem_move_file_to_trash);
8395 #endif
8400 /* Crashing and reporting backtrace. */
8402 #ifndef CYGWIN
8403 static LONG CALLBACK my_exception_handler (EXCEPTION_POINTERS *);
8404 static LPTOP_LEVEL_EXCEPTION_FILTER prev_exception_handler;
8405 #endif
8406 static DWORD except_code;
8407 static PVOID except_addr;
8409 #ifndef CYGWIN
8410 /* This handler records the exception code and the address where it
8411 was triggered so that this info could be included in the backtrace.
8412 Without that, the backtrace in some cases has no information
8413 whatsoever about the offending code, and looks as if the top-level
8414 exception handler in the MinGW startup code di the one that
8415 crashed. */
8416 static LONG CALLBACK
8417 my_exception_handler (EXCEPTION_POINTERS * exception_data)
8419 except_code = exception_data->ExceptionRecord->ExceptionCode;
8420 except_addr = exception_data->ExceptionRecord->ExceptionAddress;
8422 if (prev_exception_handler)
8423 return prev_exception_handler (exception_data);
8424 return EXCEPTION_EXECUTE_HANDLER;
8426 #endif
8428 typedef USHORT (WINAPI * CaptureStackBackTrace_proc) (ULONG, ULONG, PVOID *,
8429 PULONG);
8431 #define BACKTRACE_LIMIT_MAX 62
8434 w32_backtrace (void **buffer, int limit)
8436 static CaptureStackBackTrace_proc s_pfn_CaptureStackBackTrace = NULL;
8437 HMODULE hm_kernel32 = NULL;
8439 if (!s_pfn_CaptureStackBackTrace)
8441 hm_kernel32 = LoadLibrary ("Kernel32.dll");
8442 s_pfn_CaptureStackBackTrace =
8443 (CaptureStackBackTrace_proc) GetProcAddress (hm_kernel32,
8444 "RtlCaptureStackBackTrace");
8446 if (s_pfn_CaptureStackBackTrace)
8447 return s_pfn_CaptureStackBackTrace (0, min (BACKTRACE_LIMIT_MAX, limit),
8448 buffer, NULL);
8449 return 0;
8452 void
8453 emacs_abort (void)
8455 int button;
8456 button = MessageBox (NULL,
8457 "A fatal error has occurred!\n\n"
8458 "Would you like to attach a debugger?\n\n"
8459 "Select:\n"
8460 "YES -- to debug Emacs, or\n"
8461 "NO -- to abort Emacs and produce a backtrace\n"
8462 " (emacs_backtrace.txt in current directory)."
8463 #if __GNUC__
8464 "\n\n(type \"gdb -p <emacs-PID>\" and\n"
8465 "\"continue\" inside GDB before clicking YES.)"
8466 #endif
8467 , "Emacs Abort Dialog",
8468 MB_ICONEXCLAMATION | MB_TASKMODAL
8469 | MB_SETFOREGROUND | MB_YESNO);
8470 switch (button)
8472 case IDYES:
8473 DebugBreak ();
8474 exit (2); /* tell the compiler we will never return */
8475 case IDNO:
8476 default:
8478 void *stack[BACKTRACE_LIMIT_MAX + 1];
8479 int i = w32_backtrace (stack, BACKTRACE_LIMIT_MAX + 1);
8481 if (i)
8483 int errfile_fd = -1;
8484 int j;
8485 char buf[sizeof ("\r\nException at this address:\r\n\r\n")
8486 /* The type below should really be 'void *', but
8487 INT_BUFSIZE_BOUND cannot handle that without
8488 triggering compiler warnings (under certain
8489 pedantic warning switches), it wants an
8490 integer type. */
8491 + 2 * INT_BUFSIZE_BOUND (intptr_t)];
8492 #ifdef CYGWIN
8493 int stderr_fd = 2;
8494 #else
8495 HANDLE errout = GetStdHandle (STD_ERROR_HANDLE);
8496 int stderr_fd = -1;
8498 if (errout && errout != INVALID_HANDLE_VALUE)
8499 stderr_fd = _open_osfhandle ((intptr_t)errout, O_APPEND | O_BINARY);
8500 #endif
8502 /* We use %p, not 0x%p, as %p produces a leading "0x" on XP,
8503 but not on Windows 7. addr2line doesn't mind a missing
8504 "0x", but will be confused by an extra one. */
8505 if (except_addr)
8506 sprintf (buf, "\r\nException 0x%lx at this address:\r\n%p\r\n",
8507 except_code, except_addr);
8508 if (stderr_fd >= 0)
8510 if (except_addr)
8511 write (stderr_fd, buf, strlen (buf));
8512 write (stderr_fd, "\r\nBacktrace:\r\n", 14);
8514 #ifdef CYGWIN
8515 #define _open open
8516 #endif
8517 errfile_fd = _open ("emacs_backtrace.txt", O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);
8518 if (errfile_fd >= 0)
8520 lseek (errfile_fd, 0L, SEEK_END);
8521 if (except_addr)
8522 write (errfile_fd, buf, strlen (buf));
8523 write (errfile_fd, "\r\nBacktrace:\r\n", 14);
8526 for (j = 0; j < i; j++)
8528 /* stack[] gives the return addresses, whereas we want
8529 the address of the call, so decrease each address
8530 by approximate size of 1 CALL instruction. */
8531 sprintf (buf, "%p\r\n", (char *)stack[j] - sizeof(void *));
8532 if (stderr_fd >= 0)
8533 write (stderr_fd, buf, strlen (buf));
8534 if (errfile_fd >= 0)
8535 write (errfile_fd, buf, strlen (buf));
8537 if (i == BACKTRACE_LIMIT_MAX)
8539 if (stderr_fd >= 0)
8540 write (stderr_fd, "...\r\n", 5);
8541 if (errfile_fd >= 0)
8542 write (errfile_fd, "...\r\n", 5);
8544 if (errfile_fd >= 0)
8545 close (errfile_fd);
8547 abort ();
8548 break;
8555 /* Initialization. */
8558 globals_of_w32fns is used to initialize those global variables that
8559 must always be initialized on startup even when the global variable
8560 initialized is non zero (see the function main in emacs.c).
8561 globals_of_w32fns is called from syms_of_w32fns when the global
8562 variable initialized is 0 and directly from main when initialized
8563 is non zero.
8565 void
8566 globals_of_w32fns (void)
8568 HMODULE user32_lib = GetModuleHandle ("user32.dll");
8570 TrackMouseEvent not available in all versions of Windows, so must load
8571 it dynamically. Do it once, here, instead of every time it is used.
8573 track_mouse_event_fn = (TrackMouseEvent_Proc)
8574 GetProcAddress (user32_lib, "TrackMouseEvent");
8576 monitor_from_point_fn = (MonitorFromPoint_Proc)
8577 GetProcAddress (user32_lib, "MonitorFromPoint");
8578 get_monitor_info_fn = (GetMonitorInfo_Proc)
8579 GetProcAddress (user32_lib, "GetMonitorInfoA");
8580 monitor_from_window_fn = (MonitorFromWindow_Proc)
8581 GetProcAddress (user32_lib, "MonitorFromWindow");
8582 enum_display_monitors_fn = (EnumDisplayMonitors_Proc)
8583 GetProcAddress (user32_lib, "EnumDisplayMonitors");
8586 HMODULE imm32_lib = GetModuleHandle ("imm32.dll");
8587 get_composition_string_fn = (ImmGetCompositionString_Proc)
8588 GetProcAddress (imm32_lib, "ImmGetCompositionStringW");
8589 get_ime_context_fn = (ImmGetContext_Proc)
8590 GetProcAddress (imm32_lib, "ImmGetContext");
8591 release_ime_context_fn = (ImmReleaseContext_Proc)
8592 GetProcAddress (imm32_lib, "ImmReleaseContext");
8593 set_ime_composition_window_fn = (ImmSetCompositionWindow_Proc)
8594 GetProcAddress (imm32_lib, "ImmSetCompositionWindow");
8597 except_code = 0;
8598 except_addr = 0;
8599 #ifndef CYGWIN
8600 prev_exception_handler = SetUnhandledExceptionFilter (my_exception_handler);
8601 #endif
8603 DEFVAR_INT ("w32-ansi-code-page",
8604 w32_ansi_code_page,
8605 doc: /* The ANSI code page used by the system. */);
8606 w32_ansi_code_page = GetACP ();
8608 if (os_subtype == OS_NT)
8609 w32_unicode_gui = 1;
8610 else
8611 w32_unicode_gui = 0;
8613 /* MessageBox does not work without this when linked to comctl32.dll 6.0. */
8614 InitCommonControls ();
8616 syms_of_w32uniscribe ();
8619 #ifdef NTGUI_UNICODE
8621 Lisp_Object
8622 ntgui_encode_system (Lisp_Object str)
8624 Lisp_Object encoded;
8625 to_unicode (str, &encoded);
8626 return encoded;
8629 #endif /* NTGUI_UNICODE */